C++)
#include <iostream>
#include <string>
#include <deque>
#include <algorithm>
using namespace std;
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t, n;
cin >> t;
string p, num;
while (t--) {
cin >> p; // 수행할 함수
cin >> n; // 배열에 들어있는 갯수
cin >> num; // 정수들
// 정수들을 덱에 집어넣기
deque<int> dq;
string arr = "";
for (auto ele : num) {
if (ele != ',' && ele != '[' && ele != ']')
arr += ele;
else {
if (arr != "")
dq.push_back(stoi(arr));
arr = "";
}
}
bool flag = false; // 에러 발생 여부
bool dir = true; // 방향
for (auto ord : p) {
if (ord == 'R')
dir = !dir;
else {
if (!dq.empty() && dir)
dq.pop_front();
else if (!dq.empty() && !dir)
dq.pop_back();
// 방향이 어찌됐든 dq는 비어있음
else {
flag = true;
break;
}
}
}
if (flag && dq.empty())
cout << "error\n";
else {
// 역순이어야하면 뒤집기
if (!dir)
reverse(dq.begin(), dq.end());
string ans = "[";
int count = 1;
for (auto ele : dq) {
if (count != dq.size())
ans += (to_string(ele) + ",");
else
ans += to_string(ele);
count++;
}
cout << ans << "]\n";
}
}
return 0;
}
Python)
import sys
from collections import deque
read = sys.stdin.readline
t = int(read().rstrip())
for _ in range(t):
p = read().rstrip()
n = read().rstrip()
temp = read().rstrip()
dq = deque()
num = ''
for i in temp[1:]:
if i != ',' and i != ']':
num += i
else:
if num:
dq.append(int(num))
num = ''
ans = ''
# False -> reverse 상태
# True -> 원래
dir = True
flag = False
for ord in p:
if ord == 'R':
dir = not dir
else:
if dq and dir:
dq.popleft()
elif dq and not dir:
dq.pop()
else:
flag = True
break
if flag and not dq:
print('error')
else:
if not dir:
dq.reverse()
print('[' + ','.join(list(map(str,dq))) + ']')
C++이랑 파이썬 로직은 동일하다.
1. 입력받은 [x1, x2, ..., xn]으로부터 숫자만 추출해서 덱에 넣어준다.
2. 명령을 수행하는데 리버스의 경우 매번 뒤집기를 수행하면 시간이 오래걸리기 때문에 dir이라는 변수를 이용해서 방향이 앞인지 뒤인지 구분한다.
2.1 덱이 비어있는데 버리려고 한다면 error 발생 → flag를 이용해서 구분
2.2 비어있는 덱을 뒤집는 것은 에러가 발생하지 않는다. (16%에서 틀렸다고 뜬다면 여기서 틀렸을 가능성이 높다.)
3. 명령들을 전부 수행한 후 결과 출력
'백준 1 > 자료구조' 카테고리의 다른 글
| [백준 10799] 쇠막대기 (C++/Python) (0) | 2023.06.23 |
|---|---|
| [백준 1021] 회전하는 큐 (C++/Python) (0) | 2023.06.22 |
| [백준 2164] 카드2 (C++/Python) (0) | 2023.06.20 |
| [백준 18258] 큐2 (C++/Python) (0) | 2023.06.19 |
| [백준 3015] 오아시스 재결합 (C++/Python) (0) | 2023.06.15 |