POJ2891 Strange Way to Express Integers 扩展欧几里德 中国剩余定理

欢迎访问~原文出处——博客园-zhouzhendong

去博客园看该题解


题目传送门 - POJ2891


题意概括

  给出k个同余方程组:x mod ai = ri。求x的最小正值。如果不存在这样的x,那么输出-1.不满足所有的ai互质。


题解

  UPD(2018-08-07):

  本题做法为扩展中国剩余定理。

  我写了一篇证明:链接:https://www.cnblogs.com/zhouzhendong/p/exCRT.html

  代码就不要看了,很久之前写的,太丑了。


代码

#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;
}

  

上一篇:struts2简单入门-参数传递的三种方式


下一篇:webstorm的安装、激活码、更换主题颜色的修改、汉化