https://www.acmicpc.net/problem/5430
아이디어:
1. [1,2,3,4]의 형태로 입력됐을 때, 덱 안에 1 2 3 4를 순서대로 push_back() 해주는 parse() 함수를 따로 작성
int dat라는 임시 값에 char형 숫자가 들어올 때 이전값 * 10을 하고 들어온 숫자에서 48 ('0'에 해당)을 뺀 수를 더한다.
2. 덱 안의 값을 [1, 2, 3, 4]의 형태로 출력하는 print() 함수를 따로 작성
3. 'R'이 나올 때마다 reverse()를 하면 시간초과에 걸린다. 'R'은 토글 스위치처럼 0 과 1로 처리한다.
4. 'R'이 1이면 reverse()된 상태이므로 pop_front()가 아닌 pop_back() 한다.
'R'이 0이면 원래대로 pop_front() 한다.
5. 'R'이 입력되고 []이 입력되면 "error"를 출력하지않는다. 즉, 'D'만 error를 검출한다. 'R'은 빈 덱 []을 허용한다.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
// Answer Code
void parse(deque<int>& dq) {
string tmp;
cin >> tmp;
int dat = 0;
for (auto x : tmp) {
if (x == '[') continue;
else if (x == ',' || x == ']') {
dq.push_back(dat);
dat = 0;
}
else {
dat = 10 * dat + (x - 48);
}
}
if (tmp.length() == 2)
dq.clear();
}
void print(deque<int>& dq) {
cout << "[";
for (int i = 0; i < dq.size(); i++) {
cout << dq[i];
if (i != dq.size() - 1)
cout << ",";
}
cout << "]\n";
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T, n;
string str;
cin >> T;
while (T--) {
deque<int> DQ;
cin >> str;
cin >> n;
parse(DQ);
int r = 0;
bool isWrong = false;
for (auto x : str) {
if (x == 'R') {
r = 1 - r;
}
else if (x == 'D'){
if (DQ.empty()) {
isWrong = true;
break;
}
if (r == 0) DQ.pop_front();
else DQ.pop_back();
}
}
if (r == 1)
reverse(DQ.begin(), DQ.end());
if (isWrong) cout << "error\n";
else print(DQ);
}
return 0;
}
나의 풀이
1. print()에서 만약 덱 안의 값들이 다 같다면 dq.back()과 같다는 if 조건이 충족되면서 "]\n"을 계속 입력한다.
(ex. [15, 15, 15] 인 경우 [15]\n15]15] 로 출력)
2. R이 들어올 때마다 reverse() 함수를 호출해서 시간초과를 일으킨다.
3. "R"에는 빈 덱 "[]"을 출력해야하는데 비어있으면 무조건 "error"를 출력한다.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void parse(deque<int>& dq) {
string tmp;
cin >> tmp;
int dat = 0;
for (auto x : tmp) {
if (x == '[') continue;
else if (x == ',' || x == ']') {
dq.push_back(dat);
dat = 0;
}
else {
dat = 10 * dat + (x - 48);
}
}
if (tmp.length() == 2)
dq.clear();
}
void print(deque<int>& dq) {
cout << "[";
for (auto x : dq) {
cout << x;
if (x != dq.back())
cout << ",";
else
cout << "]\n";
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T, n;
string str;
cin >> T;
while (T--) {
deque<int> DQ;
cin >> str;
cin >> n;
parse(DQ);
for (auto x : str) {
if (x == 'R') {
reverse(DQ.begin(), DQ.end());
}
else if (x == 'D'){
if (DQ.empty()) {
cout << "error\n";
break;
}
else DQ.pop_front();
}
}
if (!DQ.empty())
print(DQ);
}
return 0;
}
'algorithm' 카테고리의 다른 글
백준 4949번 균형잡힌 세상 (0) | 2025.04.03 |
---|---|
백준 11003번 최솟값 찾기 - 덱 정렬 (0) | 2025.04.01 |
백준 1021번 회전하는 큐 (0) | 2025.03.30 |
백준 10866번 덱 (0) | 2025.03.30 |
덱 (0) | 2025.03.30 |