굥뷰를 햡시댜
[Programmers]다리를 지나는 트럭 본문
https://programmers.co.kr/learn/courses/30/lessons/42583?language=cpp
코딩테스트 연습 - 다리를 지나는 트럭 | 프로그래머스
트럭 여러 대가 강을 가로지르는 일 차선 다리를 정해진 순으로 건너려 합니다. 모든 트럭이 다리를 건너려면 최소 몇 초가 걸리는지 알아내야 합니다. 트럭은 1초에 1만큼 움직이며, 다리 길이는 bridge_length이고 다리는 무게 weight까지 견딥니다. ※ 트럭이 다리에 완전히 오르지 않은 경우, 이 트럭의 무게는 고려하지 않습니다. 예를 들어, 길이가 2이고 10kg 무게를 견디는 다리가 있습니다. 무게가 [7, 4, 5, 6]kg인 트럭이 순서
programmers.co.kr
큐를 이용한 간단한 문제 입니다.
저는 대기중인 트럭의 큐, 다리를 건너는 도중 트럭을 저장할 큐, 다리를 완전히 건넌 트럭을 저장할 큐
이렇게 총 3가지의 큐를 만들어 문제를 풀었습니다.
조건이 다리가 견딜 수 있는 최대 무게가 있다는 것 빼고는 고려할 만한 조건이 따로 없어서 쉬운 문제라고 생각합니다.
#include <string>
#include <vector>
#include <queue>
using namespace std;
struct BRIDGE {
int weight, load;
};
queue<BRIDGE> stanby, ing, complete;
int solution(int bridge_length, int weight, vector<int> truck_weights) {
int answer = 0;
int weight_sum = 0;
int time = 0;
for (int i = 0; i < truck_weights.size(); i++) {
stanby.push({ truck_weights[i], 1 });
}
while (1) {
if (complete.size() == truck_weights.size()) break;
queue<BRIDGE> temp;
while (!ing.empty()) {
BRIDGE cur = ing.front();
ing.pop();
if (cur.load < bridge_length) {
cur.load += 1;
temp.push(cur);
}
else {
weight_sum -= cur.weight;
complete.push(cur);
}
}
ing = temp;
BRIDGE stanby_cur;
if (!stanby.empty()) {
stanby_cur = stanby.front();
if (weight_sum + stanby_cur.weight <= weight) {
weight_sum += stanby_cur.weight;
ing.push(stanby_cur);
stanby.pop();
}
}
time += 1;
}
answer = time;
return answer;
}
'알고리즘 문제 풀이 > Programmers 문제 풀이' 카테고리의 다른 글
[Programmers] 주식가격 (0) | 2019.11.28 |
---|---|
[Programmers] 기능개발 (0) | 2019.11.28 |
Comments