洛谷P1516 青蛙的约会

题目传送门

思路

其实就是推一波式子,有手就行,主要是刚学会(exgcd),过来记录一下细节。

代码

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<queue>
using namespace std;
typedef long long int ll;
ll x,y,m,n,l,ans,k;
ll exgcd(ll a,ll b,ll &x,ll &y){
	if(b==0){
		x=1;
		y=0;
		return a;
	}
	ll d=exgcd(b,a%b,x,y);
	ll z=x;
	x=y;
	y=z-(a/b)*y;
	return d;
}
int main()
{
	scanf("%lld%lld%lld%lld%lld",&x,&y,&m,&n,&l);
	ll b=n-m,a=x-y;//推式子的结果
	if(b<0){//exgcd中两个数都要是正整数才行,所以要特判
		b=-b;
		a=-a;
	}
	ll gc=exgcd(b,l,ans,k);
	if(a%gc!=0){
		printf("Impossible
");//如果没有解则输出不行
	}
	else{
		printf("%lld
",(ans*(a/gc)%(l/gc)+l/gc)%(l/gc));//首先求出一组特解,就是ans*(a/gc),然后通过加减l/gc来得到最小正整数解
	}
	return 0;
}
原文地址:https://www.cnblogs.com/57xmz/p/13873957.html