관리 메뉴

fatalite

C++ 다리를 지나는 트럭 [고득점 Kit 스택 / 큐] 본문

코딩 인터뷰/프로그래머스

C++ 다리를 지나는 트럭 [고득점 Kit 스택 / 큐]

fataliteforu 2023. 5. 13. 12:22

Problem

난이도 : 프로그래머스 2단계

분류 : 큐, Deque

코멘트: 간단하게 짜는 버릇을 들이자.

Solution

#include <string>
#include <vector>
#include <deque>
#include <iostream>
using namespace std;

int solution(int bridge_length, int weight, vector<int> truck_weights) {
    int answer = 1;
    
    deque<pair<int,int>> OnBridge;
    deque<int> WaitingTruck;
    for(int a : truck_weights){
        WaitingTruck.push_back(a);
    }
    //one loop = 1s;
    int CurrentWeight = 0;
    while(!WaitingTruck.empty() || !OnBridge.empty()){
        
        answer++;
        int tmp = WaitingTruck.front();
        if(CurrentWeight + tmp <= weight && !WaitingTruck.empty()){
            
            WaitingTruck.pop_front();
            CurrentWeight += tmp;
            OnBridge.push_back({tmp,1});
        }
        pair<int,int> p = OnBridge.front();
        if(p.second >= bridge_length){
            CurrentWeight -= p.first;
            OnBridge.pop_front();
        }
        
        for(int i =0; i < OnBridge.size();i++){
            OnBridge[i].second++;
        }
        
    }
    
    return answer;
}