您的位置:首页 > 其它

hdu2669 Romantic(扩展欧几里得)

2016-11-20 22:09 267 查看
http://acm.hdu.edu.cn/showproblem.php?pid=2669

题意:求ax+by=1的最小整数解,其中a为非负数。

思路:确保x是非负数,在a、b、c不变的情况下,若x是负数,只有增大a而减小b。而x和y分别有系数a和b,那么中间用ab作为媒介,ax+ab+by-ab = a(x+b)+b(y-a),每次对x和y操作直到满足条件即可。

#include <stdio.h>
#include <algorithm>

using namespace std;

typedef long long ll;

int ext_gcd(ll a, ll b, ll &x, ll &y)//添加引用确保同步更新
{
if(b == 0)
{
x = 1;
y = 0;
return a;
}
ll d = ext_gcd(b, a%b, x, y);
ll tmp = x;
x = y;
y = tmp - (a/b)*y;
return d;
}

int main()
{
// freopen("in.txt", "r", stdin);
ll a, b, c, d;
ll x, y, m, n, l;
while(~scanf("%lld%lld", &a, &b))
{
d = ext_gcd(a, b, x, y);
if(1%d != 0)
{
printf("sorry\n");
continue;
}
while(x < 0)
{
x+=b;
y-=a;
}
printf("%lld %lld\n", x, y);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hdu