coding test - C++/Programmers
Programmers / 다리를 지나는 트럭 - 큐 / C++
sillon
2026. 2. 7. 20:06
728x90
반응형
*문제 출처는 프로그래머스에 있습니다.

문제 제목: 다리를 지나는 트럭 - 큐
문제 사이트: https://school.programmers.co.kr/learn/courses/30/lessons/42583?language=cpp

나의 풀이
#include <string>
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
int solution(int bridge_length, int weight, vector<int> truck_weights) {
int answer = 0;
int cur_weight = 0;
queue<int> bridge;
for (int i = 0 ; i < bridge_length ; i ++){
bridge.push(0);
} // 다리 길이만큼 0 넣어주기 (문제 조건 1초에 트럭 1대가 이동함)
int i = 0;
int time = 0;
// 트럭이 다리에서 이동하는 로직
while (i < truck_weights.size()){
time += 1;
cur_weight -= bridge.front(); // 다리의 제일 앞에 있는 차 빼기
bridge.pop(); // 트럭 한칸씩 앞으로 이동
if (cur_weight + truck_weights[i] <= weight){ // 다리 안의 트럭 무게 + 그 다음 트럭 가능?
int next_truck = truck_weights[i];
cur_weight += next_truck; // 가능 하면 추가
bridge.push(next_truck);
i += 1; // 다음 차 모실게요
}
else{
bridge.push(0); // ㄴㄴ 안됨 ㅎㅎ;; -> 0 넣고 기다리기
}
}
// 트럭에서 다리가 들어갈 수 있는지로직 다 구현했으면
// 마지막 트럭까지 올라가면 while 문이 끝나므로
// 다리에는 마지막 트럭이 남아있는 상태
// 마지막 트럭이 모두 건너는데 걸리는 시간 -> bridge_length
time += bridge_length;
return time;
}

※ 알아야 할 것
- queue 는 cout 으로 출력이 안된다... (헉)
728x90
반응형