[Programmers] Lv3. ์ด์ค‘์šฐ์„ ์ˆœ์œ„ํ | C++

2023. 9. 10. 16:26ใ†Coding Test/Programmers

๐Ÿ”—๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ
 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

๐Ÿง‘‍๐Ÿ’ปํ’€์ด ๊ณผ์ •

 

(1)์ž๋™์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ๋˜๊ณ , (2)์ค‘๋ณต ์ˆซ์ž ์ €์žฅ์ด ๋˜๋ฉฐ, (3)์ตœ์†Ÿ๊ฐ’๊ณผ ์ตœ๋Œ“๊ฐ’์— ๋ฐ”๋กœ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋Š” ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ์„ ์ •ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๋„ค, ๋ฐ”๋กœ multiset์ด์ฃ . multiset์„ ์ด์šฉํ•˜๋ฉด ์‰ฝ๊ฒŒ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์•Œ๊ณ ๋ฆฌ์ฆ˜์€ ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

 

  1. ๊ณต๋ฐฑ์„ ๊ธฐ์ค€์œผ๋กœ ์ž…๋ ฅ์„ ๋ถ„๋ฆฌํ•˜์—ฌ, "๋ช…๋ น์–ด"์™€ "๋ฐ์ดํ„ฐ" ๋ฌธ์ž์—ด๋กœ ๋ถ„๋ฆฌํ•ฉ๋‹ˆ๋‹ค.
  2. "๋ช…๋ น์–ด"๊ฐ€ 'I(๋Œ€๋ฌธ์ž i)'๋ผ๋ฉด, multiset์— ๋ฐ์ดํ„ฐ๋ฅผ ์‚ฝ์ž…ํ•ฉ๋‹ˆ๋‹ค.
  3. "๋ช…๋ น์–ด"๊ฐ€ 'D'๋ผ๋ฉด, ๊ทธ ๋’ค์— ์˜ค๋Š” ๋ฐ์ดํ„ฐ๊ฐ€ 1์ด๋ƒ, -1์ด๋ƒ์— ๋”ฐ๋ผ ๋ถ„๊ธฐ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค.
    •  multiset์ด ๋น„์—ˆ๋‹ค๋ฉด, ๋ฌด์‹œํ•ฉ๋‹ˆ๋‹ค.
    • ๋ฐ์ดํ„ฐ๊ฐ€ 1์ด๋ผ๋ฉด ์ตœ๋Œ“๊ฐ’์„ ์ œ๊ฑฐํ•ด์•ผ ํ•˜๋ฏ€๋กœ, multiset.end() - 1์„ ์ œ๊ฑฐํ•ฉ๋‹ˆ๋‹ค.
    • ๋ฐ์ดํ„ฐ๊ฐ€ -1์ด๋ผ๋ฉด ์ตœ์†Ÿ๊ฐ’์„ ์ œ๊ฑฐํ•ด์•ผ ํ•˜๋ฏ€๋กœ, multiset.begin()์„ ์ œ๊ฑฐํ•ฉ๋‹ˆ๋‹ค.
  4. ๋ชจ๋“  ๋ช…๋ น์„ ์ฒ˜๋ฆฌ ํ•œ ํ›„, ๋‹ต์„ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค.
    • multiset์ด ๋น„์—ˆ๋‹ค๋ฉด, {0, 0}์„ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค.
    • ๋น„์–ด ์žˆ์ง€ ์•Š๋‹ค๋ฉด, { *multiset.rbegin(), *multiset.begin() }์„ ๋ฆฌํ„ดํ•ฉ๋‹ˆ๋‹ค.

 

โœ๏ธ์†Œ์Šค ์ฝ”๋“œ ๋ฐ ๊ฒฐ๊ณผ

#include <string>
#include <vector>
#include <set>
#include <sstream>
using namespace std;

class DoublePriorityQueue
{
public:
    vector<int> GetAnswer();
    void Operate(const char instruction, int data);
    bool IsEmpty() const { return _queue.empty(); }
private:
    multiset<int> _queue;
};

void DoublePriorityQueue::Operate(const char instruction, int data)
{
    switch (instruction)
    {
    case 'I':
        _queue.emplace(data);
        break;

    case 'D':
        if (IsEmpty())
            return;

        if (data == 1)
        {
            auto maxIter = _queue.end();
            _queue.erase(--maxIter);
        }

        else if (data == -1)
        {
            auto minIter = _queue.begin();
            _queue.erase(minIter);
        }
    }
}

vector<int> DoublePriorityQueue::GetAnswer()
{
    if (IsEmpty())
        return { 0, 0 };
    return { (*_queue.rbegin()), (*_queue.begin()) };
}

vector<int> solution(vector<string> operations) {
    DoublePriorityQueue dpQueue;

    for (const auto& operation : operations)
    {
        istringstream iss(operation);
        string instruction, data;
        iss >> instruction >> data;

        dpQueue.Operate(instruction[0], stoi(data));
    }

    return dpQueue.GetAnswer();
}

 

 

728x90
๋ฐ˜์‘ํ˜•