公式

C - LRUD Instructions 2 解説 by en_translator


Find the coordinates after each move and check if there are duplicates.

When finding the duplicates, storing and searching in an array or a list costs a time proportional to the length of the list or an array, for a total of \(\Theta(N^2)\) time, leading to TLE (Time Limit Exceeded). By using a set etc., one can do it in an \(O(\log N)\) time each, for a total of \(O(N\log N)\) time.

Sample code (C++):

#include<bits/stdc++.h>
using namespace std;

int main(){
	int N;
	cin >> N;
	string S;
	cin >> S;
	set<pair<int,int>>used({{0,0}});
	int x=0,y=0;
	for(auto c:S){
		if(c=='U')y++;
		if(c=='D')y--;
		if(c=='R')x++;
		if(c=='L')x--;
		if(used.find({x,y})!=used.end()){
			cout << "Yes" << endl;
			return 0;
		}
		used.insert({x,y});
	}
	cout << "No" << endl;
}

投稿日時:
最終更新: