POJ 1061 青蛙的约会

来源:互联网 发布:java中scanner用法案例 编辑:程序博客网 时间:2024/05/21 07:13

题目链接: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 %100000007LL 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;}




0 0
原创粉丝点击