您的位置:首页 > 其它

POJ 1061 青蛙的约会

2016-05-05 21:06 302 查看
题目链接:http://poj.org/problem?id=1061

题意:我们把这两只青蛙分别叫做青蛙A和青蛙B,并且规定纬度线上东经0度处为原点,由东往西为正方向,单位长度1米,这样我们就得到了一条首尾相接的数轴。设青蛙A的出发点坐标是x,青蛙B的出发点坐标是y。青蛙A一次能跳m米,青蛙B一次能跳n米,两只青蛙跳一次所花费的时间相同。纬度线总长L米。现在要你求出它们跳了几次以后才会碰面。

思路:x + k * m = y + k * n + t * L => k * ( n - m ) + t * L = x - y , n-m 为A,L为B,那么式子就是Ax + By = C的形式,直接用扩展欧几里得。由于范围很大,为了防止越界,我们先将所有系数的公约数除掉,也就是变成ax+by = c/gcd(a,b)的形式。

#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <utility>
using namespace std;

#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)

#define Clean(x,y) memset(x,y,sizeof(x))
#define LL long long
#define ULL unsigned long long
#define inf 0x7fffffff
#define mod %100000007

LL x,y,m,n,L;

LL exgcd(LL a,LL b,LL &x,LL &y)  //返回最大公约数,x,y存的是一组解
{
if(b==0)
{
x=1;
y=0;
return a;
}
int r=exgcd(b,a%b,x,y);
int t=x;
x=y;
y=t-a/b*y;
return r;
}
LL GCD(LL x,LL y)
{
if ( y == 0 ) return x;
return GCD(y,x%y);
}
bool slove(LL x,LL y , LL m , LL n , LL L)
{
LL A = n - m;
LL B = L;
if ( A < 0 ) A+=L;
LL c = x - y;
LL gcd = GCD(A,B);
if ( c % gcd ) return false;
A/=gcd;
B/=gcd;
c/=gcd;
LL xx,yy;
exgcd( A , B , xx , yy );
xx = xx * c % B;
xx = (xx % B + B)%B;
cout<<xx<<endl;
return true;
}

int main()
{
cin>>x>>y>>m>>n>>L;
if ( !slove(x,y,m,n,L) )
puts("Impossible");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: