[PS] 백준 5430번 AC

고범수·2023년 2월 7일
0

Problem Solving

목록 보기
11/31

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

배열의 수를 뒤집거나 맨 앞의 수를 제거하는 연산을 수행한 후, 배열의 요소를 출력하는 문제이다. 배열을 진짜로 뒤집어버리면 약 100,000 (연산최대횟수) * 100,000 (배열 최대길이) 번의 연산이 필요하므로 불가능하다. 그래서 처음 상태와 뒤집은 상태를 구분한다. 처음 상태에서 D 연산이나 출력을 해야하면, 왼쪽(처음 상태에서의 맨 앞)에서 연산을 수행하고 뒤집은 상태에서는 오른쪽(처음 상태에서의 맨 뒤)에서 연산을 수행하면 되겠다.

#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <sstream>
#include <deque>

using namespace std;

int tc, n;
int curState; // 0 := 처음 상태, 1 := 뒤집은 상태
string p;
deque<int> dq;

bool execute(char cmd) {
	if (cmd == 'R') {
		curState = 1 - curState;
	}
	else if (cmd == 'D') {
		if (dq.empty()) {
			return false;
		}

		if (curState == 1) {
			dq.pop_back();
		}
		else {
			dq.pop_front();
		}
	}

	return true;
}

void printDq() {
	if (dq.empty()) {
		cout << "]" << '\n';
		return;
	}


	if (curState == 0) {
		while (dq.size() > 1) {
			cout << dq.front() << ",";
			dq.pop_front();
		}

		cout << dq.front() << "]" << '\n';
	}
	else {
		while (dq.size() > 1) {
			cout << dq.back() << ",";
			dq.pop_back();
		}

		cout << dq.front() << "]" << '\n';
	}
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);

	cin >> tc;
	while (tc--) {
		string numsStr;
		cin >> p >> n >> numsStr;

		stringstream ss(numsStr.substr(1, numsStr.length() - 2));
		string tmp;

		while (getline(ss, tmp, ',')) {
			dq.push_back(stod(tmp));
		}
		
		bool isError = false;
		for (char& ope : p) {
			if (!execute(ope)) {
				isError = true;
				break;
			}
		}

		if (isError) {
			cout << "error" << '\n';
		}
		else {
			cout << "[";
			printDq();
		}

		dq.clear();
		curState = 0;
	}

}

0개의 댓글