Codeforces Round #753 E. Robot on the Board 1(模拟)

该博客讨论了一种算法问题,涉及在一个n*m的网格中指导机器人执行指令而不超出边界。题目要求找出一个起始位置,使得机器人能执行尽可能多的指令。通过模拟机器人的移动并维护边界,可以确定可行的行走范围。当范围超出网格时,算法终止并返回最优起始坐标。文章提供了AC代码实现,使用C++进行模拟,并强调了在处理此类问题时的关键性质和思考过程。
摘要由CSDN通过智能技术生成

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值