【poj2891】 Strange Way to Express Integers

http://poj.org/problem?id=2891 (题目链接)

题意

  求解线性同余方程组,不保证模数一定两两互质。

Solotion

  一般模线性方程组的求解,详情请见:中国剩余定理

细节

  注意当最后发现方程无解直接退出时,会导致有数据没有读完,然后就会Re,所以先用数组将所有数据存下来。

代码

// poj2891
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<cmath>
#define LL long long
#define inf 2147483640
#define Pi acos(-1.0)
#define free(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout);
using namespace std;

const int maxn=100010;
LL a[maxn],r[maxn],n;

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;
}
LL CRT() {
	LL M=a[1],R=r[1];
	LL d,x,y;
	for (int i=2;i<=n;i++) {
		LL mm=a[i],rr=r[i];
		exgcd(M,mm,d,x,y);   //M*x+R=mm*y+rr
		if ((rr-R)%d!=0) return -1;
		x=((rr-R)/d*x%(mm/d)+mm/d)%(mm/d);   //求出最小正整数x
		R+=M*x;   //把整个M*x+R当做余数
		M*=mm/d;   //lcm(M,m)
	}
	return R;
}
int main() {
	while (scanf("%lld",&n)!=EOF) {
		for (int i=1;i<=n;i++) scanf("%lld%lld",&a[i],&r[i]);
		printf("%lld\n",CRT());
	}
	return 0;
}

  

  

posted @ 2016-09-27 19:49  MashiroSky  阅读(492)  评论(2编辑  收藏  举报