【中国剩余定理/扩展欧几里得定理】AcWing204.表达整数的奇怪方式——题解顺带中国剩余定理模板
作者:互联网
AcWing204.表达整数的奇怪方式
题解
模板
根据题目变形
#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;
}
int main()
{
int n;
cin >> n;
LL m1, a1, x;
cin >> m1 >> a1;
for(int i = 0; i < n - 1; ++i)
{
LL m2, a2, k1, k2;
cin >> m2 >> a2;
LL d = exgcd(m1, m2, k1, k2);
if( (a2 - a1) % d )
{
x = -1;
break;
}
k1 *= (a2 - a1) / d;
k1 = (k1 % (m2 / d) + m2/d) % (m2 / d); //另k1最小使得a最小才能出现最小x
a1 = k1 * m1 + a1;
m1 = m1 / d * m2;
}
if(x != -1)
x = (a1 % m1 + m1) % m1;
cout << x << endl;
return 0;
}
标签:剩余,题解,定理,a1,k1,a2,m1,m2,LL 来源: https://www.cnblogs.com/czy-algorithm/p/16367782.html