首页 > 其他 > 详细

HD2699Romantic(裸扩展欧几里得)

时间:2016-02-22 15:23:54      阅读:251      评论:0      收藏:0      [点我收藏+]

Romantic

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


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
题意:给出a,b; 求满足 ax + by = 1的 x 和 y值,其中x非负,多解时输出x最小的那一个
 
直接按照扩展欧几里得求解就ok了,x的通解: x = x0 + b / d * t,其中b / d 都正数,x 和 t成正比,当x0为正数的时候 t == 0,有最小值;当x0为负数的时候,x最小就是0,与横轴相交,所以可以求出 x0 + b / t * t = 0时候的 t,因为此时 t是整数,不一定是准确相交的那一个点,所以当前的x可能是负数,如果为负数,t++,取下一个整数点
技术分享
 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstring>
 4 #include <cstdio>
 5 using namespace std;
 6 int a,b,x,y,d;
 7 int gcd(int a, int b)
 8 {
 9     if(b == 0)
10     {
11         x = 1;
12         y = 0;
13         return a;
14     }
15     d = gcd(b, a % b);
16     int temp = x;
17     x = y;
18     y = temp - a / b * y;
19     return d;
20 }
21 int main()
22 {
23     while(scanf("%d%d", &a, &b) != EOF)
24     {
25         d = gcd(a, b);
26         if(1 % d)   // 如果c % gcd == 1就无解
27         {
28             printf("sorry\n");
29             continue;
30         }
31         x = x / d;  // 特解
32         y = y / d;
33         if(x > 0)  // x 大于0直接输出
34             printf("%d %d\n",x, y);
35         else
36         {
37             int t = (-1) * x / b * d;
38             //cout<<x<<" "<<b<<" "<<d<<endl;
39             int k = x + b / d * t;  //当前的t下的x值
40             if(k < 0) 
41             {
42                 t++; //当前的t所求的x为负,取下一个点
43 
44             }
45             printf("%d %d\n", x + b / d * t, y - a / d * t);
46 
47         }
48     }
49     return 0;
50 }
View Code

 

  

 

HD2699Romantic(裸扩展欧几里得)

原文:http://www.cnblogs.com/zhaopAC/p/5206891.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!