• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

  • 博客园
  • 联系
  • 订阅
  • 管理

View Post

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\n");
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\n", x, y);
58         }
59     }
60 
61     return 0;
62 }

 

 

posted on 2016-08-07 20:24  tony-cao  阅读(170)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3