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

题目: LINK 
因为a[i] 与一定互质,所以不能直接用中国剩余定理。
假设先给定 x = r1 (mod a1) , x = r2 (mod a2) 可以得到 x = r1 + a1 * x = r2 + a2 * y     =>    a1*x + a2*y = r2 - r1可以用扩展欧几里得解得最小正解x0, 即可得到最小满足当前两个同余式的解X'= r1 + a1*x0 ;

则 X = r1 + a1*x0 + k*lcm(a1, a2) (看作x = r1+a1*x0 (mod lcm(a1,a2)) ),同理继续处理(a3, r3)......

类似题目HDU 1573 X问题 HDU3579 Hello Kiki

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<iostream>
using namespace std;
typedef __int64 LL;
LL n, a1, r1, a2, r2;
LL e_gcd(LL a, LL b,LL &x, LL &y)// to get a*x + b*y =gcd(a,b);
{
    if(!b) {
        x = 1; y = 0;
        return a;
    }
    LL gcd = e_gcd(b, a%b, x, y);
    LL t = x; x = y; y = t - (a/b)*y;
    return gcd;
}
int main()
{
    while(scanf("%I64d", &n) !=EOF) {
        int flag  = 0;
        LL x, y;
        scanf("%I64d%I64d", &a1, &r1);
        for(int i=2; i<=n; i++) {
            scanf("%I64d%I64d", &a2, &r2);
            if(flag) continue ;
            LL d = e_gcd(a1, a2, x, y);
            LL c = r2 - r1;
            if(c%d ) {
                flag = 1; continue;
            }
            LL t = a2 / d;
            x = (c / d * x % t + t) % t;
            r1 = a1 * x + r1;
            a1 = a1 * a2 / d;
        }
        if(flag) printf("-1\n");
        else printf("%I64d\n", r1);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值