POJ2891 Strange Way to Express Integers 一元线性同余方程组

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


题目大意:有一种表示非负整数的方法:选择k个不同的正整数a1,a2,...,ak,对于某个整数m分别对ai求余,对应余数为ri,如果只当选择a1,a2,...,ak,那么整数m可有整数对(ai,ri)唯一表示。现在已知整数对(ai,ri),让确定出唯一的整数m.



分析:典型的解同余方程组的问题。


实现代码如下:

#include <iostream>
#include <cstdio>
#include <cstdlib>
typedef long long LL;
LL a,b,c,d,a1,r1,a2,r2,x0,y0;

void exgcd(LL a,LL b,LL &d,LL &x,LL &y)
{
    if(!b)
    {
        x=1,y=0,d=a;
        return ;
    }
    /*
    else
    {
        exgcd(b,a%b,d,y,x),y-=x*(a/b);
    }
    */
    else
    {
        exgcd(b,a%b,d,x,y);
        LL temp=x;
        x=y;
        y=temp-(a/b)*y;
    }
}

int solve(int n)
{//函数返回值即为方程的解,若方程无解,则返回-1
    bool ifhave=1;
    scanf("%lld%lld",&a1,&r1);
    for(int i=1;i<n;i++)
    {
        scanf("%lld%lld",&a2,&r2);
        a=a1,b=a2,c=r2-r1;
        exgcd(a,b,d,x0,y0);
        if(c%d) ifhave=0;
        LL t=b/d;
        x0=(x0*(c/d)%t+t)%t;
        r1=a1*x0+r1;
        a1=a1*(a2/d);
    }
    if(!ifhave) r1=-1;
    return r1;
}
int main()
{
    int n;
    while(scanf("%d",&n)!=-1)
    {
        solve(n);
        printf("%lld\n",r1);
    }
    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值