Post

baekjoon 5430:AC

baekjoon 5430 AC

5430번 AC

접근

vector풀려고 했는데 앞에서 지우는 방식이 없어서 포기했다.
찾아보다보니 deque라는 좋은 자료형이 있었다. double ended queue의
약자인 deque는 양쪽에서 삽입과 삭제가 가능하다. R로 방향 바꿀 때 실제 데이터의 방향을 바꾸지 않고 기록만 해두었다가
그 방향대로 출력만 잘 해주면 될 것 같다.

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <deque>
#include <sstream>
using namespace std;
int main(){
  ios::sync_with_stdio(false);
  cin.tie(0); cout.tie(0);
  int t; cin >> t;
  while(t--){
    string p; cin >> p;
    int n; cin >> n;
    deque<int> q;
    string arr; cin >> arr;
    //build arr
    arr = arr.substr(1, arr.size()-2);
    stringstream ss(arr);
    string temp;
    while (getline(ss, temp, ',')) {
      if (!temp.empty()) {
        q.push_back(stoi(temp));  // Convert substring to integer and add to vector
      }
    }
    
    bool reverse = false;
    bool errorA = false;
    for(auto i : p){
      if(i == 'R'){
        reverse = !reverse;
      }
      else if(i == 'D'){
        if(q.empty()){
          cout << "error\n";
          errorA = true;
          break;
        }
        if(reverse){
          q.pop_back();
        }
        else{
          q.pop_front();
        }
      }
    }
    
    if(!errorA){
      if(reverse){
        cout << "[";
        for(auto i = q.rbegin(); i != q.rend(); i++){
          cout << *i;
          if(next(i) != q.rend()){
            cout << ",";
          }
        }
        cout << "]\n";
      }
      else{
        cout << "[";
        for(auto i = q.begin(); i != q.end(); i++){
          cout << *i;
          if(next(i) != q.end()){
            cout << ",";
          }
        }
        cout << "]\n";
      }
    }
    
  }
  return 0;
}

배운 점

deque의 사용법에 대해 배웠다.

This post is licensed under CC BY 4.0 by the author.