Problem 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
<p>The input contains multiple test cases. Each test cases consists of some lines.</p><ul><li>Line 1: Contains the integer <i>k</i>.</li><li>Lines 2 ~ <i>k</i> + 1: Each contains a pair of integers <i>a<sub>i</sub></i>, <i>r<sub>i</sub></i> (1 ≤ <i>i</i> ≤</span> <i>k</i>).</ul></p>
Output
<p>Output the non-negative integer <i>m</i> 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 <tt>-1</tt>.</p></p>
Sample Input
2
8 7
11 9
Sample Output
31
题意:输入 n对数,求满足n对于输入的第一个数求余等于第二个数
思路:裸的中国 剩余定理,套模板
代码:
#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(int w[],int b[],int 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(int i=0;i<k;++i)
ret=ret*w[i]/__gcd(ret,(LL)w[i]);//使用库函数求最小公倍数
}
return ret;
}
int main()
{
int w[10000],b[10000];
int n;
while(scanf("%d",&n)!=EOF)
{
for(int i=0;i<n;++i)
{
scanf("%d%d",&w[i],&b[i]);//除数
}
LL ans=CRT(w,b,n);
printf("%lld\n",ans);
}
return 0;
}