POJ 1061 青蛙的约会

先说一下大概题意:有两只青蛙,一只在坐标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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值