알고리즘 풀이/프로그래머스

프로그래머스 - 다리를 지나는 트럭 (스택/큐, 구현)

배게 2019. 12. 4. 07:37
728x90

예전에 푼 문제인데 다시 풀려니까 안풀렷다


이게 트럭이 들어가고 나가는 과정이 조금 헷갈렸던 것 같다. 


시간도 1초씩 더해주면 뭔가 실행시간 10초 넘어갈 것 같아서 다른 방법으로 햇는데 


1초씩 더하는 방식으로 해도 무방하다


inList의 트럭중 distance가 다리 끝부분에 도달한 트럭을 먼저 보내버리고 


그 다음에 무게가 여유가 된다면 outList의 0번째 트럭을 집어 넣는 순으로 해야한다


반대로 해서 헤맷음


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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
    public int solution(int bridge_length, int weight, int[] truck_weights) {
        int answer = 0;
        int weightOnBridge = 0;
 
        ArrayList<Truck> inList = new ArrayList<>();
        ArrayList<Truck> outList = new ArrayList<>();
 
        for (int w : truck_weights)
            outList.add(new Truck(w, 0));
 
        while (true) {
            if (!inList.isEmpty() && inList.get(0).distance == bridge_length) {
                weightOnBridge -= inList.get(0).weight;
                inList.remove(0);
            }
            if (!outList.isEmpty() && outList.get(0).weight + weightOnBridge <= weight) {
                weightOnBridge += outList.get(0).weight;
                inList.add(outList.remove(0));
            }
 
            for (Truck t : inList)
                t.distance++;
            answer++;
 
            if (inList.isEmpty() && outList.isEmpty())
                break;
 
        }
 
        return answer;
    }
 
    class Truck {
        int weight;
        int distance;
 
        Truck(int weight, int distance) {
            this.weight = weight;
            this.distance = distance;
        }
    }
cs