poj 2891

中国剩余定理。

代码:

#include<iostream>
#include<fstream>

using namespace std;
long long x,y,t;

long long egcd(long long a, long long b)
{
    if (b == 0)
    {
        x = 1;
        y = 0;
        return a;
    }
    else
    {
        long long e = egcd(b, a % b);
        t = x; x = y; y = t - a / b * y;
        return e;
    }
}

void read(){
//	ifstream cin("in.txt");
	int i,j,k,f,n;
	long long m1,m2,r1,r2,d,c;

	while(cin>>n){
		f=0;
		cin>>m1>>r1;
		for(i=0;i<n-1;i++)
		{
			cin>>m2>>r2;
			if(f) continue;
			d=egcd(m1,m2);
			c=r2-r1;
			if(c%d)
			{
				f=1;
				continue;
			}
			t=m2/d;
			x=(c/d*x%t+t)%t;
			r1=m1*x+r1;
			m1=m1*m2/d;
		}
		if(f) cout<<-1<<endl;
		else
			cout<<r1<<endl;
	}


}

int main(){
	read();
	return 0;
}

posted on 2011-04-05 20:44  宇宙吾心  阅读(865)  评论(0)    收藏  举报

导航