【扩展欧几里德】POJ 1061 + zoj 2657

[size=medium][url]http://poj.org/problem?id=1061[/url]
[url]http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1657[/url]

[color=red]两题一模一样,只是无解时输出情况不同[/color]
[color=brown]首先由题意有【x+ms与y+ns建立等价关系,设次数为s】:
x+ms ≡ (y+ns)(mol L)
->(x+ms)%L = (y+ns)%L
->((x+ms) - (y+ns))%L = 0
->(x+ms) - (y+ns) = k*L
化简得:
k*L + (n-m)*s = x-y
令a = L,b = n-m,n = x-y得
ak + bs = n;[其中k,s为未知数,形如ax + by = n[/color]

[b][color=red]Egcd解析:[/color][/b](Egcd是用来解ax+by=gcd(a,b)的(a,b是常数))
[img]http://dl.iteye.com/upload/attachment/531208/565a1d2f-6c6f-38f3-a10b-f648684dbd3f.png[/img]

[color=blue]解方程步骤:
①:令d = gcd(a, b)
②:若n%d != 0,则无解
③:方程两边同时除以d ,得到a'k + b's = n'
④:用扩展欧几里德Egcd求出a'k + b's = 1的解s
⑤:得到的[s*n']就是方程的一组解
⑥:得到[b][u]最小非负整数解[/u][/b],模a+a模a【求b的模a,求a的模b, 为什么?请读者自己思考】[/color]
[/size]


#include <iostream>
#include <algorithm>
#include <string>
//#include <map>
#include <queue>
#include <vector>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
//#include <ctime>
#include <ctype.h>
using namespace std;
#define LL long long
#define inf 0x3fffffff

LL gcd (LL a, LL b)
{
return b ? gcd (b, a%b) : a;
}

void Egcd (LL a, LL b, LL &x, LL &y)
{
if (b == 0)
{
x = 1, y = 0;
return ;
}
Egcd (b, a%b, x, y);
LL tp = x;
x = y;
y = tp - a/b*y;
}

int main()
{
LL xx, yy, a, b, x, y, L, n, M, N, d;
while (~scanf ("%lld%lld%lld%lld%lld", &xx, &yy, &M, &N, &L))
{
a = L;
b = N - M;
n = xx - yy;
d = gcd (a, b);
if (n % d != 0)
{
puts ("Impossible");
continue;
}
a /= d;
b /= d;
n /= d;
Egcd (a, b, x, y);
y *= n;
if (a < 0) a = -a; //周期是正的
y = (y % a + a) % a;
printf ("%lld\n", y);
}
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值