您的位置:首页 > 其它

POJ 1061 青蛙的约会(扩展欧几里德)

2016-05-31 01:10 246 查看
题目链接:

POJ 1061 青蛙的约会

题意:

规定纬度线上东经0度处为原点,由东往西为正方向,单位长度1米,这样就得到了一条首尾相接的数轴。

设青蛙A的出发点坐标是x,青蛙B的出发点坐标是y。青蛙A一次能跳m米,青蛙B一次能跳n米,两只青蛙跳一次所花费的时间相同且都是从东往西跳。纬度线总长L米。现在要你求出它们跳了几次以后才会碰面。

分析:

假设两只青蛙跳了k次相遇。则:(x + k * m) % L = (y + k * n) % L.

也就是:(x + k * m) - (y + k * n) = k’ * L,

移项即为:(m - n) * k - k’ * L = y - x。

相当于求解此不定方程的最小正整数解k。利用扩展欧几里德先计算(m - n) * k - k’ * L = gcd(m, n)的最小解k.

然后判断y - x是否为gcd(m - n, L)的倍数,如果不是倍数则无解。否则先将k扩大(y - x) / gcd(m - n, L)倍。

因为(m - n) * k - k’ * L = y - x的通解(kk, kk’)满足:

kk = (k + t * (L / d)), kk’ =(k’ - t * (m - n) / d),t为整数,d = gcd(m - n, L);

那么求k的最小正整数解kk:令r = L / d, kk = (k % r + r ) % r;

还要注意需要将系数变正!即m - n > 0!

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <climits>
#include <cmath>
#include <ctime>
#include <cassert>
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);
using namespace std;
typedef long long ll;

ll ex_gcd(ll a, ll b, ll& xx, ll& yy)
{
if(b == 0){
xx = 1, yy = 0;
return a;
}
ll d = ex_gcd(b, a % b, yy, xx);
yy -= a / b * xx;
return d;
}

int main()
{
ll x, y, n, m, L, xx, yy;
while(~scanf("%lld%lld%lld%lld%lld", &x, &y, &m, &n, &L)){

if(m < n){
swap(n, m);
swap(x, y);
}

ll d = ex_gcd(m - n, L, xx, yy);
if((y - x) % d != 0) printf("Impossible\n");
else {
xx *= ((y - x) / d);
//通解满足:xx' = (xx + c * (L / d)), yy' =(yy - c * (m - n) / d),c为整数;
ll r = L / d;
xx = (xx % r + r) % r; //最小正整数解
printf("%lld\n", xx);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息