POJ 2891 Strange Way to Express Integers(中国剩余定理)

来源:互联网 发布:西昊 ergomax 知乎 编辑:程序博客网 时间:2024/05/02 02:36

题目链接:http://poj.org/problem?id=2891

#include <cstdio>#include <cstring>#include <cmath>#include <ctime>#include <cstdlib>#include <queue>#include <stack>#include <string>#include <iostream>#include <algorithm>using namespace std;typedef long long ll;ll exGcd(ll a,ll b,ll &x,ll &y){    if(b == 0)    {        x = 1;        y = 0;        return a;    }    ll r=exGcd(b,a%b,x,y);    ll t=x;    x=y;    y=t-a/b*y;    return r;}ll minX;ll d;int lin(ll a,ll b,ll n){    ll e;    ll x, y;    d = exGcd(a, n, x, y);    if(b%d)        return 0;    b = b/d;    e = n/d;    minX = ((x*b) % e + e) % e;    return 1;}int main(){    int k;    while(~scanf("%d",&k))    {        ll result;        ll a, r;        ll a1, r1;        int flag = 1;        scanf("%lld %lld", &a, &r);        if (a <= r)            flag = 0;        k--;        while (k--)        {            scanf("%lld %lld", &a1, &r1);            if (a1 <= r1 || !flag)                flag = 0;            else            {                flag = lin(a, r1-r, a1);//推导出方程 a*x + a1*y = r1-r                if (flag==0)                    continue;                r = minX*a + r;                a = a*a1/d;                r = (r % a + a) % a;            }        }        if (flag)            printf("%lld\n", r);        else            printf("-1\n");    }    return 0;}
0 0
原创粉丝点击