Computer Science/Algorithm Problem

백준] 1406 - 에디터(CHCI 2004)

TwinParadox 2019. 3. 13. 09:00
728x90

시간 제한 : 0.3초

메모리 제한 : 512MB




입력

첫째 줄에는 초기에 편집기에 입력되어 있는 문자열이 주어진다. 이 문자열은 영어 소문자로만 이루어져 있으며, 길이는 100,000을 넘지 않는다. 둘째 줄에는 입력할 명령어의 개수를 나타내는 정수 N(1≤N≤500,000)이 주어진다. 셋째 줄부터 N개의 줄에 걸쳐 입력할 명령어가 순서대로 주어진다. 명령어는 위의 네 가지 중 하나의 형태로만 주어진다.




출력

첫째 줄에 모든 명령어를 수행하고 난 후 편집기에 입력되어 있는 문자열을 출력한다.




소스코드

#include <iostream>
#include <list>
#include <string>
using namespace std;
int main(void)
{
	ios_base::sync_with_stdio(false);
	cout.tie(NULL);

	string str;
	int len, N;
	list<char> cList;

	cin >> str;
	cin >> N;

	len = str.length();
	cList.push_back('0');
	for (int i = 0; i < len; i++)
		cList.push_back(str[i]);

	list<char>::iterator iter = cList.end();
	iter--;
	list<char>::iterator lastNode = iter;
	iter++;
	while (N--)
	{
		char op;
		cin >> op;
		if (op == 'L' && iter != cList.begin())
			iter--;
		else if (op == 'D' && iter != cList.end())
			iter++;
		else if (op == 'B' && iter != cList.begin())
		{
			if (iter == cList.end())
			{
				cList.erase(lastNode);
				lastNode = --iter;
				iter++;
			}
			else
			{
				auto remove = --iter;
				iter++;
				cList.erase(remove);
			}
		}
		else if (op == 'P')
		{
			char c;
			cin >> c;
			if (iter == cList.begin())
				cList.insert(cList.begin(), c);
			else if (iter == cList.end())
			{
				cList.push_back(c);
				auto tmp = cList.end();
				lastNode = --tmp;
			}
			else
				cList.insert(iter, c);
		}
	}

	for (auto iter = cList.begin(); iter != cList.end(); iter++)
	{
		if(*iter=='0')
			continue;
		cout << *iter;
	}
}




Tip

리스트를 다루는 문제다. 직접 리스트를 작성해도 좋고 C++ 같은 경우는 STL을 사용해도 되는데, STL을 사용할 때는 iterator 사용 방법에 대해 잘 숙지하고 있는 것이 좋다. 그리고 이 문제는 커서가 존재할 수 있는 곳을 어떻게 결정하느냐가 중요하다. 좀 더 깔끔하게 풀 수 있을 것 같은데 아쉽다.



728x90
728x90