POJ 2891 Strange Way to Express Integers

这道题的除数不是互质的,所以不能用中国剩余定理。

应该把每个柿子都合并后,再处理下一个式子,合并后,除数编程了最小公约数,并且等式右边的c变成了最优解。

//
//  main.cpp
//  Richard
//
//  Created by 邵金杰 on 16/7/31.
//  Copyright © 2016年 邵金杰. All rights reserved.
//



#include<cstdio>
using namespace std;
typedef long long LL;
void gcd(LL a,LL b,LL &d,LL &x,LL &y)
{
    if(!b) {d=a;x=1;y=0;}
    else {gcd(b,a%b,d,y,x);y-=x*(a/b);}
}
int main()
{
    int k;
    while(scanf("%d",&k)!=EOF)
    {
        LL a1,r1,a2,r2,d,x,y;
        bool fail=false;
        scanf("%lld%lld",&a1,&r1);
        for(int i=1;i<k;i++)
        {
            scanf("%lld%lld",&a2,&r2);
            if(fail) continue;
            gcd(a1,a2,d,x,y);
            if((r2-r1)%d) {fail=true;continue;}
            else{
                LL ans=x*(r2-r1)/d;
                LL s=a2/d;
                ans=(ans%s+s)%s;
                r1=r1+ans*a1;
                a1=a1*a2/d;
            }
        }
        if(fail) printf("-1\n");
        else printf("%lld\n",r1);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值