POJ2891 Strange Way to Express Integers

本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作。

 

 

本文作者:ljh2000
作者博客:http://www.cnblogs.com/ljh2000-jump/
转载请注明出处,侵权必究,保留最终解释权!

 

题目链接:POJ2891

正解:中国剩余定理

解题报告:

  入门题...

  参考博客:CRT

  朴素的$CRT$只能处理模数互质的情况,不过稍加改进就可以做不互质的情况了。

  考虑我们把模数两两合并,每次合并两个式子:

  $x=x1*m1+r1$

  $x=x2*m2+r2$

  那么不难得到:$x1*m1+x2*m2=r2-r1$,这个式子直接用$exgcd$来解就好了,得到最小的正整数$x1$,然后我们就可以得到$x$的值。

  上面的两个式子就被我合并成了一个新的状态:模数为$lcm(m1,m2)$,余数为$x(即x1*m1+r1)$的式子,往下做,两两合并就好了。

 

 

//It is made by ljh2000
//有志者,事竟成,破釜沉舟,百二秦关终属楚;苦心人,天不负,卧薪尝胆,三千越甲可吞吴。
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <string>
#include <complex>
#include <bitset>
using namespace std;
typedef long long LL;
typedef long double LB;
typedef complex<double> C;
const double pi = acos(-1);
const int MAXN = 100011;
int k;
LL m[MAXN],r[MAXN];

inline int getint(){
    int w=0,q=0; char c=getchar(); while((c<'0'||c>'9') && c!='-') c=getchar();
    if(c=='-') q=1,c=getchar(); while (c>='0'&&c<='9') w=w*10+c-'0',c=getchar(); return q?-w:w;
}

inline void exgcd(LL a,LL b,LL &d,LL &x,LL &y){
	if(b==0) { d=a; x=1; y=0; return ; }
	exgcd(b,a%b,d,y,x);
	y-=a/b*x;
}

inline void CRT(){
	LL M,R,b,x,y,d,z;//当前的模数和余数
	M=m[1]; R=r[1];
	for(int i=2;i<=k;i++) {
		exgcd(M,m[i],d,x,y);
		z=r[i]-R;
		if(z%d!=0) { printf("-1\n"); return ; }
		b=m[i]; b/=d; z/=d;
		x=x*z%b; x+=b; x%=b;//最小正整数解x
		R+=x*M;
		M=m[i]*M/d;
	}
	printf("%lld\n",R);
}

inline void work(){
	while(scanf("%d",&k)!=EOF) {
		for(int i=1;i<=k;i++) m[i]=getint(),r[i]=getint();
		CRT();
	}
}

int main()
{
    work();
    return 0;
}
//有志者,事竟成,破釜沉舟,百二秦关终属楚;苦心人,天不负,卧薪尝胆,三千越甲可吞吴。

  

posted @ 2017-03-15 11:23  ljh_2000  阅读(177)  评论(0编辑  收藏  举报