hdu 2669 Romantic【扩展欧几里得】(模板题)

<题目链接>

题目大意:

Now tell you two nonnegative integer a and b. Find the nonnegative integer X and integer Y to satisfy X*a + Y*b = 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. 

#include<cstdio>

using namespace std;
int exgcd(int a,int b,int &x,int &y)
{
    if(b==0)
    {
        x=1;
        y=0;
        return a;
    }
    int  r=exgcd(b,a%b,x,y);
    int t=x;
    x=y;
    y=t-a/b*y;
    return r;
}

int main()
{
    int a,b,x,y,m;
    while(scanf("%d%d",&a,&b)!=EOF)
    {
        m=exgcd(a,b,x,y);
        if(m==1)         //因为题目要求gcd(a,b)要为1
        {
            while(x<0)      //exgcd求出的x,y是通解,由于题目说了,x要求非负,所以这里要对x,y的值做一些调整,但是为什么是x+=b,y-=a啊?
            {               //而且,如果x由exgcd一开始求出来的就是正数,怎么保证这个x是符合条件的非负整数中的最小值呢?
                x+=b;
                y-=a;
            }
            printf("%d %d\n",x,y);
        }
 
        else
            printf("sorry\n");
    }
    return 0;
}

2018-08-12

猜你喜欢

转载自www.cnblogs.com/00isok/p/9462814.html