알고리즘

백준(5430) - AC

SniKuz 2024. 6. 14. 12:43

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


문제 설명

아래 2가지 명령을 바탕으로한 명령조합과 자연수로 이루어진 배열이 주어질 때, 명령을 모두 수행한 후 배열의 최종 결과를 구하는 프로그램을 작성하세요. 단, 명령 수행 중 더 이상 배열에 수가 없을 시 error를  출력하세요.

R : 배열에 있는 수의 순서를 뒤집습니다. (ex : [1,2,3,4] → [4,3,2,1])
D : 첫 번째 수를 버립니다. (ex: [1,2,3,4] → [2,3,4])


아이디어

  • R 명령처럼 실제로 배열을 계속 뒤집기는 힘들어 방향을 가르키는 변수만 가지고 방향을 체크하면 좋을 것 같습니다.
  • D 명령을 위해 앞과 뒤에 자료를 쉽게 제거할 수 있는 자료구조인 double ended queue면 좋을 것 같습니다.

코드

#include <bits/stdc++.h>

using namespace std;

deque<int> split(const string& str)
{
    string substr = str.substr(1, str.size()-2);
    istringstream iss(substr);
    string buffer;
    deque<int> ret;

    while(getline(iss, buffer, ','))
    {
        ret.push_back(stoi(buffer));
    }
    return ret;
}

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

    int T;
    cin >> T;

    for(int i = 0; i < T; ++i)
    {
        string cmds;
        cin >> cmds;
        int len;
        cin >> len;
        string testCase;
        cin >> testCase;
        auto ret = split(testCase);
        bool front = true;
        bool err = false;
        for(char cmd : cmds)
        {
            if(cmd == 'R')
            {
                front = !front; 
            }
            else // cmd == 'D'
            {
                if(ret.empty())
                {
                    err = true;
                    break;
                }
                else if(front)
                {
                    ret.pop_front();
                }
                else
                {
                    ret.pop_back();
                }
            }
        }

        if(err)
        {
            cout << "error\n";
        }
        else
        {
            string tmp = "[";
            if(ret.empty())
            {
                tmp += "]";
            }
            else if(front)
            {
                for(auto s = ret.begin(); s != ret.end(); s++)
                {
                    tmp += to_string(*s);
                    tmp += ',';
                }
                tmp[tmp.size()-1] = ']';
            }
            else
            {
                for(auto s = ret.rbegin(); s!=ret.rend(); s++)
                {
                    tmp += to_string(*s);
                    tmp += ',';
                }
                tmp[tmp.size()-1] = ']';
            }
            cout << tmp << '\n';
        }
    }

    return 0;
}