青蛙的约会
题目链接:POJ - 1061题意:两只青蛙网恋了, 决定见一面, 于是相约同时向西跳, 由于地球是圆的, 所以其实它们是在绕圈跳, A每次可以跳m个单位, B每次可以跳n个单位, A起始坐标是x, B起始坐标是y,这个圈的轨道长度L;如下图所示:
问两只青蛙能不能见面;若能输出最少跳几步, 反之输出"Impossible";
设两只青蛙跳了t步后相见, 则有:(x+m*t)%L=(y+n*t)%L->x%L+m*t%L=y%L+n*t%L->m*t%L-n*t%L=y%L-x%L->t*(m-n)%L=(y-x)%L->t*(m-n)≡(y-x)modL->a*t*(m-n)-b*L=y-x;
用扩展欧几里得解方程即可;
设两只青蛙跳了t步后相见, 则有:(x+m*t)%L=(y+n*t)%L->x%L+m*t%L=y%L+n*t%L->m*t%L-n*t%L=y%L-x%L->t*(m-n)%L=(y-x)%L->t*(m-n)≡(y-x)modL->a*t*(m-n)-b*L=y-x;
用扩展欧几里得解方程即可;
#include <iostream>
#include <algorithm>
#include <string.h>
#include <stdio.h>
#include <math.h>
using namespace std;
const long long inf = 0x3f3f3f3f;
long long exgcd(long long a, long long b, long long &x, long long &y){
if(b==0){
x=1;
y=0;
return a;
}
long long r=exgcd(b, a%b, x, y);
long long t=x;
x=y;
y=t-a/b*y;
return r;
}
int main(){
long long x, y, m, n, L;
scanf("%lld%lld%lld%lld%lld", &x, &y, &m, &n, &L);
long long a, b;
long long r=exgcd(n-m, L, a, b);
long long z=x-y;
//cout << r << endl;
//cout << z << endl;
if(z%r) printf("Impossible\n");
else{
L/=r;
printf("%lld\n", ((z/r*a)%L+L)%L);//这里这个输出也是不明所以……;
}
return 0;
}