题目链接:
http://poj.org/problem?id=2891
Strange Way to Express Integers
Description Elina is reading a book written by Rujia Liu, which introduces a strange way to express non-negative integers. The way is described as following:
Choose k different positive integers a1, a2, …, ak. For some non-negative m, divide it by every ai (1 ≤ i ≤ k) to find the remainder ri. If a1, a2, …, ak are properly chosen, m can be determined, then the pairs (ai, ri) can be used to express m. “It is easy to calculate the pairs from m, ” said Elina. “But how can I find m from the pairs?” Since Elina is new to programming, this problem is too difficult for her. Can you help her? Input The input contains multiple test cases. Each test cases consists of some lines.
Output Output the non-negative integer m on a separate line for each test case. If there are multiple possible values, output the smallest one. If there are no possible values, output -1.
Sample Input Sample Output Hint All integers in the input and the output are non-negative and can be represented by 64-bit integral types. Source POJ Monthly--2006.07.30, Static |
题目思路:
裸的中国剩余定理(不互质),a是除数,r是余数
This is the code:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include <iomanip>
#include<list>
#include<queue>
#include<sstream>
#include<stack>
#include<string>
#include<set>
#include<vector>
using namespace std;
#define PI acos(-1.0)
#define EPS 1e-8
#define MOD 1e9+7
#define LL long long
#define ULL unsigned long long //1844674407370955161
#define INT_INF 0x7f7f7f7f //2139062143
#define LL_INF 0x7f7f7f7f7f7f7f7f //9187201950435737471
const int dr[]={0, 0, -1, 1, -1, -1, 1, 1};
const int dc[]={-1, 1, 0, 0, -1, 1, -1, 1};
// ios.sync_with_stdio(false);
// 那么cin, 就不能跟C的scanf,sscanf,getchar,fgets之类的一起使用了。
LL ext_gcd(LL a,LL b,LL &x,LL &y)//扩展欧几里得算法
{
if(!b)
{
x=1,y=0;
return a;
}
LL gcd=ext_gcd(b,a%b,y,x);//与下面的形式一样
y=y-a/b*x;//注意这里
/*
LL gcd=ext_gcd(b,a%b,x,y);
LL temp=x-a/b*y;
x=y;
y=temp;
*/
return gcd;
}
//逐一合并大法
LL CRT(LL w[],LL b[],LL k)//w为除数,b为余数,k为有多少式子
{
LL Wi=w[0],ret=b[0];
for(int i=1;i<k;++i)
{
LL wi=w[i];
LL bi=b[i];
LL x,y;
LL gcd=ext_gcd(Wi,wi,x,y);
LL c=bi-ret;
if(c%gcd)//表示没有结果
return -1;
LL W=wi/gcd;
ret+=Wi*(((c/gcd*x)%W+W)%W);
Wi*=W;
}
if(!ret)//表示余数全部为零
{
ret=1;
for(LL i=0;i<k;++i)
ret=ret*w[i]/__gcd(ret,w[i]);//使用库函数求最小公倍数
}
return ret;
}
int main()
{
LL w[55000],b[55000];//w表示除数,b表示余数
LL n;
while(~scanf("%lld",&n))
{
for(int i=0;i<n;++i)
{
scanf("%lld",&w[i]);//除数
scanf("%lld",&b[i]);//余数
}
LL ans=CRT(w,b,n);
printf("%lld\n",ans);
}
return 0;
}