您的位置:首页 > 其它

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

2016-10-01 12:34 555 查看
题目链接: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息