C-Wandering Robot 模拟

DreamGrid creates a programmable robot to explore an infinite two-dimension plane. The robot has a basic instruction sequence and a “repeating parameter” , which together form the full instruction sequence and control the robot.

There are 4 types of valid instructions in total, which are ‘U’ (up), ‘D’ (down), ‘L’ (left) and ‘R’ (right). Assuming that the robot is currently at , the instructions control the robot in the way below:

U: Moves the robot to .
D: Moves the robot to .
L: Moves the robot to .
R: Moves the robot to .
The full instruction sequence can be derived from the following equations
The robot is initially at and executes the instructions in the full instruction sequence one by one. To estimate the exploration procedure, DreamGrid would like to calculate the largest Manhattan distance between the robot and the start point during the execution of the instructions.

Recall that the Manhattan distance between and is defined as .

Input
There are multiple test cases. The first line of the input contains an integer indicating the number of test cases. For each test case:

The first line contains two integers and (), indicating the length of the basic instruction sequence and the repeating parameter.

The second line contains a string (, ), where indicates the -th instruction in the basic instruction sequence.

It’s guaranteed that the sum of of all test cases will not exceed .

Output
For each test case output one line containing one integer indicating the answer.

Sample Input
2
3 3
RUL
1 1000000000
D
Sample Output
4
1000000000
Hint
For the first sample test case, the final instruction sequence is “RULRULRUL” and the route of the robot is (0, 0) - (1, 0) - (1, 1) - (0, 1) - (1, 1) - (1, 2) - (0, 2) - (1, 2) - (1, 3) - (0, 3). It’s obvious that the farthest point on the route is (1, 3) and the answer is 4.

题目大意就是一个机器人重复走一个步骤,问这个机器人移动过程中曼哈顿距离的最大值,曼哈顿距离即两个坐标绝对值的和。

暴力,先按照顺序走完第一遍,之后用乘法来求出第k-1次的位置,再一步一步走完最后一次循环,找出这里面的最大的那个结果即可。

#include<bits/stdc++.h>
using namespace std;
long long int num[100005];
int main()
{
	long long int t;
	cin>>t;
	while(t--)
	{
		long long int n,k;
		long long int maxx=-1;
		cin>>n>>k;
		string root;
		cin>>root;
		long long int rx=0,ry=0;
		for(int i=0;i<n;i++)
		{
			if(root[i]=='R')
				rx++;
			if(root[i]=='U')
				ry--;
			if(root[i]=='D')
				ry++;
			if(root[i]=='L')
				rx--;
			maxx=max(maxx,abs(rx)+abs(ry));
		}
		rx*=(k-1);
		ry*=(k-1);
		for(int i=0;i<n;i++)
		{
			if(root[i]=='R')
				rx++;
			if(root[i]=='U')
				ry--;
			if(root[i]=='D')
				ry++;
			if(root[i]=='L')
				rx--;
			maxx=max(maxx,abs(rx)+abs(ry));
		}
		cout<<maxx<<endl;
	}
	return 0;
}
发布了65 篇原创文章 · 获赞 2 · 访问量 830

猜你喜欢

转载自blog.csdn.net/weixin_43797452/article/details/105169477