hdoj 2669 Romantic 【扩展欧几里得 求解最小非负解】



Romantic

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


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

hdoj 2669 Romantic 【扩展欧几里得 求解最小非负解】_第1张图片 

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
 



题意:已知x*a + y*b = 1,给出a和b,让你求出最小的非负x以及对应的y,无解输出sorry。


思路:扩展欧几里得求出x和y,根据定理——gcd(x, y) == 1,ax == c(mod b)在[0, b-1]上有解。

转化式子x*a + b*y = 1 -> a*x == 1 (mod b)。

对欧几里得求出的x,最小的非负x = (x%b + b)%b,然后代入求出y。


#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <map>
#include <string>
#include <vector>
#define lson o<<1|1, l, mid
#define rson o<<1, mid+1, r
#define ll o<<1
#define rr o<<1|1
#define INF 0x3f3f3f3f
#define eps 1e-8
#define debug printf("1\n")
#define MAXN 1010
#define MAXM 100000
#define LL long long
#define CLR(a, b) memset(a, (b), sizeof(a))
#define W(a) while(a--)
#define Ri(a) scanf("%d", &a)
#define Ri2(a, b) scanf("%d%d", &a, &b)
#define Pi(a) printf("%d\n", (a))
#define Pi2(a, b) printf("%d %d\n", a, b)
#define Rl(a) scanf("%lld", &a)
#define Rl2(a, b) scanf("%lld%lld", &a, &b)
#define Pl(a) printf("%lld\n", (a))
#define Pl2(a, b) printf("%lld %lld\n", a, b)
#define Rs(a) scanf("%s", a)
#define Rs2(a, b) scanf("%s%s", a, b)
#define Ps(a) printf("%s\n", (a))
#define Ps2(a, b) printf("%s %s\n", a, b)
#define FOR(i, l, r) for(int i = (l); i <= (r); i++)
#define FOR1(i, l, r) for(int i = (l); i < (r); i++)
#define MOD 1000000007
using namespace std;
LL gcd(LL a, LL b){
    return b == 0 ? a : gcd(b, a%b);
}
void exgcd(LL a, LL b, LL &d, LL &x, LL &y)
{
    if(b == 0) {d = a, x = 1, y = 0;}
    else
    {
        exgcd(b, a%b, d, y, x);
        y -= x * (a/ b);
    }
}
int main()
{
    LL a, b;
    while(~Rl2(a, b))
    {
        if(gcd(a, b) != 1)
        {
            printf("sorry\n");
            continue;
        }
        LL d, x, y;
        exgcd(a, b, d, x, y);
        x = (x % b + b) % b;
        y = (1 - a*x) / b;
        Pl2(x, y);
    }
    return 0;
}


你可能感兴趣的:(hdoj 2669 Romantic 【扩展欧几里得 求解最小非负解】)