Robot Program(找规律)

Robot Program

题目链接:https://codeforces.com/problemset/problem/1452/A

题目描述:

There is an infinite 2-dimensional grid. The robot stands in cell (0,0) and wants to reach cell (x,y). Here is a list of possible commands the robot can execute:
move north from cell (i,j) to (i,j+1);
move east from cell (i,j) to (i+1,j);
move south from cell (i,j) to (i,j−1);
move west from cell (i,j) to (i−1,j);
stay in cell (i,j).
The robot wants to reach cell (x,y) in as few commands as possible. However, he can’t execute the same command two or more times in a row.
What is the minimum number of commands required to reach (x,y) from (0,0)?

描述翻译:

有一个无限的二维网格。机器人站在单元格(0,0)中,想要到达单元格(x,y)。以下是机器人可以执行的命令列表:
从单元格(i,j) 向北移动到(i,j+1);
从单元格(i,j) 向东移动到(i+1,j);
从单元(i,j) 向南移动到(i,j−1);
从单元格(i,j) 向西移动到(i−1,j);
待在当前的单元格中。
机器人想用尽可能少的命令到达单元格(x,y)。但他不能在同一行中执行两次或更多次。
从(0,0)到达(x,y)所需的最小命令数是多少?

输入:

The first line contains a single integer t (1≤t≤100) — the number of testcases.
Each of the next t lines contains two integers x and y (0≤x,y≤104) — the destination coordinates of the robot.

输入翻译:

第一行包含单个整数t(1≤t≤100)——测试用例的数量。
接下来的每一条t线包含两个整数x和y(0≤x,y≤104)——机器人的目标坐标。

输出:

For each testcase print a single integer — the minimum number of commands required for the robot to reach (x,y) from (0,0) if no command is allowed to be executed two or more times in a row.

输出翻译:

对于每个测试用例,打印一个整数-如果不允许在一行中执行两次或更多次命令,则机器人从(0,0)达到(x,y)所需的最小命令数。

注意:

The explanations for the example test:
We use characters N, E, S, W and 0 to denote going north, going east, going south, going west and staying in the current cell, respectively.
In the first test case, the robot can use the following sequence: NENENENENE.
In the second test case, the robot can use the following sequence: NENENEN.
In the third test case, the robot can use the following sequence: ESENENE0ENESE.
In the fourth test case, the robot doesn’t need to go anywhere at all.
In the fifth test case, the robot can use the following sequence: E0E.

注意翻译:

示例测试说明
我们使用字符N、E、S、W和0分别表示向北、向东、向南、向西和停留在当前单元格中。
在第一个测试用例中,机器人可以使用以下序列:NENENENENE。
第二种情况下,机器人可以使用下面的程序。
在第三个测试用例中,机器人可以使用以下序列:eseneneOne。
在第四个测试用例中,机器人根本不需要去任何地方。
在第五个测试用例中,机器人可以使用以下序列:E0E。

输入样例:

5
5 5
3 4
7 1
0 0
2 0

输出样例:

10
7
13
0
3

题解:本题乍一看深搜广搜。。。可是呢,这样过不去呀,所以,这道题我们找规律。

1、 对于x==y我们直接向下向右交替就是最短到达目标。

2、对于x!=y的情况,我们可以先计算x和y中最小的那个值(利用1的方法),然后停一下走一下,最后到达终点的时候不用停,所以就减一。

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
int main()
{
    
    
	int t;
	scanf("%d",&t);
	while(t--)
	{
    
    
		int x,y;
		scanf("%d%d",&x,&y);
		int sum;
		if(x==y)
			sum=x+y;
		else
			sum=2*min(x,y)+abs(x-y)*2-1;//x与y不相等的情况,找到最小的那个值,
		//然后就走一步停一步,最后到达终点不用停,所以就减1
		printf("%d\n",sum);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/zlzqq/article/details/110429043