[CF2147A]Shortest Increasing Path题解
time limit per test
1 second
memory limit per test
256 megabytes
You are at (0,0) in a rectangular grid and want to go to (x,y).
In order to do so, you are allowed to perform a sequence of steps.
Each step consists of moving a positive integer amount of length in the positive direction of either the x or the y axis.
The first step must be along the x axis, the second along the y axis, the third along the x axis, and so on. Formally, if we number steps from one in the order they are done, then odd-numbered steps must be along the x axis and even-numbered steps must be along the y axis.
Additionally, each step must have a length strictly greater than the length of the previous one.
Output the minimum number of steps needed to reach (x,y), or −1 if it is impossible.
有道 翻译
你在一个矩形网格中的 (0,0) 处,想要转到 (x,y) 处。
为此,您可以执行一系列步骤。
每一步包括沿 x 或 y 轴的正方向移动一个正整数长度。
第一步必须沿着 x 轴,第二步沿着 y 轴,第三步沿着 x 轴,依此类推。形式上,如果我们按照完成步骤的顺序从1开始编号,那么奇数步骤必须沿着 x 轴,偶数步骤必须沿着 y 轴。
此外,每一步的长度必须严格大于前一步的长度。
输出达到 (x,y) 所需的最小步数,如果不可能达到则输出 −1 。
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1≤t≤104). The description of the test cases follows.
The first and only line of each case contains two integers x and y (1≤x,y≤109).
有道 翻译
输入** **
每个测试包含多个测试用例。第一行包含测试用例的数量 t ( 1≤t≤104 )。下面是测试用例的描述。
每种情况的第一行也是唯一一行包含两个整数 x 和 y ( 1≤x,y≤109 )。
Output
For each test case, output the minimum number of steps to reach (x,y) or −1 if it is impossible.
有道 翻译
** **输出
对于每个测试用例,如果不可能,输出达到 (x,y) 或 −1 的最小步数。
Example
Input
Copy
10
1 2
5 6
4 2
1 1
2 1
3 3
5 1
5 4
752 18572
95152 2322
Output
Copy
2
2
3
-1
-1
-1
-1
-1
2
3
Note
In the second test case, you can move to (5,0) by moving 5 along the x axis and then to (5,6) by moving 6 along the y axis.

In the third test case, you can move to (1,0), then to (1,2), and finally to (4,2).

In the fourth test case, reaching (1,1) is impossible since after moving to (1,0) along the x axis, you are forced to move at least 2 along the y axis.
有道 翻译
注意
(可视化工具链接)(https://codeforces.com/assets/contests/2147/A_cdXXtjqxZBm9unXAJx2Q.html)
在第二个测试用例中,您可以沿着 x 轴移动 5 到 (5,0) ,然后沿着 y 轴移动 6 到 (5,6) 。
! [] (https://espresso.codeforces.com/d2004648d27b0293b7b5a2bf5c299b775a067848.png)
在第三个测试用例中,您可以移动到 (1,0) ,然后移动到 (1,2) ,最后移动到 (4,2) 。
! [] (https://espresso.codeforces.com/dba4a2a4e5028d5aa466d15009f7766286faac00.png)
在第四个测试用例中,到达 (1,1) 是不可能的,因为在沿着 x 轴移动到 (1,0) 之后,您将被迫沿着 y 轴移动至少 2 。
思路
若y==0,直接一步到位.
若x<y,直接两步到位.
若x==y||x==y+1,无解.
若其他,直接三步到位.
代码见下
#include<bits/stdc++.h>
using namespace std;
long long t,x,y;
int main(){
cin>>t;
while(t--){
cin>>x>>y;
if(y==0){
cout<<1<<endl;
}
else if(x<y){
cout<<2<<endl;
}
else if(x==y||x==y+1||y==1){
cout<<-1<<endl;
}
else{
cout<<3<<endl;
}
}
return 0;
}

浙公网安备 33010602011771号