알고리즘/백준

[백준] 골드5 5430번 - AC 문제풀이 (C++)

개발초고수 2023. 5. 2. 22:47

유의사항 :  배열을 일일이 뒤집으려하면 안된다. 또한, 배열을 삭제하는 연산을 수행하면 안된다.(시간 초과)

 

접근법 :

1. 배열을 뒤집는 것은 배열을 읽는 방향을 가리키는 변수를 선언하여 뒤집을 때마다 읽는 방향을 바꿔주는 방식으로 구현한다.

2. 배열의 삭제는 입력받은 숫자 배열의 앞과 뒤의 가리키는 인덱스 변수를 각각 두어 이를 증감시키는 방식으로 구현한다.

 

#include <stdlib.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <stack>
#include <cmath>
#include <string>
#include <queue>


using namespace std;
int T;

void func(string command, string arr, int cnt){
    int idx = 1;
    vector<int> numvec;

    // 문자열을 숫자로 변환하여 numvec 에 담아주는 과정
    for(int i = 0; i < cnt; i++){
        string numString = "";
        while(idx < arr.length() && arr[idx] != ',' && arr[idx] != ']'){
            numString += arr[idx];
            idx ++;
        }
        idx++;
        numvec.push_back(stoi(numString));
    }


    idx = 0;
    int sttIdx = 0;
    int endIdx = numvec.size() - 1;
    int dir = 1;
    while(idx < command.length()){
        // 뒤집기 연산일 때 뒤에 이어지는 R의 개수를 세어 한번에 뒤집는다.
        if(command[idx] == 'R'){
            int tmp = idx;
            
            while(command[tmp] == 'R'){
                tmp ++;
            }
            if((tmp - idx) % 2 == 1){ // R 개수가 홀수이면 뒤집기
                dir *= -1; // 읽기 방향을 반대로 바꾼다.
            }
            idx = tmp;
        }else{ // 삭제 연산일 때 읽기 방향에 따라 시작과 끝 인덱스를 조정한다.
            if(dir == 1){
                sttIdx ++;
            }
            else{
                endIdx --;
            }
            idx ++;
        }
    }

    cout << "[";
    if(dir == 1){ // 읽기 방향에 따라 출력하고 종료
        for(int i = sttIdx; i <= endIdx; i ++){
            if(i == endIdx)
                cout << numvec[i];
            else
                cout << numvec[i] << ",";
        }
    }
    else{
        for(int i = endIdx; i >= sttIdx; i --){
            if(i == sttIdx)
                cout << numvec[i];
            else
                cout << numvec[i] << ",";
        }
    }
    cout << "]";
    cout << '\n';
}

int main(){
    cin >> T;
    vector<pair<pair<string, int>, string>> list;
    for(int tc = 0; tc <T; tc++){ // 테스트케이스를 모아서 list에 담는다.
        int cnt;
        string command;
        string arr;
        cin >> command >> cnt >> arr;
        list.push_back({{command, cnt}, arr});
    }


    for(int tc = 0; tc < T; tc++){
        string command = list[tc].first.first;
        string arr = list[tc].second;
        int dCnt = 0;
        for(int i = 0; i < command.length(); i++){
            if(command[i] == 'D'){
                dCnt ++;
            }
        }
        // D의 개수가 숫자 배열의 길이보다 크면 error 출력
        if(dCnt > list[tc].first.second){
            cout << "error" << '\n';
        }else{
            func(command, arr, list[tc].first.second);
        }
    }

    
    
    return 0;
}