본문 바로가기

Algorithm

C++(씨쁠쁠)(cplusplus)-백준(baekjoon)(BaekJoon)코딩 2812번:크게 만들기(스택) 답

반응형

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
#include <iostream>
#include <stack>
#include <cstring>
using namespace std;
char s[500001];
stack <char> t, tmp;
int main() {
    ios_base::sync_with_stdio(false);
    int n, k, i;
    cin >> n >> k >> s;
    int slen = strlen(s);
    for (i = 0; k;) {
        if (!t.empty() && (t.top() < s[i])) {//이미 들어있는 숫자가 들어올 숫자보다 작다면 pop
            t.pop();
            k -= 1;
        }
        else if (slen - i <= k) {//남은 문자열이 앞으로 지워야 할 문자열의 수보다 작거나 같을 때 스킵
            i += k;
k = 0;
        }
        else {
            t.push(s[i++]);
        }
    }
    while (!t.empty()) {
        tmp.push(t.top());
        t.pop();
    }
    while (!tmp.empty()) {
        cout << tmp.top();
        tmp.pop();
    }
    for (; s[i]; i++)
        cout << s[i];
}
 

cs