Mini

백준 5430 AC c++ // 파싱, 덱 사용법 본문

Algorithm/덱

백준 5430 AC c++ // 파싱, 덱 사용법

Mini_96 2023. 11. 28. 14:48

https://www.acmicpc.net/problem/5430

 

5430번: AC

각 테스트 케이스에 대해서, 입력으로 주어진 정수 배열에 함수를 수행한 결과를 출력한다. 만약, 에러가 발생한 경우에는 error를 출력한다.

www.acmicpc.net

0. 덱

뒤쪽에서도 삽입,삭제 가능한 업그레이드 벡터라고 생각하면 된다.

양쪽끝에서 삽입,삭제하는 문제일때 사용하면 된다.

 

1. 시행착오

끝에서 2번째줄이 없는경우 : 정답이 빈칸인경우 "["이 팝되서 "]" 만출력된다.

예외처리조건추가후 []이 출력됨.

string ret = "[";
		while (d.size()) {
			if (!rev) {
				ret += to_string(d.front());
				ret += ",";
				d.pop_front();
			}
			else {
				ret += to_string(d.back());
				ret += ",";
				d.pop_back();
			}
		}
		if(ret!="[") ret.pop_back();
		ret += "]\n";

 

2. 전체코드

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

int t;

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);

	/*list<int> L;
	L.push_back(1); L.push_back(2); L.push_back(3);
	auto it = --L.end();
	cout << *it<<"\n";
	it = L.erase(it);
	cout << *it << "\n";*/
	//return 0;

	cin >> t;
	while (t--) {
		string p, arr;
		int n;
		deque<int> d;
		cin >> p >> n >> arr;
		for (int i = 1; i < arr.size() - 1; ++i) {
			string temp = "";
			while (arr[i] != ',') {
				temp += arr[i];
				++i;
				if (i == arr.size() - 1) break;
			}
			d.push_back(stoi(temp));
		}

		//for (auto i : L) cout << i << " ";

		int rev = 0;
		bool error = false;
		for (char op : p) {
			if (op == 'R') {
				rev = ~rev;
			}
			if (op == 'D') {
				if (d.empty()) {
					cout << "error\n";
					error = true;
					break;
				}
				if (!rev) d.pop_front();
				else d.pop_back();
			}
		}
		if (error) continue;

		//for (auto i : d)cout << i << " ";
		string ret = "[";
		while (d.size()) {
			if (!rev) {
				ret += to_string(d.front());
				ret += ",";
				d.pop_front();
			}
			else {
				ret += to_string(d.back());
				ret += ",";
				d.pop_back();
			}
		}
		if(ret!="[") ret.pop_back();
		ret += "]\n";

		cout << ret;
	}
	return 0;
}