Poj 1061 青蛙的约会(扩展欧几里得)
2015-11-21 22:06
405 查看
两个青蛙在赤道上跳跃,走环路。起始位置分别为x,y。每次跳跃距离分别为m,n。赤道长度为L。两青蛙跳跃方向与次数相同的情况下,问两青蛙是否有方法跳跃到同一点。输出最少跳跃次数。
Input
输入只包括一行5个整数x,y,m,n,L,其中x≠y < 2000000000,0 < m、n < 2000000000,0 < L < 2100000000。
Output
输出碰面所需要的跳跃次数,如果永远不可能碰面则输出一行"Impossible"
Sample Input
1 2 3 4 5
Sample Output
4 #include"iostream"
#include"cstdio"
#include"cmath"
using namespace std;
typedef long long LL;
LL e_gcd(LL a,LL b,LL &x,LL &y) //扩展欧几里得,求最大公因子和特解
{
if(b==0)
{
x=1;
y=0;
return a;
}
else
{
LL res=e_gcd(b,a%b,x,y);
LL temp;
temp=x;
x=y;
y=temp-a/b*y;
return res;
}
}
LL cal(LL a,LL b,LL c)
{
LL s,k;
LL ans=e_gcd(a,b,s,k); //最大公因子
if(c%ans!=0) //方程有解的充要条件
return -1;
s*=c/ans;
b/=ans; //否则取到的可能不是最小解
if(b<0)
b=abs(b);
return (s+b)%b; //由特解求出最小解
}
int main()
{
LL x,y,m,n,L;
while(scanf("%lld %lld %lld %lld %lld",&x,&y,&m,&n,&L)!=EOF)
{
LL ans=cal(n-m,L,x-y);
if(ans==-1)
printf("Impossible!\n");
else
printf("%lld\n",ans);
}
}
Input
输入只包括一行5个整数x,y,m,n,L,其中x≠y < 2000000000,0 < m、n < 2000000000,0 < L < 2100000000。
Output
输出碰面所需要的跳跃次数,如果永远不可能碰面则输出一行"Impossible"
Sample Input
1 2 3 4 5
Sample Output
4 #include"iostream"
#include"cstdio"
#include"cmath"
using namespace std;
typedef long long LL;
LL e_gcd(LL a,LL b,LL &x,LL &y) //扩展欧几里得,求最大公因子和特解
{
if(b==0)
{
x=1;
y=0;
return a;
}
else
{
LL res=e_gcd(b,a%b,x,y);
LL temp;
temp=x;
x=y;
y=temp-a/b*y;
return res;
}
}
LL cal(LL a,LL b,LL c)
{
LL s,k;
LL ans=e_gcd(a,b,s,k); //最大公因子
if(c%ans!=0) //方程有解的充要条件
return -1;
s*=c/ans;
b/=ans; //否则取到的可能不是最小解
if(b<0)
b=abs(b);
return (s+b)%b; //由特解求出最小解
}
int main()
{
LL x,y,m,n,L;
while(scanf("%lld %lld %lld %lld %lld",&x,&y,&m,&n,&L)!=EOF)
{
LL ans=cal(n-m,L,x-y);
if(ans==-1)
printf("Impossible!\n");
else
printf("%lld\n",ans);
}
}
相关文章推荐
- UItableView
- [Python] 用Flask引入CSS无法正常显示
- 杭电2715 Herd Sums
- 1096. Consecutive Factors (20)
- HDU 5569 matrix(DP)——BestCoder Round #63(div.1 div.2)
- App Store App申请审核加速
- 1096. Consecutive Factors (20)
- js中this和that
- iOS App提交指南-协议、税务和银行业务
- MySQL--产品的起源和状态
- PHP入门(2) - 数据类型
- Java抽象类和接口
- 微信公众号二次开发(二)-注册新浪SAE
- 谓词大揭秘
- SQLi-Labs Lesson 1-8 notes
- 【小细节】Integer缓存机制(包装类型的缓存机制)
- 迭代解决装载问题
- Android Resource Types之Color State List 简介
- LeetCode之Median Of Two Sorted Arrays
- 国内的Jquery CDN免费服务