๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿš“ Self Study/๐Ÿ”“ Programmers

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค (ํ”„๋ฆฐํ„ฐ, ์Šคํƒ/ํ) C++

by UKHYUN22 2022. 1. 4.
728x90

 

map์˜ ๊ฐœ๋…์œผ๋กœ index์™€ value๊ฐ€ ๋ชจ๋‘ ํ•„์š”ํ•œ ๋ฌธ์ œ์˜€๋‹ค. Map์„ ์ด์šฉํ•ด์„œ Pair๋ฅผ ๋งŒ๋“ค๊ณ  ์ด๋ฅผ Queue์— ๋„ฃ์–ด์ฃผ๋Š” ๋ฐฉ์‹์œผ๋กœ ์ ‘๊ทผ์„ ํ–ˆ๋‹ค๊ฐ€ ์ž˜ ๋˜์ง€ ์•Š์•˜๋‹ค. ๊ทธ๋ž˜์„œ queue ์ž์ฒด๋ฅผ ํ•œ ์Œ์„ ๋งŒ๋“ค์–ด์„œ ํ• ๋‹น์„ ํ–ˆ๋”๋‹ˆ ์ž˜ ํ’€๋ ธ๋‹ค. Queue๋ฅผ ์‚ฌ์šฉํ•ด์„œ ํ•œ ๋ฐฉ์— ๋ฌธ์ œ๊ฐ€ ํ’€๋ ธ๋‹ค... ๋„ˆ๋ฌด ๊ธฐ๋ถ„์ด ์ข‹์€๋ฐ...?

 

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

using namespace std;

int solution(vector<int> priorities, int location) {
    int answer = 0;
    int index = 0;
    queue<pair<int,int>> q;
    
    // key์— index ๊ฐ’์„ ๋„ฃ๊ณ  value์— ์šฐ์„ ์ˆœ์œ„๋ฅผ ๋„ฃ์–ด์ค€๋‹ค.
    for(int i =0 ; i < priorities.size() ; i++) {
        q.push(make_pair(i,priorities[i]));
    }
    
    // ์šฐ์„ ์ˆœ์œ„๋ฅผ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌ
    sort(priorities.begin(), priorities.end(), greater<int>());
    
    while(true) {
        // queue์˜ ๊ฐ€์žฅ ์•ž์˜ ์›์†Œ๊ฐ€ ๊ฐ€์žฅ ์šฐ์„ ์ˆœ์œ„๊ฐ€ ๋†’์€ ๊ฒƒ๊ณผ ๋™์ผํ•œ ๊ฒฝ์šฐ
        if(q.front().second == priorities[index]) {
            answer++;
            index++;
            if(q.front().first == location)
                break;
            q.pop();
        } 
        // ๊ฐ™์ง€ ์•Š์€ ๊ฒฝ์šฐ ๊ฐ€์žฅ ์•ž์˜ ์›์†Œ๋ฅผ ์ œ์ผ ๋’ค๋กœ ๋„ฃ์–ด์ค€๋‹ค.
        else {
            int first = q.front().first;
            int second = q.front().second;
            q.pop();
            q.push(make_pair(first, second));
        }
    }
    
    return answer;
}