您的位置:首页 > 其它

POJ 1061 青蛙的约会

2015-07-28 21:38 218 查看
先说一下大概题意:有两只青蛙,一只在坐标x,另一直在坐标y,青蛙x一次跳跃可以前进m单位距离,青蛙y一次跳跃可以前进n单位的距离,两青蛙都在同一纬度,该纬度长度为L。两只青蛙同方向同时跳啊跳,问你最少跳多少次,它们才可以相遇,如果不能相遇,输出impossble

分析:

假设跳了T次以后,

青蛙1的坐标便是x+m*T,青蛙2的坐标为y+n*T。

它们能够相遇的情况为(x+m*T)-(y+n*T)==P*L,

其中P为某一个整数,

变形一下得到(n-m)*T+P*L==x-y

我们设a=(n-m),b=L,c=x-y,T=x,P=y.于是便得到ax+by==c。

直接套用扩展欧几里得函数,得到一组解x,y。

由于问题是问最少跳多少次,于是只有x是我们需要的信息。

那么再想,x是最小的吗?

答案是可能不是!那么如何得到最小解呢?

我们考虑x的所有解的式子: x=x0+b/d*t。

x0是我们刚刚求到的,很显然右边是有个单调函数,

当t为某一个与x正负性质相反的数时,可以得到最小的x。

令x的正负性质为正,那么x=x0-b/d*t1 (t1==-t)。

这里得到的x可能是负数,如果是负数,

我们再为它加上一个b/d即是所求答案了!

#include <iostream>
#include <sstream>
#include <iomanip>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <string>
#include <numeric>
#include <algorithm>
#include <functional>
#include <iterator>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <complex>
#include <ctime>
#define LL long long
using namespace std;

LL x,y,m,n,L,a,b,c,d;

LL gcd(LL a,LL b)
{
LL t,d;
if(b == 0)
{
x = 1;
y = 0;
return a;
}
d = gcd(b,a % b);
t = x;
x = y;
y = t - a / b * y;
return d;
}

int main()
{

while(scanf("%I64d %I64d %I64d %I64d %I64d",&x,&y,&m,&n,&L) != EOF)
{
a = n - m, b = L, c = x - y;
d = gcd(a,b);
if(c % d != 0)
{
printf("Impossible\n");
continue;
}
else
{
x = x * c / d;
LL k = d * x / b;
k = x - b / d * k;
if(k < 0)
k += b / d;
printf("%I64d\n",k);

}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: