http://poj.org/problem?id=2891 /* 中国剩余定理的使用: 首先得到 a1 * x + r1 = m 和 a2 * y + r2 = m,联立得到 a1 * x - a2 * y = r2 - r1,利用extend_gcd解之, 先解得a1*X-a2*Y=GCD(a1,a2)时的X Y值和a1,a2的gcd,x y存在整数解的条件是 gcd | r2-r1.是否输出-1就是从这判断。有解即为 x=(r2-r1)/gcd*X tmp=a2/gcd, x=( ( r2 - r1 ) / gcd * X % tmp + tmp ) % tmp; 接着输入下一组a3,r3,问题变为求满足LCM(a1,a2)%m1=m和 a3%m1=r3的新的m值:m1 LCM(a1,a2) * x + a3 * y = r3 - m */ #include <iostream> using namespace std; __int64 x,y,t; __int64 extend_gcd(__int64 a,__int64 b) //return gcd(a,b) 得到x,y { if(b == 0) { x = 1; y = 0; return a; } else { __int64 temp = extend_gcd(b,a%b); t = x; x = y; y = t - a/b*y; return temp; } } int main() { // freopen("in.txt", "r", stdin); __int64 a1,a2,r1,r2,c,gcd,temp; bool yes; int n; while(scanf("%d",&n) != -1) { yes = false; scanf("%I64d %I64d",&a1 ,&r1); for(int i=0 ;i<n-1 ;i++) { scanf("%I64d %I64d",&a2 ,&r2); if(yes) continue; c = r2 - r1; gcd = extend_gcd(a1,a2); if(c%gcd != 0) { yes = true; continue; } temp = a2/gcd; x = (c/gcd*x % temp + temp)%temp; r1 = a1*x + r1; a1 = a1*a2/gcd; } if(yes) printf("-1/n"); else printf("%I64d/n",r1); } return 0; }