题目大意
求最小整数x,满足x≡a[i](mod m[i])(没有保证所有m[i]两两互质)
题解
中国剩余定理显然不行。。。。只能用方程组两两合并的方法求出最终的解,刘汝佳黑书P230有讲~~具体证明和实现我是参考此大神的
代码:
#include<iostream> using namespace std; #define MAXN 100000 typedef long long LL; LL m[MAXN],a[MAXN]; void extended_gcd(LL a,LL b,LL &d,LL &x,LL &y) { if(!b) { d=a,x=1,y=0; } else { extended_gcd(b,a%b,d,y,x),y-=x*(a/b); } } LL no_coprime(LL n) { LL mm,aa,x,y,c,d; aa=a[0],mm=m[0]; for(int i=1; i<n; i++) { c=a[i]-aa; extended_gcd(mm,m[i],d,x,y); if(c%d!=0) return -1; m[i]/=d; x=((x*c/d)%m[i]+m[i])%m[i]; aa=x*mm+aa; mm=mm*m[i]; } return aa; } int main(void) { LL n; while(cin>>n) { for(int i=0; i<n; i++) cin>>m[i]>>a[i]; cout<<no_coprime(n)<<endl; } return 0; }