poj2891 Strange Way to Express Integers(中国剩余定理)
来源:互联网 发布:小世界网络的度分布 编辑:程序博客网 时间:2024/06/05 02:13
Description
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.
- 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
28 711 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.
Source
中国剩余定理:
#include<stdio.h>#include<algorithm>#include<string.h>#define ll __int64ll gcd(ll a,ll b,ll &x,ll &y){if(b==0){x=1;y=0;return a;}ll d=gcd(b,a%b,x,y);ll t=x;x=y;y=t-a/b*y;return d;}ll mod(ll a,ll b ,ll n,ll &d){ll e,x,y;d=gcd(a,n,x,y);if(b%d!=0)return -1;e=(x*(b/d))%n;while(e<0)e+=n/d;return e;}int main(){bool flag;ll m,r1,a1,a2,r2,x,d;while(~scanf("%I64d",&m)){scanf("%I64d%I64d",&a1,&r1);flag=0;for(int i=1;i<m;i++){scanf("%I64d%I64d",&a2,&r2);if(flag)continue;x=mod(a1,r2-r1,a2,d);if(x==-1){flag=1;continue;}r1+=a1*x;a1=a1*a2/d;r1=(r1%a1+a1)%a1;}if(flag)printf("-1\n");elseprintf("%I64d\n",r1);}}
- poj2891 Strange Way to Express Integers(中国剩余定理)
- poj2891 Strange Way to Express Integers(中国剩余定理)
- POJ2891 Strange Way to Express Integers 不互质中国剩余定理
- POJ2891 Strange Way to Express Integers(中国剩余定理)
- poj2891--Strange Way to Express Integers(不互素的中国剩余定理)
- 【POJ2891】Strange Way to Express Integers——中国剩余定理(非互质)
- [POJ2891]Strange Way to Express Integers(扩展中国剩余定理)
- poj2891 Strange Way to Express Integers (中国剩余定理+拓展欧几里得)
- poj2891——Strange Way to Express Integers(扩展欧几里得解中国剩余定理)
- Strange Way to Express Integers(中国剩余定理+不互质)
- POJ2891 Strange Way to Express Integers(解多元线性同余方程)(中国剩余定理非互质版)(例题)
- poj 2891 Strange Way to Express Integers 中国剩余定理
- 中国剩余定理 poj 2891 Strange Way to Express Integers
- Strange Way to Express Integers-----不互质的中国剩余定理
- POJ 2891 Strange Way to Express Integers 中国剩余定理
- poj Strange Way to Express Integers 2891 (中国剩余定理)
- POJ 2891-Strange Way to Express Integers【中国剩余定理】
- POJ 2891 Strange Way to Express Integers (中国剩余定理)
- 修改eclipse自动生成的comments中的author名字
- HandlerThread的使用
- 编程语言及其应用
- sql(join on 和where的执行顺序)
- 浮点数IEEE-754标准
- poj2891 Strange Way to Express Integers(中国剩余定理)
- HTML——2(HTML 文件的结构)
- android开发步步为营之74:生成facebook注册应用主页需要的Key Hashes
- Android 开发 voip/sip 程序
- 关于开发工具的一些快捷键收集(持续更新)
- CArray排序
- Zookeeper 的学习与运用
- DLL动态链接库的是如何建立的(1)
- oncreate()方法中获得view宽高 观察者模式