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

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค / C++] ๊ตฌ๋ช…๋ณดํŠธ

meeeeejin 2021. 1. 11. 22:42

 

๋ฌธ์ œ๋งํฌ: programmers.co.kr/learn/courses/30/lessons/42885

 

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

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

programmers.co.kr

 

ํ’€์ด

 

people์„ ๊ฐ€๋ฒผ์šด ์‚ฌ๋žŒ -> ๋ฌด๊ฑฐ์šด ์‚ฌ๋žŒ ์ˆœ์„œ๋Œ€๋กœ ์ •๋ ฌํ•œ ๋’ค, ๋ณดํŠธ์— ํƒˆ ์ˆ˜ ์žˆ๋Š” (๊ฐ€์žฅ ๊ฐ€๋ฒผ์šด ์‚ฌ๋žŒ, ๊ฐ€์žฅ ๋ฌด๊ฑฐ์šด ์‚ฌ๋žŒ)์˜ ์กฐํ•ฉ์„ ์ฐพ์•˜๋‹ค. ๋‚จ์•„์žˆ๋Š” ์‚ฌ๋žŒ๋“ค ์ค‘ ๊ฐ€์žฅ ๊ฐ€๋ฒผ์šด ์‚ฌ๋žŒ๊ณผ๋„ ํ•จ๊ป˜ ๋ณดํŠธ์— ํƒ€์ง€ ๋ชปํ•˜๋ฉด ๊ทธ ์‚ฌ๋žŒ์€ ๋ฌด์กฐ๊ฑด ํ˜ผ์ž ๋ณดํŠธ์— ํƒ€์•ผ ๋œ๋‹ค. 

 

light: ๋‚จ์•„์žˆ๋Š” ์‚ฌ๋žŒ๋“ค ์ค‘ ๊ฐ€์žฅ ๊ฐ€๋ฒผ์šด ์‚ฌ๋žŒ

heavy: ๋‚จ์•„์žˆ๋Š” ์‚ฌ๋žŒ๋“ค ์ค‘ ๊ฐ€์žฅ ๋ฌด๊ฑฐ์šด ์‚ฌ๋žŒ

 

1. people[light] + people[heavy] <= limit    // ๋‘ ์‚ฌ๋žŒ์ด ๊ฐ™์ด ๋ณดํŠธ์— ํƒˆ ์ˆ˜ ์žˆ์„ ๊ฒฝ์šฐ

   light์™€ heavy๋ฅผ ๊ฐ™์ด ๋ณดํŠธ์— ํƒœ์šฐ๊ณ , answer์— 1์„ ๋”ํ•œ๋‹ค. 

 

2. people[light] + people[heavy] > limit    // ๋‘ ์‚ฌ๋žŒ์ด ๊ฐ™์ด ๋ณดํŠธ์— ํƒˆ ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ

   heavy ํ˜ผ์ž ๋ณดํŠธ์— ํƒœ์šฐ๊ณ , answer์— 1์„ ๋”ํ•œ๋‹ค. 

 

light >= heavy ๊ฐ€ ๋  ๋•Œ๊นŒ์ง€ 1, 2๋ฅผ ๊ณ„์‚ฐํ•œ๋‹ค. ๋งˆ์ง€๋ง‰์— light == heavy ๋ผ๋ฉด ํ•œ ์‚ฌ๋žŒ์ด ๋‚จ์•„์žˆ๋‹ค๋Š” ๋œป์ด๋ฏ€๋กœ answer์— 1์„ ๋”ํ•œ๋‹ค. 

 

 

 

์†Œ์Šค์ฝ”๋“œ

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <string>
#include <vector>
#include <algorithm>
 
using namespace std;
 
int solution(vector<int> people, int limit) {
    int answer = 0;
    sort(people.begin(), people.end());
    int light = 0, heavy = people.size() - 1;
 
    while(light < heavy) {
        if(people[light] + people[heavy] <= limit) {
            light++;
            heavy--;
            answer++;
        }
        else{
            heavy--;
            answer++;
        }
    }
 
    if(light == heavy) answer++;
 
    return answer;
}
cs

 

ํ…Œ์ŠคํŠธ ๊ฒฐ๊ณผ

 

 

 

 

 

 

๊ณต๋ถ€ํ•œ ๊ฒƒ์„ ์ •๋ฆฌํ•œ ๋‚ด์šฉ์ž…๋‹ˆ๋‹ค. ์ˆ˜์ •ํ•  ๋ถ€๋ถ„์ด ์žˆ๋‹ค๋ฉด ์•Œ๋ ค์ฃผ์‹œ๋ฉด ๊ฐ์‚ฌํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค :)

 

 

 

728x90