문제링크 : https://programmers.co.kr/learn/courses/30/lessons/42583
코딩테스트 연습 - 다리를 지나는 트럭
트럭 여러 대가 강을 가로지르는 일 차선 다리를 정해진 순으로 건너려 합니다. 모든 트럭이 다리를 건너려면 최소 몇 초가 걸리는지 알아내야 합니다. 트럭은 1초에 1만큼 움직이며, 다리 길이��
programmers.co.kr
#include <string> #include <vector> #include <queue> #include <algorithm> using namespace std; int solution(int bridge_length, int weight, vector<int> truck_weights) { int answer = 0; queue<pair<int,int>> q; int cnt = truck_weights.size(); int cur_i = 0; int cur_w = 0; int time = 0; while (1) { if (cur_i < cnt && cur_w + truck_weights[cur_i] <= weight) { int qsize = q.size(); while (qsize--) { auto truck = q.front(); q.pop(); if (truck.second != bridge_length) { q.push(make_pair(truck.first, truck.second + 1)); } else { cur_w -= truck_weights[truck.first]; } } cur_w += truck_weights[cur_i]; q.push(make_pair(cur_i++, 1)); time++; } else if (!q.empty()) { auto truck = q.front(); q.pop(); cur_w -= truck_weights[truck.first]; int offset = bridge_length - truck.second+1; int qsize = q.size(); while (qsize--) { truck = q.front(); q.pop(); q.push(make_pair(truck.first, truck.second + offset)); } if (cur_i < cnt && cur_w + truck_weights[cur_i] <= weight) { cur_w += truck_weights[cur_i]; q.push(make_pair(cur_i++, 1)); } time += offset; } else { answer = time; break; } //printf("time : %d\n", time); } return answer; } int main() { int bridge = 2; int wi = 10; vector<int> a = { 7,4,5,6 }; //int bridge = 100; //int wi = 100; //vector<int> a = { 10 }; //int bridge = 1; //int wi = 6; //vector<int> a = { 6,6}; printf("%d", solution(bridge, wi, a)); }
'Problem-Solving > Programmers' 카테고리의 다른 글
[프로그래머스] Level2 - 조이스틱 (C++) (0) | 2020.07.14 |
---|---|
[프로그래머스] Level2 - 더 맵게 (C++) (0) | 2020.07.07 |
[프로그래머스] Level2 - 괄호 변환 (C++) (0) | 2020.06.28 |
[프로그래머스] Level2 - 카카오 프렌즈 컬러링북 (0) | 2020.06.21 |
[프로그래머스] Level2 - 문자열 압축 (0) | 2020.06.12 |