알고리즘
백준 13335번 트럭 C++
영춘권의달인
2021. 11. 17. 15:05

아직 다리 위에 올라가지 않은 트럭을 저장하는 큐와 다리 위에 올라간 트럭을 저장하는 큐 이렇게 큐를 두 개 만들어서
while문 안에서 시간을 1씩 증가시키면서 1초마다 할 수 있는 가장 효율적인 행동을 찾아가면서 문제를 해결하였다.
다리 위에 올라간 트럭을 저장하는 큐는 pair<int, int> 형식으로, 트럭의 무게와 다리 위에 올라간 시간을 저장하였다.
그리고 트럭이 모두 도착하면 while문을 종료하였다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
using namespace std;
typedef long long ll;
queue<int> ready;
int n, w, l;
void solve() {
queue<pair<int, int>> bridgeTruck;
int time = 0;
int currWeight = 0;
int cnt = 0;
int arrived = 0;
while (arrived < n) {
time++;
if (!bridgeTruck.empty()) {
auto a = bridgeTruck.front();
if (a.second + w == time) {
bridgeTruck.pop();
currWeight -= a.first;
arrived++;
cnt--;
}
}
if (!ready.empty()) {
int weight = ready.front();
if (currWeight + weight <= l && w > cnt) {
ready.pop();
currWeight += weight;
bridgeTruck.push({ weight,time });
cnt++;
}
}
}
cout << time;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> w >> l;
int input;
for (int i = 0; i < n; i++) {
cin >> input;
ready.push(input);
}
solve();
};