题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2669
Romantic
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4179 Accepted Submission(s): 1745
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
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 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)
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
10 44
34 79
Sample Output
2 -3
sorry
7 -3
sorry
7 -3
Author
yifenfei
题解: 扩展欧几里得算法,数论内容,简单证明一下,gcd(x,y,&a,&b)要求的是ax+by = gcd(x,y);
在求出gcd(y,x%y,a1,b1)的情况下,即a1y + b1x%y = gcd(x,y);
有a1y + b1(x-(x/y)*y) = gcd(x,y) 有a = b1, b = a1-b1(x/y);
那么如果写成gcd(y,x%y, b1,a1) 那么在递归回溯的时候有a = a1,b = b1-a1(x/y)那么就可以不对a再处理,b = b-a(x/y) 即可
这道题要求了x必需是正数,那么就在x的基础上每次都加上一组数,使得x变大,y 变小,使得ax + by = k 不变,既设x = x+x', y = y+y';
那么有ax'+by' = 0; 所以可以取x' = b, y' = -a;
下面是代码:
#include<cstdio>
#include<iostream>
using namespace std;
#define ll long long
ll gcd(ll a, ll b)
{
return b==? a: gcd(b,a%b);
}
ll extend_gcd(ll x, ll y, ll &a, ll &b)
{
if(y==){
a = ;
b = ;
return x;
}
ll d = extend_gcd(y, x%y, b, a);
b = b - (x/y)*a;
return d;
}
int main()
{
ll a, b;
while(~scanf("%I64d%I64d",&a,&b))
{
if(gcd(a,b)!=)
puts("sorry");
else {
ll x, y;
extend_gcd(a,b,x,y);
while(x<=){
x+=b;
y-=a;
}
printf("%I64d %I64d\n",x,y);
}
}
return ;
}