ZOJ
来源:互联网 发布:淘宝网天天特价首页 编辑:程序博客网 时间:2024/06/05 17:20
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,band c, here c always equals to a+b.
You must arrive B as soon as possible. Please calculate the minimum number of steps.
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)
For each test case, output the minimum number of steps. If it's impossible to reach point B, output "-1" instead.
20 1 1 20 1 2 4
1-1
题意:给你一个起点和终点,每次可以向左或向右走a步或b或c步,c=a+b;问最小步数;
根据公式ax+by=c;,当x,y同号时等于max(x,y),当a,b异号时等于(abs(x)+abs(y)),因为a,b大于0,所以不管x,y同号还是异号都是当x,y,最接近时,答案最小,写出通式
x=x1+b/(gcd)*k,y=y1-a/gcd*k; 假设x,y相等,k=(y-x)/(a+b),因为x,y不一定相等,所以枚举k附近的点
#include <algorithm>#include <string.h>#include <iostream>#include <stdio.h>#include <string>#include <vector>#include <queue>#include <map>#include <set>using namespace std;typedef long long LL;const int N = 1e5+10;LL exgcd(LL a,LL b,LL &x,LL &y){ if(b==0) { x=1, y=0; return a; } LL ans=exgcd(b,a%b,x,y); LL tmp=x; x=y; y=tmp-a/b*y; return ans;}int main(){ int t; scanf("%d", &t); while(t--) { LL A, B, a, b, c, x, y; scanf("%lld %lld %lld %lld",&A, &B, &a, &b); if(A>B) swap(A,B); c=(B-A); LL g=exgcd(a,b, x, y); if(c%g!=0) puts("-1"); else { a/=g, b/=g; x*=(c/g), y*=(c/g); LL k=(y-x)/(a+b); LL ans=10000000000ll; for(LL i=k-1;i<=k+1;i++) { if(abs(x+i*b)+abs(y-i*a)==abs(x+i*b+y-i*a)) ans=min(ans,max(abs(x+i*b),abs(y-i*a))); else ans=min(ans,abs(x+i*b)+abs(y-i*a)); } cout<<ans<<endl; } } return 0;}
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- ZOJ
- 用QT信号和槽实现主界面有两个按钮,一个按钮打开新界面,另一个关闭新界面
- CentOS软件的安装,更新与卸载命令
- [Leetcode.467]Unique Substrings in Wraparound String
- “让云计算落地”系列之二:驯服OpenStack这匹野马
- Redis初探05——Redis的sets类型及操作
- ZOJ
- 浅析字符编码
- 史上最清晰Unicode/UCS-/UTF-/ISO-/GBK-/ASCII编码关系
- html中的各属性介绍
- 挥鞭式进入效果实现
- 外贸电商:除了paypal,这些支付方式也能帮到你
- 远离炒作:正视比特币区块链的四大问题
- iOS巅峰之CocoaPods第三方库的管理找不到.h文件
- 加载xib文件、awakeFromNib方法