青蛙的约会
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 102326 | Accepted: 19803 |
Description
我们把这两只青蛙分别叫做青蛙A和青蛙B,并且规定纬度线上东经0度处为原点,由东往西为正方向,单位长度1米,这样我们就得到了一条首尾相接的数轴。设青蛙A的出发点坐标是x,青蛙B的出发点坐标是y。青蛙A一次能跳m米,青蛙B一次能跳n米,两只青蛙跳一次所花费的时间相同。纬度线总长L米。现在要你求出它们跳了几次以后才会碰面。
Input
Output
Sample Input
1 2 3 4 5
Sample Output
4
题意是一个收尾相接的数轴,长度为l,A和B在数轴上x和y点,x和y可能相同,也可能不同,他们具有速度m和n,只有两者坐标完全相同的时候他们才会相遇,问最短什么时候相遇。
一个追及问题,如果我们直接列公式有(n - m) * t + p * l = x - y,然后直接爆搜p的值,那么倘若x 和 y差值极大,n 和 m差值极小,就会运算10的九次幂级别的运算次数,导致超时,所以需要优化求解。
抽象出列出的公式为ap + bq = c,其中a = n - m, b = l, c = x - y。然后我们需要这个公式:
若有ap+bq=c成立,则有c % gcd(a, b) = 0.
所以在这里就可以把无解的点输出Impossible,只要判断c可否被gcd(a,b)除开就好。其中gcd直接用辗转相除法解决即可。
之后我们在等式两边都除以gcd(a,b)化简这个式子,得到a1p + b1q = c1
此时直接通过扩展欧几里得算法(extend_gcd),算出p和q的解。这里用到我们的第二个公式:
如果ap + bq = c算出解p0,q0,那么就可以得到所有的解 p = p0 + b * t,q = q0 - a * t
通过上式,我们就可以算出t,有最终解t = (p0 % b + b) % b,这个括号中加的一个b是为了保证在p != 0的时候出现的负值的情况,代码如下:
/************************************************************************* > File Name: 青蛙的约会.cpp > Author: ZhangHaoRan > Mail: chilumanxi@gmail.com > Created Time: 2016年03月11日 星期五 06时57分53秒 ************************************************************************/ #include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<string> #include<vector> #include<set> #include<map> #include<queue> #include<list> #include<algorithm> using namespace std; long long gcd(long long a, long long b){ if(b == 0){ return a; } else return gcd(b, a % b); } void extend_gcd(long long a, long long b, long long &x, long long &y){ if(a == 0 && b == 0) return ; if(b == 0){ x = 1; y = 0; return ; } extend_gcd(b, a % b, x, y); long long int t = x; x = y; y = t - a / b * y; return ; } int main(void){ long long x, y, m, n, l; cin >> x >> y >> m >> n >> l; long long a = n - m; long long b = l; long long c = x - y; long long p, q; long long int d = gcd(a, b); if(c % d){ cout << "Impossible" << endl; return 0; } a /= d; b /= d; c /= d; extend_gcd(a, b, p, q); p *= c; long long ans = (p % b + b) % b; cout << ans << endl; return 0; }
查看原文:http://chilumanxi.org/2016/03/11/poj-1061-%e9%9d%92%e8%9b%99%e7%9a%84%e7%ba%a6%e4%bc%9a/