ZOJ
来源:互联网 发布:温州龙湾网络问政 编辑:程序博客网 时间:2024/06/06 14:45
There is an interesting and simple one person game. Suppose there is a number axis under your feet. You are at point A at first and your aim is point B. There are 6 kinds of operations you can perform in one step. That is to go left or right by a,b and c, here c always equals to a+b.
You must arrive B as soon as possible. Please calculate the minimum number of steps.
Input
There are multiple test cases. The first line of input is an integer T(0 < T ≤ 1000) indicates the number of test cases. Then T test cases follow. Each test case is represented by a line containing four integers 4 integers A, B, a and b, separated by spaces. (-231 ≤ A, B < 231, 0 < a, b < 231)
Output
For each test case, output the minimum number of steps. If it's impossible to reach point B, output "-1" instead.
Sample Input
20 1 1 20 1 2 4
Sample Output
1-1
题意:从A点到B点 有3种移动方式 移动 a距离,b距离或者 a+b距离,问最少需要多少步。
分析:
有3种情况
ax+by=A-B
ax+cy=A-B
bx+cy=A-B
用扩展欧几里德很容易求出 x和y的值
X=x+b/gcd *t
Y=y-a/gcd *t
通过这两个方程可以得到两个关于t的线,两个的斜率互异
我们要求的是 |X|+|Y|的最小值
所以最小值应该在 X=0或者Y=0处可以取到
但是这里的X和Y是经过整除运算得到的,所以存在误差
在计算的时候需要多查看左一位和右一位
AC代码:
#include<stdio.h>#include<string.h>#include<math.h>#include<algorithm>using namespace std;long long kzgcd(long long a,long long b,long long &x,long long &y){if(b==0){x=1,y=0;return a;}long long ans=kzgcd(b,a%b,x,y);long long t=x;x=y;y=t-(a/b)*y;return ans;}long long solve(long long a,long long b,long long c){long long x,y;long long gcd=kzgcd(a,b,x,y);if(c%gcd) return -1;x=x*c/gcd;y=y*c/gcd;long long aa=a/gcd;long long bb=b/gcd;//x=x0+b/gcd *t y=y0-a/gcd *t;long long ans=abs(x)+abs(y);for(long long i=-x/bb-1;i<=-x/bb+1;i++){long long xx=x+bb*i;long long yy=y-aa*i;if(ans>abs(xx)+abs(yy))ans=abs(xx)+abs(yy);}for(long long i=y/aa-1;i<=y/aa+1;i++){long long xx=x+bb*i;long long yy=y-aa*i;if(ans>abs(xx)+abs(yy))ans=abs(xx)+abs(yy);}return ans;}int main(){int T;scanf("%d",&T);while(T--){long long A,B,a,b;scanf("%lld%lld%lld%lld",&A,&B,&a,&b);long long C=abs(A-B),c=a+b,ans[4];ans[1]=solve(a,b,C);ans[2]=solve(a,c,C);ans[3]=solve(b,c,C);if(ans[1]==-1&&ans[2]==-1&&ans[3]==-1)printf("-1\n");else{long long anss=ans[1];for(int i=2;i<=3;i++)anss=min(anss,ans[i]);printf("%lld\n",anss);}} }
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- Spring 4.0 学习日记(5) ---bean的自动装配
- C# Session操作类
- Unable to validate using XSD: Your JAXP provider does not support XML Schema
- 如何判断小端模式和大端模式
- mybatis入门案例(一)
- ZOJ
- C# CookieHelper帮助类
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- C#创建com组件
- HTTP协议详解
- json的小例子
- webapck 全局引入jquery
- HDU