Problem Description
The Sky is Sprite.
The Birds is Fly in the Sky.
The Wind is Wonderful.
Blew Throw the Trees
Trees are Shaking, Leaves are Falling.
Lovers Walk passing, and so are You.
…………………………..Write in English class by yifenfei

Girls are clever and bright. In HDU every girl like math. Every girl like to solve math problem!
Now tell you two nonnegative integer a and b. Find the nonnegative integer X and integer Y to satisfy Xa + Yb = 1. If no such answer print “sorry” instead.

Input
The input contains multiple test cases.
Each case two nonnegative integer a,b (0<a, b<=2^31)

Output
output nonnegative integer X and integer Y, if there are more answers than the X smaller one will be choosed. If no answer put “sorry” instead.

Sample Input
77 51 10 44 34 79

Sample Output
2 -3 sorry 7 -3
 
求解X*a + Y*b = 1,已知a,b,求x和y。典型的扩展欧几里得算法。
函数
long long exgcd(long long a,long long b,long long &x,long long &y)
直接就是模板,求解x,y。
代码:

#include <iostream>

using namespace std;
long long exgcd(long long a,long long b,long long &x,long long &y)
{
    long long r,t;
    if(b==0)
    {
        x=1;
        y=0;
        return a;
    }
    r=exgcd(b,a%b,x,y);
    t=x;
    x=y;
    y=t-a/b*y;
    return r;
}
int main()
{
    long long a,b;
    while(cin>>a>>b)
    {
       long long  x,y;
       long long d=exgcd(a,b,x,y);
       if(d!=1)
        cout<<"sorry"<<endl;
       else
       {
            long long tx;
            tx=x;
            x=(x%b+b)%b;//确保x为正数
            y=(1-a*x)/b;
            cout<<x<<" "<<y<<endl;
       }
    }
}
0
Posted in ACM

Leave a Comment:

电子邮件地址不会被公开。