HDU-2669 拓展欧几里得

来源:互联网 发布:天猫和淘宝是什么关系 编辑:程序博客网 时间:2024/06/05 08:21

题目一大推 其实都没用,昨天训练赛看到a*x+b*y= 1;就想到了拓展欧几里得,直接写就可以,在取结果的时候注意,需要x = (x % b + b)%b ; 防负数就可以了

昨天写这个模板还是写的有点慢~~还需要更加熟练
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 X*a + Y*b = 1. If no such answer print "sorry" instead. 

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 5110 4434 79

#include <iostream>#include <cstdio>#include <cstring>#include <cstdlib>#include <algorithm>#include <vector>#include <map>#include <math.h>#include <stack>#define LL long longusing namespace std;const int INF = 0x3f3f3f3f;int dir[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};LL exgcd(LL n ,LL m,LL &x,LL &y){    if (m == 0)    {        x = 1;        y = 0;        return n;    }    LL g = exgcd(m, n % m, x, y);    LL t = x - n / m * y;    x = y;    y = t;    return g;}int main(){    LL a,b,x,y;    while(cin>>a>>b)    {        LL d = exgcd(a,b,x,y);        if(1 % d)            cout<<"sorry"<<endl;        else        {            x=(x%b+b)%b;            y=(1-a*x)/b;            cout<<x<<" "<<y<<endl;        }    }    return 0;}