题目地址:http://poj.org/problem?id=2891
#include<iostream>
#include<cstdio>
using namespace std;
typedef long long inta;
void extend_gcd(inta a,inta b,inta &x,inta &y,inta &gcd)
{
if(b==0)
{
x=1;
y=0;
gcd=a;
}
else
{
extend_gcd(b,a%b,x,y,gcd);
inta temp=x;
x=y;
y=temp-a/b*y;
}
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
inta a1,r1,a2,r2,x,y;
cin>>a1>>r1;
int bad=0;
for(int i=1;i<n;i++)
{
cin>>a2>>r2;
inta a=a1;
inta b=a2;
inta c=r2-r1;
inta q=1;
extend_gcd(a,b,x,y,q);
if(c%q!=0)
{
bad=1;
}
else
{
inta t=b/q;
x=(c/q*x%t+t)%t;
r1=a1*x+r1;
a1=a1/q*a2;
r1=r1%a1;
}
}
if(bad==0)
cout<<r1<<endl;
else cout<<-1<<endl;
}
}
2中国剩余定理中 模不一定互素的情形 只好两两合并
3注意应该先还原r1 再更新a1的值