代码改变世界

FZU 1402 猪的安家 中国剩余定理

2012-07-30 14:54  javaspring  阅读(252)  评论(0编辑  收藏  举报

来源:http://acm.fzu.edu.cn/problem.php?pid=1402

题意:中文~

思路:就是中国剩余定理的模板题,本来是做poj上的一道题,那道题没要求两辆不互质,还要转化成两辆互质的,还不会,,,先把这道题水过了。。

代码:

#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;

#define CLR(arr,val) memset(arr,val,sizeof(arr))
const int N = 1010;
long long a[N],r[N];
void extend_Eulid(long long a,long long b,long long &x,long long &y){
	if(b == 0){
	  y = 0;
	  x = 1;
	  return;
	}
	extend_Eulid(b,a%b,x,y);
	int temp = x;
	x = y;
	y = temp - a/b * y;
}
int main(){
	//freopen("1.txt","r",stdin);
	int n;
	while(scanf("%d",&n) != EOF){
		long long M = 1;
		for(int i = 1;i <= n; ++i){
		  scanf("%lld%lld",&a[i],&r[i]);
		  M *= a[i];
		}
		long long sum = 0;
		for(int i = 1;i <= n;++i){
		  long long m = M / a[i];
		  long long x,y;
		  extend_Eulid(m,a[i],x,y);
		  x = (x % a[i] + a[i]) % a[i];
		  sum = ( sum + x * m * r[i])%M ;
		}
		printf("%lld\n",sum );
	}
	return 0;
}