本文主要是介绍poj2891 中国剩余定理不互质,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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 mfrom 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.
- Line 1: Contains the integer k.
- Lines 2 ~ k + 1: Each contains a pair of integers ai, ri (1 ≤ i ≤ k).
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
2 8 7 11 9
Sample Output
31
Hint
All integers in the input and the output are non-negative and can be represented by 64-bit integral types.
题意:
一个数m除以ai为bi,求这个数。
分析:
裸的中国剩余定理,直接套的模板。
代码:
#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(int i=0;i<k;++i)ret=ret*w[i]/__gcd(ret,(LL)w[i]);//使用库函数求最小公倍数}return ret;
}
int main()
{LL w[100000],b[100000];int n;while(scanf("%d",&n)!=EOF){for(int i=0;i<n;++i){scanf("%lld%lld",&w[i],&b[i]);//除数}LL ans=CRT(w,b,n);printf("%lld\n",ans);}return 0;
}
这篇关于poj2891 中国剩余定理不互质的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!