Codeforces Round #617 (Div. 3) C Yet Another Walking Robot (map)

题目传送

题目大意:一个机器人从起点走到终点,但是中间可能会走很多无用路,(会转圈)不太聪明的亚子~~~要删掉尽可能短的路,让机器人也能走到终点。

做法:用map记录上一次来的这个位置是哪一步,再次来到时更新结果。

#include <iostream>
#include <map>
using namespace std;

#define inf 0x3f3f3f3f
#define maxn 200000+10

map<int, int> vis[2 * maxn];
char ss[maxn];

int main(void)
{
	int t, n;
	cin >> t;
	while (t--) {
		cin >> n;
		cin >> ss + 1;
		//for (int i = 0; i < 2 * maxn; i++) {
		//	vis[i].clear();
		//} 会超时。。。。感觉下面没快多少
		for (int i = 0; i <= n; i++) {
			vis[maxn - i].clear();
			vis[maxn + i].clear();
		}
		int xx = maxn, yy = 0, ans_len = inf, ans_l, ans_r;
		vis[xx][yy] = 0;
		for (int i = 1; i <= n; i++) {
			if (ss[i] == 'L') xx--;
			if (ss[i] == 'R') xx++;
			if (ss[i] == 'U') yy++;
			if (ss[i] == 'D') yy--;
			if (vis[xx].count(yy)) {
				int L = vis[xx][yy] + 1;
				int R = i;
				if (R - L + 1 < ans_len) {
					ans_len = R - L + 1;
					ans_l = L;
					ans_r = R;
				}
			}
			vis[xx][yy] = i;
		}
		if (ans_len != inf) cout << ans_l << " " << ans_r << endl;
		else cout << "-1" << endl;
	}
	return 0;
}
发布了16 篇原创文章 · 获赞 9 · 访问量 4571

猜你喜欢

转载自blog.csdn.net/qq_43054573/article/details/104187562