poj 2891 Strange Way to Express Integers 扩展CRT

http://www.elijahqi.win/archives/3177
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.

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
那么考虑当两个余数不互质的时候 我们应该如何处理
假设他们分别是m1 c1 m2 c2
那么转换下形式
x = k 1 m 1 + c 1
x = k 2 m 2 + c 2
满足翡蜀定理 即 g c d ( m 1 , m 2 ) | ( c 1 c 2 ) 这种情况下才有解
k 1 m 1 = k 2 m 2 c 1 + c 2
两个同除gcd(m1,m2)
m 1 ( m 1 , m 2 ) k 1 = k 2 m 2 ( m 1 , m 2 ) + c 2 c 1 ( m 1 , m 2 )
m 1 ( m 1 , m 2 ) k 1 c 2 c 1 ( m 1 , m 2 ) ( m o d m 2 ( m 1 , m 2 ) )
考虑将左边的系数除到右边
k 1 i n v ( m 1 ( m 1 , m 2 ) , m 2 ( m 1 , m 2 ) ) × ( c 2 c 1 ( m 1 , m 2 ) ) ( m o d m 2 ( m 1 , m 2 ) )
再将原来的系数还原回来
k 1 = i n v ( m 1 ( m 1 , m 2 ) , m 2 ( m 1 , m 2 ) ) × ( c 2 c 1 ( m 1 , m 2 ) ) + ( y × m 2 ( m 1 , m 2 ) )
然后再将k1带回原式可以发现
x i n v ( m 1 ( m 1 , m 2 ) , m 2 ( m 1 , m 2 ) ) × ( c 2 c 1 ( m 1 , m 2 ) ) × m 1 + c 1 ( m o d m 1 × m 2 ( m 1 , m 2 ) )
然后这题就搞定了 那么本题只需要直接exgcd求出的即是我想要的
i n v ( m 1 ( m 1 , m 2 ) )

#include<cstdio>
#include<cctype>
#include<algorithm>
#define ll long long
using namespace std;
inline ll read(){
    ll x=0,f=1;char ch=getchar();
    while(!isdigit(ch)) {if (ch=='-') f=-1;ch=getchar();}
    while(isdigit(ch)) x=x*10+ch-'0',ch=getchar();
    return x*f; 
}
inline ll exgcd(ll a,ll b,ll &x,ll &y){
    if (!b) {x=1;y=0;return a;} ll g=exgcd(b,a%b,x,y);
    ll t=x;x=y;y=t-a/b*y;return g;
}
ll k;
int main(){
    freopen("poj2891.in","r",stdin);
    while(~scanf("%lld",&k)){static ll m1,c1,m2,c2;
        m1=read();c1=read();bool flag=0;
        for (int i=2;i<=k;++i){
            m2=read();c2=read();ll t1,t2;if (flag) continue;
            ll g=exgcd(m1,m2,t1,t2);
            if ((c2-c1)%g) {flag=1;}
            t1=t1*(c2-c1)/g;m2/=g;t1=(t1%m2+m2)%m2;
            c1+=t1*m1;m1*=m2;c1%=m1;
        }
        if(flag) {puts("-1");continue;}
        printf("%lld\n",c1);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/elijahqi/article/details/80049210