๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๊ฐœ๋ฐœ/์ž๋ฃŒ๊ตฌ์กฐ & ์•Œ๊ณ ๋ฆฌ์ฆ˜

๋‹ค๋ฆฌ๋ฅผ ์ง€๋‚˜๋Š” ํŠธ๋Ÿญ (Java)

by 1mj 2022. 1. 24.

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

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๋‹ค๋ฆฌ๋ฅผ ์ง€๋‚˜๋Š” ํŠธ๋Ÿญ

ํŠธ๋Ÿญ ์—ฌ๋Ÿฌ ๋Œ€๊ฐ€ ๊ฐ•์„ ๊ฐ€๋กœ์ง€๋ฅด๋Š” ์ผ์ฐจ์„  ๋‹ค๋ฆฌ๋ฅผ ์ •ํ•ด์ง„ ์ˆœ์œผ๋กœ ๊ฑด๋„ˆ๋ ค ํ•ฉ๋‹ˆ๋‹ค. ๋ชจ๋“  ํŠธ๋Ÿญ์ด ๋‹ค๋ฆฌ๋ฅผ ๊ฑด๋„ˆ๋ ค๋ฉด ์ตœ์†Œ ๋ช‡ ์ดˆ๊ฐ€ ๊ฑธ๋ฆฌ๋Š”์ง€ ์•Œ์•„๋‚ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๋‹ค๋ฆฌ์—๋Š” ํŠธ๋Ÿญ์ด ์ตœ๋Œ€ bridge_length๋Œ€ ์˜ฌ๋ผ๊ฐˆ

programmers.co.kr

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์ฝ”๋”ฉํ…Œ์ŠคํŠธ ๊ณ ๋“์  Kit ๋‹ค๋ฆฌ๋ฅผ ์ง€๋‚˜๋Š” ํŠธ๋Ÿญ ๋ฌธ์ œ ํ’€์ด์ด๋‹ค.

bridge_length๊ฐ€ ๋‹ค๋ฆฌ์˜ ๊ธธ์ด์ด์ž ํ•œ ํŠธ๋Ÿญ์ด ์ง€๋‚˜๊ฐ€๋Š”๋ฐ ๊ฑธ๋ฆฌ๋Š” ์‹œ๊ฐ„์ด๋ผ๋Š” ์ ์„ ๊ณ ๋ คํ•˜์—ฌ ํ’€์–ด์•ผ ํ•œ๋‹ค.

 

์ผ์ฐจ์„  ๋‹ค๋ฆฌ๋Š” ํŠธ๋Ÿญ์ด ์•ž์—์„œ ๋’ค๋กœ ์ง€๋‚˜๊ฐ€๋ฏ€๋กœ ํ๋ฅผ ์ผ์ฐจ์„  ๋‹ค๋ฆฌ๋ผ๊ณ  ์ƒ๊ฐํ•˜๊ณ  ํ’€์—ˆ๋‹ค.

 

์ผ๋‹จ ํ(๋‹ค๋ฆฌ)์— ์žˆ๋Š” ์ „์ฒด ํ•˜์ค‘์„ ๊ตฌํ•ด ์ด๋ฒˆ์— ๋“ค์–ด๊ฐˆ ํ•˜์ค‘์„ ๋”ํ–ˆ์„ ๋•Œ ์ˆ˜์šฉ ๊ฐ€๋Šฅํ•˜๋ฉด ๋„ฃ์–ด์ฃผ์—ˆ๊ณ , ์ปค์„œ ๋ชป ๋“ค์–ด๊ฐ€๋Š” ๊ฒฝ์šฐ๋Š” ๋‹ค๋ฆฌ๊ฐ€ ๋น„์–ด์žˆ๋‹ค๋Š” ์˜๋ฏธ(๋‹ค๋ฆฌ๊ฐ€ ๋น„์–ด์žˆ์–ด๋„ ์ง€๋‚˜๋Š”๋ฐ ์‹œ๊ฐ„์ด ๊ฑธ๋ฆฌ๋ฏ€๋กœ)์—์„œ 0์œผ๋กœ ์ฑ„์›Œ์ฃผ์—ˆ๋‹ค. ๋‹ค๋ฆฌ๊ฐ€ ๊ฝ‰ ์ฐจ์žˆ์œผ๋ฉด ๋งˆ์ง€๋ง‰๊นŒ์ง€ ์ด๋™ํ–ˆ๋‹ค๋Š” ์˜๋ฏธ์ด๋ฏ€๋กœ ๋งˆ์ง€๋ง‰ ์š”์†Œ๋ฅผ ์ œ๊ฑฐํ•ด์ฃผ์—ˆ๋‹ค.

 

import java.util.*;

class Solution {
    public int solution(int bridge_length, int weight, int[] truck_weights) {
        int i = 0;
        int answer = 0; // ๋งˆ์ง€๋ง‰ ํŠธ๋Ÿญ ์ œ์™ธ ๋ชจ๋“  ํŠธ๋Ÿญ์ด ๋‹ค๋ฆฌ๋ฅผ ํ†ต๊ณผํ•˜๋Š”๋ฐ ๊ฑธ๋ฆฐ ์‹œ๊ฐ„
        Queue<Integer> bridge = new LinkedList<>(); // ์ผ์ฐจ์„  ๋‹ค๋ฆฌ
        
        while (true) {
            int turn = truck_weights[i];
            if (i == truck_weights.length) {
                break;
            }
            if (bridge.size() == bridge_length) {
                bridge.poll();
            } else if (getBridgeSum(bridge) + turn > weight) {
                bridge.add(0);
                answer++;
            } else {
                bridge.add(turn);
                answer++;
                i++;
            }
        }
        return answer + bridge_length;
    }
    
    public int getBridgeSum(Queue<Integer> que) {
        Iterator iter = que.iterator();
        int sum = 0;
        while (iter.hasNext()) {
            sum = sum + (Integer) iter.next(); 
        }
        return sum;
    }
}

 

์ž…์ถœ๋ ฅ ์˜ˆ์‹œ์— ์žˆ๋Š” ์ผ€์ด์Šค ์ˆœ์„œ๋กœ ๋ฐ˜๋ณต์ด ๋๋‚ฌ์„ ๋•Œ ๋ณ€์ˆ˜ ๊ฐ’์„ ์ถœ๋ ฅํ•ด๋ณด๋ฉด ์•„๋ž˜์™€ ๊ฐ™๋‹ค.

bridge (ํ) answer
7 1
7, 0 2
0, 4 3
4, 5 4
5, 0 5
0, 6 6

 

๋Œ“๊ธ€