E. Robot on the Board 1
大致题意:
有一个机器人,可以在n*m的方格内行走,现在给出一个指令,让你在方格内找到一个坐标,使机器人不走出方格且尽可能执行完全部的指令
Input
The first line contains an integer t (1≤t≤10^4) — the number of test cases.
The next 2t lines contain descriptions of the test cases.
In the description of each test case, the first line contains two integers n and m (1≤n,m≤10^6) — the height and width of the field that the robot is located on. The second line of the description is a string s consisting solely of characters ‘L’, ‘R’, ‘D’ and ‘U’ — the sequence of commands the robot executes. The string has a length from 1 to 10^6 commands.
It is guaranteed that the total length of s over all test cases does not exceed 10^6.
Output
Print t lines, each of which contains the answer to the corresponding test case. The answer to the test case are two integers r (1≤r≤n) and c (1≤c≤m), separated by a space — the coordinates of the cell (row number and column number) from which the robot should start moving to perform as many commands as possible.
If there are several such cells, you may output any of them.
time limit per test : 2 seconds
Tag:模拟
Difficulty:5/10
思路:
首先看数据范围,直接暴力枚举每个格子是肯定不行的;那么可以尝试从(1, 1)开始走并且只走一遍求出最终结果,在走的过程中,有两个性质:
- 如果走出格子,那么这次指令是无效的,无论在哪里开始都一样,都会失败
- 如果不走出格子,那么机器人行走的路径一定有一个范围
那么我们的问题就在于如何求这个范围
我们可以以(1,1)为起始点,向右定为x轴正方向,向下定为y轴正方向,每次行走时更新xy轴最大值和最小值来确定范围,最后根据偏移量计算出坐标即可
我们容易知道,如果范围的最大值和最小值的差还大于格子大小,那么无论如何机器人都会坠毁,由此来结束循环
要注意此时的横纵坐标是什么
AC代码:
#include <iostream>
using namespace std;
int T;
int n, m;
int main() {
cin >> T;
while (T --) {
cin >> n >> m;
string s;
cin >> s;
int x = 0, y = 0;
int minx = 0, miny = 0, maxx = 0, maxy = 0;
int ansx = 1, ansy = 1;
for (char c:s) {
if(c == 'U') miny = min(miny, --y);
else if (c == 'D') maxy = max(maxy, ++y);
else if (c == 'L') minx = min(minx, --x);
else maxx = max(maxx, ++x);
if ((maxx - minx) >= m || (maxy - miny >= n)) break;
ansx = 1 + abs(minx);
ansy = 1 + abs(miny);
}
cout << ansy << " " << ansx << endl;
}
return 0;
}