P1516 青蛙的約會

andyc_03發表於2020-10-30

 

(n-m)T+LP=X-Y

用exgcd去求解這個方程,然後找到最小正整數解即可

 

程式碼

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll x,y,m,n,l;
void exgcd(ll a,ll b, ll &d, ll &x,ll &y)
{
	if(!b)
	{
		x=1; y=0; d=a;
		return;
	}
	exgcd(b,a%b,d,x,y);
	ll t=x; x=y; y=t-a/b*y;
}
int main()
{
	freopen("frog.in","r",stdin);
	freopen("frog.out","w",stdout);
	ll a,b,d;
	while(scanf("%lld%lld%lld%lld%lld",&x,&y,&m,&n,&l)==5 && x!=EOF)
	{
		if(n<m) swap(n,m),swap(x,y);
		exgcd(n-m,l,d,a,b);
		if((x-y)%d!=0 || m==n)
			printf("Impossible\n");
		else printf("%lld\n",(a*(x-y)/d%(l/d)+(l/d))%(l/d));
	}
	
	return 0;
}

 

相關文章