标签:输出 1.5 targe 最小 ret def htm namespace return
给出k个同余方程组:x mod ai = ri。求x的最小正值。如果不存在这样的x,那么输出-1.不满足所有的ai互质。
互质就简单,但是不互质就有些麻烦,到现在我还是不大懂。
具体证明可以求教大佬,如果我懂了,会更新的。
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef long long LL;
const int N=100005;
LL ex_gcd(LL a,LL b,LL &x,LL &y){
if (!b){
x=1,y=0;
return a;
}
LL ans=ex_gcd(b,a%b,y,x);
y-=(a/b)*x;
return ans;
}
LL m,a[N],n[N];
LL solve(){
LL a1,a2,n1,n2,c,d,k1,k2,K,t;
a1=a[1],n1=n[1];
for (int i=2;i<=m;i++){
a2=a[i],n2=n[i],d=ex_gcd(n1,n2,k1,k2),c=a2-a1;
if (c%d)
return -1;
K=c/d*k1,t=n2/d,K=(K%t+t)%t,a1+=n1*K,n1=n1/d*n2;
}
return a1;
}
int main(){
while (~scanf("%lld",&m)){
for (int i=1;i<=m;i++)
scanf("%lld%lld",&n[i],&a[i]);
printf("%lld\n",solve());
}
return 0;
}
POJ2891 Strange Way to Express Integers 扩展欧几里德 中国剩余定理
标签:输出 1.5 targe 最小 ret def htm namespace return
原文地址:http://www.cnblogs.com/zhouzhendong/p/7795374.html