Hello Ocean! ๐ŸŒผ

[C++/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ด์ค‘์šฐ์„ ์ˆœ์œ„ํ ๋ณธ๋ฌธ

Algorithm

[C++/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ด์ค‘์šฐ์„ ์ˆœ์œ„ํ

bba_dda 2022. 3. 1. 20:27
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

https://programmers.co.kr/learn/courses/30/lessons/42628

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ์ด์ค‘์šฐ์„ ์ˆœ์œ„ํ

 

programmers.co.kr

์ด์ค‘ ์šฐ์„ ์ˆœ์œ„ ํ๋Š” ๋‹ค์Œ ์—ฐ์‚ฐ์„ ํ•  ์ˆ˜ ์žˆ๋Š” ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ๋งํ•ฉ๋‹ˆ๋‹ค.

 

๋ช…๋ น์–ด ์„ค๋ช…
I ์ˆซ์ž ํ์— ์ฃผ์–ด์ง„ ์ˆซ์ž๋ฅผ ์‚ฝ์ž…ํ•ฉ๋‹ˆ๋‹ค.
D 1 ํ์—์„œ ์ตœ๋Œ“๊ฐ’์„ ์‚ญ์ œํ•ฉ๋‹ˆ๋‹ค.
D -1 ํ์—์„œ ์ตœ์†Ÿ๊ฐ’์„ ์‚ญ์ œํ•ฉ๋‹ˆ๋‹ค.

์ด์ค‘ ์šฐ์„ ์ˆœ์œ„ ํ๊ฐ€ ํ•  ์—ฐ์‚ฐ operations๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ,

๋ชจ๋“  ์—ฐ์‚ฐ์„ ์ฒ˜๋ฆฌํ•œ ํ›„ ํ๊ฐ€ ๋น„์–ด์žˆ์œผ๋ฉด [0,0] ๋น„์–ด์žˆ์ง€ ์•Š์œผ๋ฉด [์ตœ๋Œ“๊ฐ’, ์ตœ์†Ÿ๊ฐ’]์„ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ๊ตฌํ˜„ํ•ด์ฃผ์„ธ์š”.

 

์ œํ•œ์‚ฌํ•ญ

  • operations๋Š” ๊ธธ์ด๊ฐ€ 1 ์ด์ƒ 1,000,000 ์ดํ•˜์ธ ๋ฌธ์ž์—ด ๋ฐฐ์—ด์ž…๋‹ˆ๋‹ค.
  • operations์˜ ์›์†Œ๋Š” ํ๊ฐ€ ์ˆ˜ํ–‰ํ•  ์—ฐ์‚ฐ์„ ๋‚˜ํƒ€๋ƒ…๋‹ˆ๋‹ค.
    • ์›์†Œ๋Š” “๋ช…๋ น์–ด ๋ฐ์ดํ„ฐ” ํ˜•์‹์œผ๋กœ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.- ์ตœ๋Œ“๊ฐ’/์ตœ์†Ÿ๊ฐ’์„ ์‚ญ์ œํ•˜๋Š” ์—ฐ์‚ฐ์—์„œ ์ตœ๋Œ“๊ฐ’/์ตœ์†Ÿ๊ฐ’์ด ๋‘˜ ์ด์ƒ์ธ ๊ฒฝ์šฐ, ํ•˜๋‚˜๋งŒ ์‚ญ์ œํ•ฉ๋‹ˆ๋‹ค.
  • ๋นˆ ํ์— ๋ฐ์ดํ„ฐ๋ฅผ ์‚ญ์ œํ•˜๋ผ๋Š” ์—ฐ์‚ฐ์ด ์ฃผ์–ด์งˆ ๊ฒฝ์šฐ, ํ•ด๋‹น ์—ฐ์‚ฐ์€ ๋ฌด์‹œํ•ฉ๋‹ˆ๋‹ค.

ํ’€์ด

C++ STL์˜ Priority Queue๋ฅผ ์ด์šฉํ•˜์˜€๋‹ค.

๋‹ค๋งŒ, ๋‚ด๋ฆผ์ฐจ์ˆœ์˜ ํ(minQ)์™€ ์˜ค๋ฆ„์ฐจ์ˆœ์˜ ํ(maxQ) ๋‘๊ฐœ๋ฅผ ์ด์šฉํ•˜๋Š” ๊ณผ์ •์—์„œ minQ์—์„œ popํ•œ ์›์†Œ๋ฅผ maxQ์—์„œ๋„ ์ง€์šธ ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์—, count๋ณ€์ˆ˜๋ฅผ ๋”ฐ๋กœ ์ด์šฉํ•˜์˜€๋‹ค.

 

ํ์— insertํ•  ๋•Œ count++

maxQ or minQ์—์„œ popํ•  ๋•Œ count--

 

count == 0 ์ด ๋˜๋ฉด, minQ, maxQ๋ฅผ ๋ชจ๋‘ ์ดˆ๊ธฐํ™”ํ•ด์ฃผ์—ˆ๋‹ค. 

์ฝ”๋“œ

#include <string>
#include <vector>
#include <queue>
#include <iostream>

using namespace std;

int count = 0;
priority_queue<int, vector<int>, greater<int>> minQ;
priority_queue<int, vector<int>, less<int>> maxQ;

void operation(string op) {
    if (op[0] == 'I') {
        string num = op.substr(2);
        int n = stoi(num);
        maxQ.push(n);
        minQ.push(n);
        count++;
    }
    if (op[0] == 'D') {
        if (count <= 0) {
            return;
        }
        if (op[2] == '1') { // ์ตœ๋Œ“๊ฐ’ ์‚ญ์ œ
            maxQ.pop();
            count--;
        }
        else { // ์ตœ์†Ÿ๊ฐ’ ์‚ญ์ œ
            minQ.pop();
            count--;
        }
        if (count == 0) {
            minQ= priority_queue<int, vector<int>, greater<int>>();
            maxQ = priority_queue<int, vector<int>, less<int>>();
        }
    }
}
vector<int> solution(vector<string> operations) {
    vector<int> answer;
    for (string op: operations) {
        operation(op);
    }
    if (count == 0) {
        return {0,0};
    }
    else {
        return {maxQ.top(), minQ.top()};
    }
}

๊ฒฐ๊ณผ

 

๋ฐ˜์‘ํ˜•