프로그래머스 다리를지나는트럭

최성현·2021년 2월 10일
0

문제 링크

코드 설명

전체 truck_weight배열만큼 순서대로 queue에 들어가며
선입선출의 원리에따라 큐를 사용하였다.

그 후, 전체 while문을 돌면서 각각의 경우의수에 맞게 들어갈 수 있도록 코드를 만들었다.
도로의 최대 무게를 재기위한 maxWeight 변수를 만들었다.

소스 코드

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

int solution(int bridge_length, int weight, vector<int> truck_weights) {
    int answer = 0;
    queue<int> q;
    int maxWeight = 0;

    for (int i = 0; i < truck_weights.size(); i++) {
        int a = truck_weights[i];
        while (1) { //각각의 경우의 수를 생각해서 전체 반복
            if (q.empty()) {
                q.push(a);
                maxWeight += a;
                answer++;
                break; //truck_weights배열에서 다음 차를 받기위해선 break;
            }
            else if (q.size() == bridge_length) {
                maxWeight -= q.front();
                q.pop();
                
                
            }
            else  {
                if (maxWeight + a > weight) {
                    q.push(0);
                    answer++;
                }
                else {
                    q.push(a);
                    answer++;
                    maxWeight += a;
                    break;
                }

            }
            




        }
    }

    return answer+bridge_length;
}
int main() {
    solution(2, 10, { 7,4,5,6 });

    return 0;
}
profile
후회없이

0개의 댓글