λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
Algorithm πŸ§‘πŸ»‍πŸ’»/λ°±μ€€(BOJ)

[λ°±μ€€,c++] 2493번 - 탑

by dkswnkk 2022. 6. 3.

문제

 

2493번: 탑

첫째 쀄에 νƒ‘μ˜ 수λ₯Ό λ‚˜νƒ€λ‚΄λŠ” μ •μˆ˜ N이 주어진닀. N은 1 이상 500,000 μ΄ν•˜μ΄λ‹€. λ‘˜μ§Έ μ€„μ—λŠ” N개의 νƒ‘λ“€μ˜ 높이가 직선상에 놓인 μˆœμ„œλŒ€λ‘œ ν•˜λ‚˜μ˜ λΉˆμΉΈμ„ 사이에 두고 주어진닀. νƒ‘λ“€μ˜ λ†’μ΄λŠ” 1

www.acmicpc.net

 

μ½”λ“œ

#include <iostream>
#include <stack>
using namespace std;

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    
    int N; cin>>N;
    stack<pair<int,int>>st; // {탑 번호, 높이}
    
    for(int i=0; i<N; i++){
        int height; cin>>height;

        while(!st.empty()){
            if(st.top().second>height){
                cout<<st.top().first<<' ';
                break;
            }
            st.pop();
        }
        if(st.empty()) cout<< 0 <<' ';
        st.push({i+1,height});
        
    }
}

 

풀이

stack에 {탑 번호, 높이} ν˜•μ‹μœΌλ‘œ μ €μž₯을 ν•˜κΈ° μœ„ν•΄ pair νƒ€μž…μœΌλ‘œ μ„ μ–Έν•©λ‹ˆλ‹€.

솑신탑을 μž…λ ₯받을 λ•Œλ§ˆλ‹€ stack을 μ°ΎλŠ”λ°, λ§Œμ•½ ν˜„μž¬ μŠ€νƒμ΄ λΉ„μ–΄μžˆμ§€ μ•Šλ‹€λ©΄ ν˜„μž¬ μ†‘μ‹ νƒ‘μ˜ 높이보닀 큰 높이가 λ‚˜μ˜¬ λ•ŒκΉŒμ§€ μŠ€νƒμ„ λΉ„μ›Œκ°‘λ‹ˆλ‹€. λ§Œμ•½ ν˜„μž¬ 솑신탑보닀 큰 높이λ₯Ό λ°œκ²¬ν–ˆλ‹€λ©΄ κ·Έ 솑신탑은 μ§€μš°μ§€ 말아야 ν•©λ‹ˆλ‹€.

κ·Έ ν›„, while문을 λΉ μ Έλ‚˜μ™”μ„ λ•Œ μŠ€νƒμ΄ λΉ„μ–΄μžˆλ‹€λ©΄ ν˜„μž¬ 솑신탑보닀 높은 탑이 μ—†λ‹€λŠ” 말이 λ˜κΈ°μ— 0을 좜λ ₯ν•©λ‹ˆλ‹€.

그리고 κ³΅ν†΅μ μœΌλ‘œ ν˜„μž¬μ˜ 솑신탑은 μŠ€νƒμ— λ„£μ–΄μ€λ‹ˆλ‹€.

제일 처음 ν’€μ—ˆμ„λ•ŒλŠ” μ•„λž˜μ™€ 같이 쑰금 λ”λŸ½κ²Œ ν’€μ—ˆμ—ˆμŠ΅λ‹ˆλ‹€.

#include <iostream>
#include <stack>
using namespace std;

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    
    int N; cin>>N;
    stack<pair<int,int>>st; // {탑 번호, 높이}
    
    for(int i=0; i<N; i++){
        int height; cin>>height;
        if(i==0){
            cout<<0<<' ';
            st.push({i+1, height});
            continue;
        }
        while(!st.empty()){
            if(st.top().second>height){
                cout<<st.top().first<<' ';
                st.push({i+1, height});
                break;
            }
            else{
                bool flag = false;
                while(!st.empty()){
                    if(st.top().second<height) st.pop();
                    else{
                        flag = true;
                        cout<<st.top().first<<' ';
                        break;
                    }
                }
                if(!flag) cout<<0<<' ';
                st.push({i+1, height});
                break;
            }
        }
        
    }
}

λŒ“κΈ€