hdu2669-Romantic-(扩展欧几里得定理)

Romantic

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 10883    Accepted Submission(s): 4610


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

hdu2669-Romantic-(扩展欧几里得定理)

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)   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   翻译:输入a和b,找到x和y满足ax+by=1,x为正数。 分析:显然是扩展欧几里得定理的模板题,当gcd(a,b)=1时,有解,然而扩欧模板解出来是特解,不能保证x为正数,需要遍历通解。通解公式:x = x0 + (b/gcd)*t; y = y0 + (a/gcd)*t; 注意:为什么是b/gcd和a/gcd,而不是b和a? a(x+b*t/gcd) + b(y-a*t/gcd) = gcd; ax + a*b*t/gcd + by - b*a*t/gcd = gcd = ax + by; 对于x = x0 + b*t和y = y0 - a*t; a(x+bt) + b(y-at) = gcd ax+abt + by-abt = gcd = ax + by 显然b/gcd比b更小,通解找得全面一些。
 1 #include<stdio.h>
 2 #include<iostream>
 3 #include<algorithm>
 4 #include<cstring>
 5 #include<math.h>
 6 #include<string>
 7 #define ll long long
 8 #define inf 0x3f3f3f3f
 9 using namespace std;
10 // ax + by = gcd(a,b)
11 ll exgcd(ll a, ll b, ll &x, ll &y)//扩展欧几里德定理
12 {
13     if(b==0)//终有一次a%b传进来是0,递归出口
14     {
15         x=1;y=0;
16         return a;
17     }
18     ll q=exgcd(b,a%b,y,x);
19     //最终递归出来,y1=1,x1=0
20     y=y-(a/b)*x;
21     //后面的y相当于下一个递归的x2,x相当于下一个递归的y2,符合推导公式
22     //x1=y2;   y1=x2-[a/b]*y2;
23     return q;
24 }
25 
26 int main()
27 {
28     ll a,b;
29     while(scanf("%lld %lld",&a,&b)!=EOF)
30     {
31         ll x,y;
32         ll gcd=exgcd(a,b,x,y);
33         if(gcd==1)
34         {
35             while(x<0)
36             {
37                 x=x+b;
38                 y=y-a;
39             }
40             printf("%lld %lld\n",x,y);
41         }
42         else printf("sorry\n");
43     }
44     return 0;
45 }

 

上一篇:AI之Robot:带你玩转机器人&DIY机器人——让你成为机器人的真正主人


下一篇:Patty said the private romantic curls stunning audience try modeling madness