๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค(Programmers)

[c++] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ๊ตฌ๋ช…๋ณดํŠธ(Level 2)

by dkswnkk 2022. 4. 25.

๋ฌธ์ œ

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๊ตฌ๋ช…๋ณดํŠธ

๋ฌด์ธ๋„์— ๊ฐ‡ํžŒ ์‚ฌ๋žŒ๋“ค์„ ๊ตฌ๋ช…๋ณดํŠธ๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ตฌ์ถœํ•˜๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ๊ตฌ๋ช…๋ณดํŠธ๋Š” ์ž‘์•„์„œ ํ•œ ๋ฒˆ์— ์ตœ๋Œ€ 2๋ช…์”ฉ ๋ฐ–์— ํƒˆ ์ˆ˜ ์—†๊ณ , ๋ฌด๊ฒŒ ์ œํ•œ๋„ ์žˆ์Šต๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ์‚ฌ๋žŒ๋“ค์˜ ๋ชธ๋ฌด๊ฒŒ๊ฐ€ [70kg, 50kg, 80kg, 5

programmers.co.kr

 

์ฝ”๋“œ

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

int solution(vector<int> people, int limit) {
    int answer = 0;
    priority_queue<int,vector<int>,greater<int>> pq;    // ์ตœ์†Œ ํž™
    sort(people.begin(),people.end(),greater<>());  // ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ
    
    for(int i=0; i<people.size(); i++){
        if(pq.empty()) pq.push(people[i]);
        else{
            if(people[i]+pq.top()<=limit){
                pq.pop();
                answer++;
            }
            else pq.push(people[i]);
        }
    }
    return answer+pq.size();
}

 

ํ’€์ด(20๋ถ„)

๊ตฌ๋ช…๋ณดํŠธ๋Š” ์ž‘์•„์„œ ํ•œ ๋ฒˆ์— ์ตœ๋Œ€ 2๋ช…์”ฉ๋ฐ–์— ํƒˆ ์ˆ˜ ์—†๋‹ค.๋ผ๋Š” ์กฐ๊ฑด์„ ์ฝ์ง€ ์•Š๊ณ , ๋ฌด๊ฒŒ ์ œํ•œ๋งŒ ์ œ์•ฝ์„ ์ฃผ์–ด ๊ตฌํ•˜๋‹ค๊ฐ€ ๊ณ„์† 75์ ๋งŒ ๋– ์„œ ์‹œ๊ฐ„์„ ์†Œ๋น„ํ–ˆ์Šต๋‹ˆ๋‹ค. -๋ฌธ์ œ๋ฅผ ์ œ๋Œ€๋กœ ์ฝ์์‹œ๋‹ค-

people limit return
[70, 50, 80, 50] 100 3

์œ„ ์ž…๋ ฅ์„ ์˜ˆ์‹œ๋กœ ํ•œ๋ฒˆ ์„ค๋ช…ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

  1. people ๋ฐฐ์—ด์„ ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•œ๋‹ค. [80, 70, 50, 50]
  2. heap์€ ์ตœ์†Œ ํž™์ด๋‹ค.
  3. ํ˜„์žฌ heap์ด ๋น„์—ˆ๊ธฐ ๋•Œ๋ฌธ์— ํ•˜๋‚˜๋ฅผ ๋„ฃ๋Š”๋‹ค pq = [80, ]
  4. 70์„ pq์˜ top์ธ 80๊ณผ ๋”ํ–ˆ์„ ๋•Œ ๋ฌด๊ฒŒ ์ œํ•œ 100์„ ๋„˜์–ด๊ฐ€๊ธฐ ๋•Œ๋ฌธ์— pq์— pushํ•œ๋‹ค. pq = [70, 80, ]
  5. 50์„ pq์˜ top์ธ 70๊ณผ ๋”ํ–ˆ์„ ๋•Œ ๋ฌด๊ฒŒ์ œํ•œ 100์„ ๋„˜์–ด๊ฐ€๊ธฐ ๋•Œ๋ฌธ์— pq์— pushํ•œ๋‹ค. pq=[50, 70, 80, ]
  6. 50์„ pq์˜ top์ธ 50๊ณผ ๋”ํ–ˆ์„ ๋•Œ ๋ฌด๊ฒŒ์ œํ•œ 100 ์ดํ•˜๋ฅผ ๋งŒ์กฑํ•˜๊ณ , ํ•œ ๋ณดํŠธ์— ๋‘ ๋ช… ์ด์ƒ์€ ํƒ‘์Šนํ•  ์ˆ˜ ์—†๊ธฐ์— pop์„ ํ•˜๊ณ  ๊ตฌ๋ช…๋ณดํŠธ์˜ ๊ฐœ์ˆ˜๋ฅผ ++ํ•ด์ค€๋‹ค. pq = [70, 80]
  7. ์ตœ์ข…์ ์œผ๋กœ answer์™€ ๋‚จ์•„์žˆ๋Š” ์‚ฌ๋žŒ์ธ pq์˜ ์‚ฌ์ด์ฆˆ๋ฅผ ๋”ํ•ด์ฃผ๋ฉด ํ•„์š”ํ•œ ๊ตฌ๋ช…๋ณดํŠธ์˜ ๊ฐœ์ˆ˜๊ฐ€ ๋œ๋‹ค.

๋Œ“๊ธ€