코딩테스트/프로그래머스

프로그래머스 문제풀이 - 다리를 지나는 트럭 (큐)

글로벌디노 2020. 10. 21. 22:43

프로그래머스 문제풀이

코딩테스트 연습 > 스택/큐 > 다리를 지나는 트럭

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

 

 

C++

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

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

    for (int i = 0; i < bridge_length; i++)
        bridge.push(0);

    int i = 0;
    while(i < truck_weights.size())
    {
        ++answer;
        weightSum -= bridge.front();
        bridge.pop();

        if (weightSum + truck_weights[i] <= weight)
        {
            weightSum += truck_weights[i];
            bridge.push(truck_weights[i]);
            ++i;
        }
        else
        {
            bridge.push(0);
        }
    }

    answer += bridge_length;

    return answer;
}