码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 1061

时间:2014-08-27 16:05:17      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:blog   os   使用   io   div   log   amp   sp   on   

胡乱写一下,竟然是一次同余方程的内容。

a=n-m; b=L; d=x-y; 得

ax+by=d

然后,根定理,方程有解必须gcd(a,b)|d。

确定有解后,两边除以gcd(a,b); 此时gcd(a‘,b‘)=1;使用EXGCD求出为1的解后再乘上d/gcd(a,b)。

但要求最小解,就尽可能的把ax的值附到by上去,所以可以有ax=b*k+a*v(因为附到by上后必须仍上a*x的形式)。两边同除a就可得到结果。其实,只有一个可能,就是a=1。

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

__int64 gcd(__int64 a,__int64 b){
	if(b==0) return a;
	return gcd(b,a%b);
}

void exgcd(__int64 a,__int64 b,__int64 &x,__int64 &y){
	if(b==0){
		x=1; y=0;
		return ;
	}
	exgcd(b,a%b,x,y);
	__int64 t=x;
	x=y;
	y=t-a/b*y;
}

int main(){
	__int64 x,y,m,n,L,a,b,c,d;
	while(scanf("%I64d%I64d%I64d%I64d%I64d",&x,&y,&m,&n,&L)!=EOF){
		a=n-m; b=L; d=x-y;
		c=gcd(a,b);
		if(d%c!=0){
			printf("Impossible\n");
			continue;
		}
		a/=c; b/=c; d/=c;
		exgcd(a,b,x,y);
		x*=d; y*=d;
		__int64 t=(x%(b)+b)%b;
		printf("%I64d\n",t);
	}
	return 0;
}

  

 

POJ 1061

标签:blog   os   使用   io   div   log   amp   sp   on   

原文地址:http://www.cnblogs.com/jie-dcai/p/3939440.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!