zoukankan      html  css  js  c++  java
  • HDU 2669

    题目大意:

      已知线性方程ax+by=1; 输入a, b的值, 要求输出整数解x, y的值(输出x, y的最小整数解), 若没有解, 输出"sorry".

     
    分析:
      求线性方程的解用扩展欧几里得算法,令gcd(a,b)=d, 如果1是d的倍数表示方程有解, 否则无解.
     
     
     
     
     
    代码如下:
     
     
     
     
     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cstring>
     4 #include <fstream>
     5 #include <ctime>
     6 #include <cmath>
     7 #include <cstdlib>
     8 #include <algorithm>
     9 #include <set>
    10 #include <map>
    11 #include <list>
    12 #include <stack>
    13 #include <queue>
    14 #include <iterator>
    15 #include <vector>
    16 
    17 using namespace std;
    18 
    19 #define LL long long
    20 #define INF 0x3f3f3f3f
    21 #define MOD 1000000007
    22 #define MAXN 10000010
    23 #define MAXM 1000010
    24 
    25 
    26 LL extend_gcd(LL a, LL b, LL &x, LL &y)
    27 {
    28     if(b == 0)
    29     {
    30         x = 1;
    31         y = 0;
    32         return a;
    33     }
    34     else
    35     {
    36         LL r = extend_gcd(b, a%b, y, x);
    37         y -= x*(a/b);
    38         return r;
    39     }
    40 }
    41 
    42 
    43 int main()
    44 {
    45     int a, b;
    46     while(scanf("%d%d", &a, &b)==2)
    47     {
    48         LL t, p;
    49         LL ans = extend_gcd(a, b, t, p);
    50         if(1%ans)
    51             printf("sorry
    ");
    52         else
    53         {
    54             LL x = 1*t/ans; //特解
    55             x = (x%(b/ans)+(b/ans))%(b/ans);    //最小整数解
    56             LL y = (1-a*x)/b;
    57             printf("%lld %lld
    ", x, y);
    58         }
    59     }
    60 
    61     return 0;
    62 }
     
  • 相关阅读:
    Floyd_Warshall算法
    Bellman_Ford算法
    深度优先搜索
    广度优先搜索
    贪心算法_活动选择
    动态规划_0-1背包问题
    算法导论_动态规划_最长回文子序列
    算法导论_动态规划_最长公共子序列
    动态规划解决分割问题
    2016 Google中国开发者大会游记
  • 原文地址:https://www.cnblogs.com/xl1164191281/p/4748741.html
Copyright © 2011-2022 走看看