๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/๋ฐฑ์ค€(BOJ)

[๋ฐฑ์ค€,c++] 2812๋ฒˆ - ํฌ๊ฒŒ ๋งŒ๋“ค๊ธฐ

by ์•ˆ์ฃผํ˜• 2022. 7. 29.

๋ฌธ์ œ

 

2812๋ฒˆ: ํฌ๊ฒŒ ๋งŒ๋“ค๊ธฐ

N์ž๋ฆฌ ์ˆซ์ž๊ฐ€ ์ฃผ์–ด์กŒ์„ ๋•Œ, ์—ฌ๊ธฐ์„œ ์ˆซ์ž K๊ฐœ๋ฅผ ์ง€์›Œ์„œ ์–ป์„ ์ˆ˜ ์žˆ๋Š” ๊ฐ€์žฅ ํฐ ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

www.acmicpc.net

 

์ฝ”๋“œ

#include <iostream>
#include <stack>
#include <algorithm>

using namespace std;

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    
    int N, K; cin>>N>>K;
    string num; cin>>num;
    stack<char> st;
    int remove_cnt = 0;
    int i=0;
    
    for(i; i<N; i++){
        if(st.empty()) st.push(num[i]);
        else if(st.top()>num[i]) st.push(num[i]);
        else{
            while(true){
                if(!st.empty() && num[i]>st.top()){
                    if(remove_cnt == K) break;
                    st.pop();
                    remove_cnt++;
                }
                else break;
            }
            st.push(num[i]);
        }
    }
    

    string ans = "";
    while(!st.empty()){
        ans += st.top();
        st.pop();
    }
    reverse(ans.begin(), ans.end());
    ans = ans.substr(0, N-K);
    cout<<ans;
}

 

ํ’€์ด

stack์„ ํ™œ์šฉํ•˜์—ฌ ํ•ด๊ฒฐํ–ˆ์Šต๋‹ˆ๋‹ค.

  1. ์ด์ „์˜ ์ˆซ์ž๋ณด๋‹ค ํ˜„์žฌ์˜ ๊ฐ’์ด ํฌ๋‹ค๋ฉด ํ˜„์žฌ๋ณด๋‹ค ๊ฐ€์žฅ ํฐ ๊ฐ’์ด ๋‚˜์˜ค๊ธฐ ์ „๊นŒ์ง€ ์Šคํƒ์˜ ๋ชจ๋“  ๊ฐ’๋“ค์„ ์ง€์›๋‹ˆ๋‹ค.
  2. ์ด์ „์˜ ์ˆซ์ž๊ฐ€ ํ˜„์žฌ์˜ ๊ฐ’๋ณด๋‹ค ํฌ๋‹ค๋ฉด ํ˜„์žฌ์˜ ๊ฐ’์„ ์ถ”๊ฐ€ํ•ฉ๋‹ˆ๋‹ค.
  3. ์Šคํƒ์˜ ๋ฌธ์ž์—ด์„ 0, n-k ๊ธธ์ด๊นŒ์ง€ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

์ด๋ฏธ k๊ฐœ๋ฅผ ์ œ๊ฑฐํ–ˆ์Œ์—๋„ ๋ถˆ๊ตฌ ํ•˜๊ณ  3๋ฒˆ ์ž‘์—…์„ ํ•˜๋Š” ์ด์œ ๋Š” ์•„๋ž˜์™€ ๊ฐ™์ด ํฌ๊ธฐ๊ฐ€ ๊ฐ™์€ ์ˆซ์ž๋งŒ ์žˆ์–ด์„œ ์ „๋ถ€ ์Šคํƒ์— push ๋  ๊ฒฝ์šฐ๊ฐ€ ์žˆ๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค.

2 1
1 1

๋Œ“๊ธ€