POJ 2891 Strange Way to Express Integers
2016-07-31 21:30
218 查看
这道题的除数不是互质的,所以不能用中国剩余定理。
应该把每个柿子都合并后,再处理下一个式子,合并后,除数编程了最小公约数,并且等式右边的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;
}
应该把每个柿子都合并后,再处理下一个式子,合并后,除数编程了最小公约数,并且等式右边的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;
}
相关文章推荐
- poj 2891 Strange Way to Express Integers(扩展欧几里得,中国剩余定理)
- POJ 2891 Strange Way to Express Integers
- poj 2891 Strange Way to Express Integers 模数不互素的中国剩余定理
- POJ 2891 Strange Way to Express Integers(中国剩余定理)
- POJ 2891 Strange Way to Express Integers(解一元线性同余方程组)
- poj 2891 Strange Way to Express Integers
- poj 2891 Strange Way to Express Integers(解一般模线性方程组)
- POJ_2891_Strange Way to Express Integers(非互质的中国剩余定理)
- POJ 2891 Strange Way to Express Integers ★ (扩展欧几里德解同余式组)
- lightoj 1319 - Monkey Tradition 中国剩余定理(孙子定理)+poj 2891 Strange Way to Express Integers
- POJ 2891 Strange Way to Express Integers
- poj 2891 Strange Way to Express Integers
- poj 2891 Strange Way to Express Integers
- POJ 2891 Strange Way to Express Integers (解一元线性方程组)
- POJ-2891 Strange Way to Express Integers 模线性方程组
- poj 2891 Strange Way to Express Integers 中国剩余定理
- poj 2891 Strange Way to Express Integers——使用中国剩余定理中处理某些方程模数不互质的方法
- poj-2891(Strange Way to Express Integers)--中国剩余定理&&扩展欧几里得
- poj 2891 Strange Way to Express Integers 模数不互素的中国剩余定理
- POJ 2891 Strange Way to Express Integers