解題思路
維護入度、完成輪及解鎖輪。初始入度 0 者解鎖輪為 1;每輪開始只在已解鎖未完成者中,以 (解鎖輪,期限,編號) 排序取前 B 個。先凍結整批名單,再標記完成與扣後繼入度,入度降零者記為下一輪才解鎖。
待辦任務保留原解鎖輪,不能因等待而變新任務。選取名單在扣入度前固定,保證同輪新解鎖者不會被插入本輪。若無可選者而仍有未完成任務,所有剩餘者都受循環直接或間接阻擋,立即停止;已完成者才計 max(0,完成輪-期限)。
時間 O(N² log N+M),空間 O(N+M);N≤80,輪數不超過 N,逐輪排序足夠。Python 輸入 token O(N+M)。
Step-by-step animation
逐步推演(例子條件見步驟說明)
步驟 1 / 3
首輪選取
自訂 B=1、期限 [9,1,1],邊 2→3,任務 1、2 都在輪1解鎖。
1
2
- 本輪選取
- 2
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
int n, m, B;
cin >> n >> m >> B;
vector<int> d(n), ind(n), unlock(n, -1), done(n, -1);
for (int &x : d)
cin >> x;
vector<vector<int>> g(n);
while (m--) {
int u, v;
cin >> u >> v;
g[--u].push_back(--v);
ind[v]++;
}
for (int i = 0; i < n; i++)
if (!ind[i])
unlock[i] = 1;
int round = 1, cnt = 0;
ll late = 0;
while (true) {
vector<int> v;
for (int i = 0; i < n; i++)
if (done[i] < 0 && unlock[i] > 0 && unlock[i] <= round)
v.push_back(i);
if (v.empty())
break;
sort(v.begin(), v.end(), [&](int x, int y) {
return tie(unlock[x], d[x], x) < tie(unlock[y], d[y], y);
});
if ((int)v.size() > B)
v.resize(B);
for (int u : v) {
done[u] = round;
cnt++;
late += max(0, round - d[u]);
}
for (int u : v)
for (int w : g[u])
if (--ind[w] == 0)
unlock[w] = round + 1;
round++;
}
cout << (cnt == n ? round - 1 : -1) << ' ' << cnt << ' ' << late << '\n';
for (int i = 0; i < n; i++)
cout << done[i] << (i + 1 == n ? '\n' : ' ');
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。