짱아의 개발 기록장

백준 5430번. AC(c++) / 투포인터 본문

Algorithm/Baekjoon

백준 5430번. AC(c++) / 투포인터

jungahshin 2021. 5. 4. 14:50
반응형

R연산을 할 때 그냥 reverse를 써서 구현하다가... 시간초과가 났다.

시간초과나는 것이 당연한게 최악의 경우를 생각해보면, n이 10만개+ R연산이 10만개 => 10만*10만이 되어서 터진다...

그래서 투포인터로 구현해야한다.

 

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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// AC
// 그냥 쉽게 reverse를 사용하려고 하면 매번 최대 10만개를 옮기다보니....당연,,, 시간초과가 난다.(10만*10만)
// 투포인터로 시간을 매우 줄일 수 있다...!
#include <algorithm>
#include <queue>
#include <iostream>
using namespace std;
 
int testcase, n;
string p, arr;
 
int main()
{
    cin>>testcase;
    for(int i=0; i<testcase; i++){
        cin>>p;
        cin>>n;
        cin>>arr;
        string tmp = "";
        vector<int> dq;
        for(int j=0; j<arr.size(); j++){
            if(arr[j]!='[' && arr[j]!=']' && arr[j]!=','){
                tmp += arr[j];
            }else{
                if(tmp.size()>0){
                    dq.push_back(stoi(tmp));
                    tmp = "";
                }
            }
        }
 
        int Start = 0, End = dq.size()-1;
        bool isAscend = true;
 
        bool isError = false;
        for(int j=0; j<p.size(); j++){
            if(p[j]=='R'){
                isAscend = !isAscend;
                swap(Start, End);
            }else{
                if(isAscend){
                    if(Start>End){
                        isError = true;
                        break;
                    }else{
                        Start++;
                    }
                }else{
                    if(Start<End){
                        isError = true;
                        break;
                    }else{
                        Start--;
                    }
                }
            }
        }
        
        if(isError){
            cout<<"error"<<"\n";
            continue;
        }
 
        if(isAscend){
            if(Start>End) cout<<"[]"<<"\n";
            else{
                string ans = "";
                ans += '[';
                for(int j=Start; j<=End; j++){
                    ans += to_string(dq[j]);
                    ans += ',';
                }
                ans.pop_back();
                ans += ']';
                cout<<ans<<"\n"
            }            
        }else{
            if(Start<End) cout<<"[]"<<"\n";
            else{
                string ans = "";
                ans += '[';
                for(int j=Start; j>=End; j--){
                    ans += to_string(dq[j]);
                    ans += ',';
                }
                ans.pop_back();
                ans += ']';
                cout<<ans<<"\n"
            }
        }
    }
 
    return 0;
}
cs
반응형
Comments