题目:
LINK
因为a[i] 与一定互质,所以不能直接用中国剩余定理。
假设先给定 x = r1 (mod a1) , x = r2 (mod a2) 可以得到 x = r1 + a1 * x = r2 + a2 * y => a1*x + a2*y = r2 - r1可以用扩展欧几里得解得最小正解x0, 即可得到最小满足当前两个同余式的解X'= r1 + a1*x0 ;
因为a[i] 与一定互质,所以不能直接用中国剩余定理。
假设先给定 x = r1 (mod a1) , x = r2 (mod a2) 可以得到 x = r1 + a1 * x = r2 + a2 * y => a1*x + a2*y = r2 - r1可以用扩展欧几里得解得最小正解x0, 即可得到最小满足当前两个同余式的解X'= r1 + a1*x0 ;
则 X = r1 + a1*x0 + k*lcm(a1, a2) (看作x = r1+a1*x0 (mod lcm(a1,a2)) ),同理继续处理(a3, r3)......
类似题目HDU 1573 X问题 HDU3579 Hello Kiki
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<iostream>
using namespace std;
typedef __int64 LL;
LL n, a1, r1, a2, r2;
LL e_gcd(LL a, LL b,LL &x, LL &y)// to get a*x + b*y =gcd(a,b);
{
if(!b) {
x = 1; y = 0;
return a;
}
LL gcd = e_gcd(b, a%b, x, y);
LL t = x; x = y; y = t - (a/b)*y;
return gcd;
}
int main()
{
while(scanf("%I64d", &n) !=EOF) {
int flag = 0;
LL x, y;
scanf("%I64d%I64d", &a1, &r1);
for(int i=2; i<=n; i++) {
scanf("%I64d%I64d", &a2, &r2);
if(flag) continue ;
LL d = e_gcd(a1, a2, x, y);
LL c = r2 - r1;
if(c%d ) {
flag = 1; continue;
}
LL t = a2 / d;
x = (c / d * x % t + t) % t;
r1 = a1 * x + r1;
a1 = a1 * a2 / d;
}
if(flag) printf("-1\n");
else printf("%I64d\n", r1);
}
return 0;
}