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

 

5430번: AC

각 테스트 케이스에 대해서, 입력으로 주어진 정수 배열에 함수를 수행한 결과를 출력한다. 만약, 에러가 발생한 경우에는 error를 출력한다.

www.acmicpc.net

[난이도] Gold5
[유형] 구현

[풀이]
배열에 직접 원소를 넣어서 reverse,pop 연산을 하게되면 시간초과가 발생한다.
배열 대신 배열의 왼쪽 index 'l', 오른쪽 index 'r', 현재 뒤집혀 있는지를 체크하는 flag 'rvs' 를 유지하면서
R,D 커맨드마다 위 변수들을 적절히 조절해주면 된다.

주의할 점은 배열에 원소가 모두 삭제되었을 때 배열을 뒤집는 R 연산을 해도 error가 아니라는 점이다.

 

#include <cstdio>
#include <string>
#include <iostream>
#include <vector>
using namespace std;
int T,N,K;
string cmd,s;
int main(){
    ios_base::sync_with_stdio(false); 
    cin.tie();
    cin >> T;
    while(T--){
        cin >> cmd >> N >> s;
        vector<int> v;
        int prev=1;
        for(int i=1;i<s.size();i++){
            if(i-prev>0){
                if(s[i]==',' || s[i]==']'){
                    string t = s.substr(prev,i-prev);
                    v.push_back(stoi(t));
                    prev=i+1;
                }
            }
        }
        int l=0,r=N-1;
        bool rvs=0,err=0;
        for(auto& c : cmd){
            if(c=='R') rvs = !rvs;
            else{
                if(l>r) {
                    err=1;
                    break;
                }
                if(rvs==0) l++;
                else r--;
            }
        }
        if(err){
            cout << "error" << '\n';
            continue;
        }
        cout << '[';
        if(!rvs) {
            for(int i=l;i<=r;i++){
                cout << v[i];
                if(i!=r) cout << ',';
            }
        }else{
            for(int i=r;i>=l;i--){
                cout << v[i];
                if(i!=l) cout << ',';
            }            
        }
        cout << ']' << '\n';   
    }
} 

 

https://github.com/has2/Problem-Solving/blob/master/boj-solved.ac/Gold5/5430.cpp

 

 

 

 

+ Recent posts