C. Yet Another Walking Robot

题意:有一个机器人在平面上,一开始机器人在点(0, 0),它行走的路径是一个长度为n的字符串s,'L','R','U','D'。让我们计算去掉这个字符串s中的连续子序列,不改变终点,使得修改的子序列的长度最小。

分析:我们可以使用关联数组map,存储走过的路径的坐标到字符串下标的映射,我们只要走过的坐标点曾经出现过,说明我们走了一段徒劳的路径,那么我们就更新最小的区间的两端。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <map>
#include <algorithm>

using namespace std;

int main()
{
	int t;
	scanf("%d", &t);

	while (t--)
	{
		int n;
		scanf("%d", &n);

		string s;
		cin >> s;

		map<pair<int, int>, int> v;
		pair<int, int> cur(0, 0);

		int l = -1, r = n;
		//起始位置
		v[cur] = 0;

		for (int i = 0; i < n; ++i)
		{
			if (s[i] == 'L') --cur.first;
			else if (s[i] == 'R') ++cur.first;
			else if (s[i] == 'U') ++cur.second;
			else if (s[i] == 'D') --cur.second;
			if (v.count(cur))
			{
				if (i - v[cur] + 1 < r - l + 1)
				{
					l = v[cur];
					r = i;
				}
			}
			v[cur] = i + 1;
		}
		if (l == -1)
		{
			cout << -1 << endl;
		}
		else
		{
			cout << l + 1 << " " << r + 1 << endl;
		}
	}


	return 0;
}


原文地址:https://www.cnblogs.com/pixel-Teee/p/12272446.html