λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°

πŸ“ μ•Œκ³ λ¦¬μ¦˜/Programmers

[C++/PGS] Lv.3 : μ΄μ€‘μš°μ„ μˆœμœ„ν

728x90

문제 μ„€λͺ…

이쀑 μš°μ„ μˆœμœ„ νλŠ” λ‹€μŒ 연산을 ν•  수 μžˆλŠ” 자료ꡬ쑰λ₯Ό λ§ν•©λ‹ˆλ‹€.

λͺ…λ Ήμ–΄μˆ˜μ‹  탑(높이)
I 숫자 큐에 주어진 숫자λ₯Ό μ‚½μž…ν•©λ‹ˆλ‹€.
D 1 νμ—μ„œ μ΅œλŒ“κ°’μ„ μ‚­μ œν•©λ‹ˆλ‹€.
D -1 νμ—μ„œ μ΅œμ†Ÿκ°’μ„ μ‚­μ œν•©λ‹ˆλ‹€.

이쀑 μš°μ„ μˆœμœ„ 큐가 ν•  μ—°μ‚° operationsκ°€ λ§€κ°œλ³€μˆ˜λ‘œ μ£Όμ–΄μ§ˆ λ•Œ, λͺ¨λ“  연산을 μ²˜λ¦¬ν•œ ν›„ 큐가 λΉ„μ–΄μžˆμœΌλ©΄ [0,0] λΉ„μ–΄μžˆμ§€ μ•ŠμœΌλ©΄ [μ΅œλŒ“κ°’, μ΅œμ†Ÿκ°’]을 return ν•˜λ„λ‘ solution ν•¨μˆ˜λ₯Ό κ΅¬ν˜„ν•΄μ£Όμ„Έμš”.

μ œν•œμ‚¬ν•­
  • operationsλŠ” 길이가 1 이상 1,000,000 μ΄ν•˜μΈ λ¬Έμžμ—΄ λ°°μ—΄μž…λ‹ˆλ‹€.
  • operations의 μ›μ†ŒλŠ” 큐가 μˆ˜ν–‰ν•  연산을 λ‚˜νƒ€λƒ…λ‹ˆλ‹€.
    • μ›μ†ŒλŠ” “λͺ…λ Ήμ–΄ 데이터” ν˜•μ‹μœΌλ‘œ μ£Όμ–΄μ§‘λ‹ˆλ‹€.- μ΅œλŒ“κ°’/μ΅œμ†Ÿκ°’μ„ μ‚­μ œν•˜λŠ” μ—°μ‚°μ—μ„œ μ΅œλŒ“κ°’/μ΅œμ†Ÿκ°’μ΄ λ‘˜ 이상인 경우, ν•˜λ‚˜λ§Œ μ‚­μ œν•©λ‹ˆλ‹€.
  • 빈 큐에 데이터λ₯Ό μ‚­μ œν•˜λΌλŠ” 연산이 μ£Όμ–΄μ§ˆ 경우, ν•΄λ‹Ή 연산은 λ¬΄μ‹œν•©λ‹ˆλ‹€.

κ½€ μ–΄λ ΅λ‹€!!

μ²˜μŒμ— 2, 6λ²ˆμ„ 톡과λͺ»ν•΄μ„œ ν—€λ©¨λŠ”λ° κ²°κ΅­ 고쳀음 γ…‹γ…‹

νλŠ” μ›μ†Œ 탐색이 λΆˆκ°€λŠ₯ν•΄μ„œ, μ΅œλŒ“κ°’ μ‚­μ œλŠ” pop으둜 μ²˜λ¦¬ν•˜κ³  μ΅œμ†Ÿκ°’ μ‚­μ œλŠ” λ‹€λ₯Έ λ°©λ²•μœΌλ‘œ μ²˜λ¦¬ν•΄μ€˜μ•Ό ν•©λ‹ˆλ‹·

 

 

μš°μ„ μˆœμœ„ 큐λ₯Ό μ‚¬μš©ν•΄μ„œ, D 1 μΌλ•ŒλŠ” κ·Έλƒ₯ popν•΄μ£Όκ³ 

D -1 μΌλ•ŒλŠ” μ‚¬μ΄μ¦ˆκ°€ μžˆμ„λ•Œ λˆ„μ κ°’μ„ μ‚­μ œν•΄μ€¬λŠ”λ°

μ²˜μŒμ—λŠ” ν˜„μž¬ 큐 μ‚¬μ΄μ¦ˆ(nowSize)λ₯Ό κ³ λ €ν•˜μ§€ μ•Šκ³  "D 1" pop을 μ§„ν–‰ν•΄μ„œ λͺ¨μˆœμ΄ 생긴 것 κ°™μ•˜λ‹€!!

 

이걸 κ³ μ³μ£Όλ‹ˆ λ‹€ λ§žμ•˜μŠ΅λ‹ˆλ‹€ ^-^

 

 

 

λ‚˜μ˜ 풀이

#include <string>
#include <vector>
#include <queue>
#include <iostream>
using namespace std;

vector<int> solution(vector<string> operations) {
    vector<int> answer;
    priority_queue<int> pq;
    int minDelete = 0;
    int nowSize = 0;
    for(int i=0; i<operations.size(); ++i){
        if(operations[i]=="D 1"){
            if(nowSize>0) {
                pq.pop();
                nowSize--;
            }
        }
        if(operations[i]=="D -1"){
            if(nowSize>0) {
                minDelete++;
                nowSize--;
            }
        }
        if(operations[i][0]=='I'){
            operations[i].replace(0,2,""); // 숫자만 남김
            int num = stoi(operations[i]);
            pq.push(num);
            nowSize++;
        }
    }
    if(nowSize==0 || nowSize <= minDelete) {
        answer.push_back(0);
        answer.push_back(0);
    }
    else {
        int pqtop = pq.top();
        while(pq.size()>minDelete+1) {
            cout << pq.top()<<" ";
            pq.pop();
        }
        answer.push_back(pqtop);
        answer.push_back(pq.top());
    }
    return answer;
}

 

728x90