poj2891 Strange Way to Express Integers(中国剩余定理)
2016-04-26 17:31
381 查看
Strange Way to Express Integers
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. 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. Source POJ Monthly--2006.07.30, Static |
#include<stdio.h>
#include<algorithm>
#include<string.h>
#define ll __int64
ll 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");
else
printf("%I64d\n",r1);
}
}
相关文章推荐
- 3.2013/06/11_韩信点兵
- 初学ACM - 组合数学基础题目PKU 1833
- POJ ACM 1001
- POJ ACM 1002
- 1611:The Suspects
- POJ1089 区间合并
- POJ 2635 The Embarrassed Cryptographe
- POJ 3292 Semi-prime H-numbers
- POJ 2773 HAPPY 2006
- POJ 3090 Visible Lattice Points
- POJ-2409-Let it Bead&&NYOJ-280-LK的项链
- POJ-1695-Magazine Delivery-dp
- POJ1523 SPF dfs
- POJ-1001 求高精度幂-大数乘法系列
- POJ-1003 Hangover
- POJ-1004 Financial Management
- 用单调栈解决最大连续矩形面积问题
- 2632 Crashing Robots的解决方法
- 1573 Robot Motion (简单题)
- POJ 1200 Crazy Search(简单哈希)