nefu 84 ( 拓展欧几里德模板题 )


**链接:****传送门 **

思路:拓展欧几里德模板题,设大圣至少翻转 t 次,大圣起始位置为 x ,大圣目标位置为 y + n * s ( 大圣到达目标位置 y 可能需要多圈,所以用 s 来表示圈数 ),因为只能逆时针翻转所以可以得到一个方程 x + D * t = y + n * s ( 使用D与d区分 ),将方程转换一下可以得到 D * t + n * s = y - x,求出 t 的最小正整数解即可,拓欧模板。


/*************************************************************************
    > File Name: nefu84.cpp
    > Author:    WArobot 
    > Blog:      http://www.cnblogs.com/WArobot/ 
    > Created Time: 2017年05月20日 星期六 15时25分01秒
 ************************************************************************/

#include<cstdio>
using namespace std;

#define ll long long
// 拓展欧几里德 
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 tmp = x;
	x = y;	y = tmp - a/b * y;
	return d;
}
int main(){
	ll T , n , D , x , y , t , s;
	scanf("%lld",&T);
	while(T--){
		scanf("%lld%lld%lld%lld",&n,&D,&x,&y);
		ll c = y - x;
		ll d = exgcd( D , n , t , s );
		if( c%d != 0 )	printf("Impossible
");
		else{
			ll ans = t;
			ans = t*(c/d);
			ans = ( ans%(n/d) + (n/d) ) % (n/d);
			printf("%lld
",ans);
		}
	}
	return 0;
}
原文地址:https://www.cnblogs.com/WArobot/p/6882286.html