스택(Stack)

스택/큐 > 다리를 지나는 트럭

cepiloth 2018. 9. 29. 20:52
반응형

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


1. 문제


2. 알고리즘

키워드 - 스택


3. 코드


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
42
43
#include <string>
#include <vector>
#include <queue>
 
using namespace std;
 
int solution(int bridge_length, int weight, vector<int> truck_weights) {
    queue<int> q;
 
    int sum, count; sum = count = 0;
    
    for(int i=0; i<truck_weights.size(); i++) {
        int d = truck_weights[i];
 
        while (true) {
 
            if (q.empty()) {
                q.push(d);
                count++;
                sum += d;
                break;
            }
            else if (q.size() == bridge_length) {
                sum -= q.front(); q.pop();
            }
            else {
 
                if (sum + d > weight) {
                    q.push(0);
                    count++;
                }
                else {
                    q.push(d);
                    count++;
                    sum += d;
                    break;
                }
            }
        }
    }
    
    return count + bridge_length;
}
cs



반응형