Codeforces Round #617 (Div. 3)-C.Yet Another Walking Robot(用map记录坐标与路径值)

题意:

机器人从原点出发,每次向上下左右移动一步,但可能会走重复的路,题目要求找出最短的重复路径。删除后不能影响起点和终点。

思路:

使用map,定义一个map<pair<int,int>, int> res,记录每个坐标和其对应的路径值,定义一个pair<int,int> cur(0,0),记录当前移动到了哪个位置,没移动一步,使用res.count(cur))查找,当前点是否出现过,其中map里的count函数判断关键字是否出现,出现就返回1,否则返回0。

代码

#include<iostream>
#include<map>
#include<cstring>
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;

int main(){
	#ifdef _DEBUG
		freopen("input.txt", "r", stdin);
	#endif
	int t;
	cin>>t;
	while(t--){
		int n, l, r;
		string s;
		cin>>n>>s;
		map<pair<int,int>, int> res;//坐标与路径长度额映射 
		pair<int,int> cur(0,0);
		res[cur] = 0;
		l = -1, r = n;
		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
				cur.second--;

				
			if(res.count(cur)){
				if(i - res[cur] < r - l){//比较这次的距离是否比上一次的更短 
					l = res[cur];
					r = i;
				}
			}
			res[cur] = i + 1;//每个点到原点的距离 
		}
		if(l == -1)
			cout<<-1<<endl;
		else
			cout<<l + 1<<" "<<r + 1<<endl;
	}
	return 0; 
}

发布了26 篇原创文章 · 获赞 11 · 访问量 2288

猜你喜欢

转载自blog.csdn.net/qq_41731507/article/details/104312200