-
프로그래머스 - 다리를 지나는 트럭알고리즘 풀이/프로그래머스 2019. 12. 14. 11:58
문제 : https://programmers.co.kr/learn/courses/30/lessons/42583
코딩테스트 연습 - 다리를 지나는 트럭 | 프로그래머스
트럭 여러 대가 강을 가로지르는 일 차선 다리를 정해진 순으로 건너려 합니다. 모든 트럭이 다리를 건너려면 최소 몇 초가 걸리는지 알아내야 합니다. 트럭은 1초에 1만큼 움직이며, 다리 길이는 bridge_length이고 다리는 무게 weight까지 견딥니다. ※ 트럭이 다리에 완전히 오르지 않은 경우, 이 트럭의 무게는 고려하지 않습니다. 예를 들어, 길이가 2이고 10kg 무게를 견디는 다리가 있습니다. 무게가 [7, 4, 5, 6]kg인 트럭이 순서
programmers.co.kr
풀이 :
cand의 second에는 +1씩 증가하도록 하여 길이와 같아진다면 erase 하는 방식으로 해결하였다.
코드 ( C++ )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters#include <iostream> #include <queue> #include <vector> using namespace std; int solution(int bridge_length, int weight, vector<int> truck_weights) { int answer = 0; queue<int> list; for (int i = 0; i < truck_weights.size(); ++i) list.push(truck_weights[i]); int time = 1; vector<pair<int, int>> cand; int sum = 0; while(1) { if (!list.empty() && sum + list.front() <= weight) { cand.push_back({ list.front(),0 }); sum += list.front(); list.pop(); } for (int i = 0; i < cand.size(); ++i) { cand[i].second++; } time++; if (cand[0].second == bridge_length) { sum -= cand[0].first; cand.erase(cand.begin()); } if (list.empty() && cand.empty()) break; } return time; } '알고리즘 풀이 > 프로그래머스' 카테고리의 다른 글
프로그래머스 - 종이접기 (0) 2020.04.11 프로그래머스 - 베스트앨범 (0) 2020.01.01 프로그래머스 - H-Index (0) 2019.12.08 프로그래머스 - 숫자 야구 (0) 2019.12.06 프로그래머스 - 위장 (0) 2019.12.05