zoukankan      html  css  js  c++  java
  • hdu_2669 Romantic(扩展欧几里得)

    题目链接: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



    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
    题解: 扩展欧几里得算法,数论内容,简单证明一下,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;
    下面是代码:
     1 #include<cstdio>
     2 #include<iostream>
     3 using namespace std;
     4 #define ll long long
     5 ll gcd(ll a, ll b)
     6 {
     7     return b==0? a: gcd(b,a%b);
     8 }
     9 ll extend_gcd(ll x, ll y, ll &a, ll &b)
    10 {
    11     if(y==0){
    12         a = 1;
    13         b = 0;
    14         return x;
    15     }
    16     ll d = extend_gcd(y, x%y, b, a);
    17     b = b - (x/y)*a;
    18     return d;
    19 }
    20 int main()
    21 {
    22     ll a, b;
    23     while(~scanf("%I64d%I64d",&a,&b))
    24     {
    25         if(gcd(a,b)!=1)
    26             puts("sorry");
    27         else {
    28             ll x, y;
    29             extend_gcd(a,b,x,y);
    30             while(x<=0){
    31                 x+=b;
    32                 y-=a;
    33             }
    34         printf("%I64d %I64d
    ",x,y);
    35         }
    36     }
    37     return 0;
    38 }
  • 相关阅读:
    c++
    zjoi 力
    poj 3415
    [SDOI2014]旅行
    模板测试
    [WC2006]水管局长
    HDU5730
    [NOI2014]魔法森林
    [NOI2012]骑行川藏(未完成)
    [NOI2012]随机数生成器
  • 原文地址:https://www.cnblogs.com/shanyr/p/5278667.html
Copyright © 2011-2022 走看看