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 }
  • 相关阅读:
    vue路由跳转时更改页面title
    vue:axios二次封装,接口统一存放
    https://github.com/simple-uploader/vue-uploader/blob/master/README_zh-CN.md
    基于vue-simple-uploader封装文件分片上传、秒传及断点续传的全局上传插件
    前端三大主流框架的对比React、Vue、Angular 所谓是是三分天下
    React前端框架以及和Vue的对比
    Win10远程桌面:身份验证错误要求的函数不受支持的解决方法
    经典案例模块——20200404
    流的新认知
    网络编程
  • 原文地址:https://www.cnblogs.com/shanyr/p/5278667.html
Copyright © 2011-2022 走看看