「POJ1061」青蛙的约会 (扩展欧几里德+同余方程)

题意


两数在一个首尾相连的数轴上,长度为\(l\)速度为\(m\)\(n\),起始点为\(x\),\(y\),问能否在某一刻相遇,如果能,输出最少需要的时间,否则输出Impossible

思路


跳第\(i\)次时,两个数分别在\((x+m\times i) \mod l\)\((y+n\times i) \mod l\)

相等就是$(x+m\times i) \equiv $$(y+n\times i)$ \((\)\(\mod l)\)

\(\operatorname{exgcd}\)求解即可

最后注意负数,一直加模数就可以了

Code

#include<bits/stdc++.h>
#define int long long
using namespace std;
int exgcd(int a,int b,int &x,int &y)
{
	if(!b)
	{
		x=1;
		y=0;
		return a;
	}
	int d=exgcd(b,a%b,y,x);
	y-=a/b*x;
	return d;
}
int x,y,n,m,l;
int t1,t2;
signed main()
{
	ios::sync_with_stdio(0);
	cin>>x>>y>>m>>n>>l;
	int t=exgcd(n-m,l,t1,t2);
	if((x-y)%t)
	{
		cout<<"Impossible";
		return 0;
	}
	t1*=(x-y)/t;
	while(t1<0) t1+=l;
	cout<<(t1+l)%l;
	return 0;
}
posted @ 2023-08-21 15:38  inlinexhx  阅读(12)  评论(0编辑  收藏  举报