Files
python/TangDou/AcWing/CRT/P4777.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

47 lines
1.1 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <iostream>
using namespace std;
typedef long long LL;
LL exgcd(LL a, LL b, LL &x, LL &y) {
if (!b) {
x = 1, y = 0;
return a;
}
LL d = exgcd(b, a % b, y, x);
y -= a / b * x;
return d;
}
LL n, a1, m1, a2, m2, k1, k2;
int main() {
cin >> n;
cin >> a1 >> m1; // 读入第一个方程
n--; // 共n-1个方程
while (n--) {
cin >> a2 >> m2;
// 开始合并
// a1*k1+(-a2)*k2=m2-m1
// ① 求a1*k1+(-a2)*k2=gcd(a1,-a2)的解,视k1=x,k2=y
LL d = exgcd(a1, -a2, k1, k2);
if ((m2 - m1) % d) { // 如果不是0,则无解
cout << -1;
exit(0);
}
// ② 求 a1*k1+(-a2)*k2=m2-m1 的一组解,需要翻 (m2-m1)/d倍
k1 *= (m2 - m1) / d;
// ③ 求最小正整数解
int t = abs(a2 / d);
k1 = (k1 % t + t) % t;
// ④ 更新a1和m1,准备下一轮合并
m1 = k1 * a1 + m1;
a1 = abs(a1 / d * a2);
}
// 输出,m1是一个解,不是最小整数解,需要模a1
cout << (m1 % a1 + a1) % a1;
return 0;
}