HDU 2669 Romantic(裸的拓展欧几里得)

Romantic

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


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



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
 
Author
yifenfei
 
Source
 
Recommend
lcy   |   We have carefully selected several similar problems for you:  2668 2674 2671 2670 2672 
 
 1 #include <iostream>  
 2 #include <cstdio>  
 3 #include <cstring>  
 4 #include <cmath>  
 5 #include <vector>  
 6 #include <string>  
 7 #include <queue>  
 8 #include <stack>  
 9 #include <algorithm>  
10 
11 #define INF 0x7fffffff  
12 #define EPS 1e-12  
13 #define MOD 1000000007  
14 #define PI 3.141592653579798  
15 #define N 100000  
16 
17 using namespace std;
18 
19 typedef long long ll;
20 
21 ll e_gcd(ll a, ll b, ll &x, ll &y)
22 {
23     ll d = a;
24     if (b != 0)
25     {
26         d = e_gcd(b, a%b, y, x);
27         y -= a / b * x;
28     }
29     else
30     {
31         x = 1; y = 0;
32     }
33     return d;
34 }
35 
36 ll cal(ll a, ll b, ll c)
37 {
38     ll x, y;
39     ll gcd = e_gcd(a, b, x, y);
40     if (c%gcd != 0) return -1;
41     x *= c / gcd;
42     y *= c / gcd;
43     if (b < 0) b = -b;
44     ll ans = x % b;//最小的x,因为ax+by=c,尽量把ax分给b,多些y,少些x
45     if (ans <= 0) ans += b;
46     return ans;
47 }
48 
49 int main()
50 {
51     ll a, b;
52     while (cin>>a>>b)
53     {
54         ll ans = cal(a, b, 1);
55         if (ans == -1) printf("sorry
");
56         else printf("%I64d %I64d
", ans, (1 - ans * a) / b);
57     }
58     return 0;
59 }
原文地址:https://www.cnblogs.com/caiyishuai/p/8454553.html