您的位置:首页 > 其它

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

2015-06-05 11:25 381 查看
题目连接: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: