본문 바로가기

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

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

728x90
반응형


🔗 문제 링크

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


반응형
728x90

👩‍💻 코드

#include <string>
#include <vector>
#include <deque>
#include <utility>
#include <iostream>

using namespace std;

int solution(int bridge_length, int weight, vector<int> truck_weights) {
    int answer = 0;
    int sum = 0;
    int i = 0;
    deque<pair<int, int>> crossing;
    
    while(i < truck_weights.size() || !crossing.empty()){
        answer++;
        
        if (!crossing.empty() && crossing.front().second == bridge_length) {
            sum -= crossing.front().first;
            crossing.pop_front();
        }
        
        if(i < truck_weights.size() && sum + truck_weights[i] <= weight){
            sum += truck_weights[i];
            crossing.push_back({truck_weights[i], 0});
            i++;
        }
        
        for (auto& truck : crossing) {
            truck.second++;
        }
    }
    
    return answer;
}

📝 풀이

시간 초가 증가함에 따라 트럭의 위치와 거리를 확인합니다.

트럭이 다리를 다 건넜다면 제거합니다.

대기 트럭이 존재하고 다리의 무게를 넘지 않는 다면 다리를 건너기 시작합니다.

다리위에 있는 트럭들은 한 칸씩 앞으로 이동합니다.

이 과정을 대기 트럭이 없거나 다리에 트럭이 없을 때까지 반복합니다.

최종적으로 걸린 시간 초 값인 answer을 return 합니다.

728x90
반응형