中国剩余定理模数不互质的情况(poj 2891

中国剩余定理模数不互质的情况
主要有一个ax+by==k*gcd(a,b),注意一下倍数情况和最小

https://vjudge.net/problem/POJ-2891

#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
#include <cmath>
#include <cstring>
#define inf 2147483647
#define N 1000010
#define p(a) putchar(a)
#define For(i,a,b) for(long long i=a;i<=b;++i)
//by war
//2019.8.8
using namespace std;
long long T,n;
long long r[N],a[N],x,y,gcd,flag;
void in(long long &x){
    long long y=1;char c=getchar();x=0;
    while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();}
    while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=getchar();}
    x*=y;
}
void o(long long x){
    if(x<0){p('-');x=-x;}
    if(x>9)o(x/10);
    p(x%10+'0');
}

void exgcd(long long a,long long b,long long &x,long long &y){
    if(!b){
        x=1;y=0;gcd=a;
        return;
    }
    exgcd(b,a%b,y,x);
    y-=a/b*x;
}

signed main(){
    while(scanf("%lld",&n)!=EOF){
        flag=0;
        For(i,1,n)
           in(r[i]),in(a[i]);
        For(i,2,n){
            exgcd(r[1],r[i],x,y);
            if((a[i]-a[1])%gcd==0){
                x*=(a[i]-a[1])/gcd;
                y=r[i]/gcd;
                x=(x%y+y)%y;
                a[1]+=r[1]*x;
                r[1]=r[1]*r[i]/gcd;
            }
            else{
                o(-1);p('\n');
                flag=1;
                break;
            }
        }
        if(!flag)
            o(a[1]),p('\n');
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/war1111/p/11323764.html