您的位置:首页 > 其它

HDU-2669 拓展欧几里得

2017-07-01 08:11 239 查看
题目一大推 其实都没用,昨天训练赛看到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) 

Outputoutput 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


#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <math.h>
#include <stack>
#define LL long long
using 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: