拓扑排序做了多少次减法
七个构建任务编号 0~6,(a, b) 表示 a 做完才能做 b。
数一数 kahn 里「入度减 1」这个动作在两张图上各做了多少次——左边是那张 DAG,右边是加了 5 → 3 的那张:
#include <algorithm>
#include <climits>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <string>
#include <utility>
#include <vector>
using namespace std;
using Edges = vector<pair<int, int>>;
const int N = 7;
// 七个构建任务,(a, b) 表示 a 做完才能做 b
const Edges DEP = {{0, 1}, {0, 2}, {1, 3}, {2, 3}, {3, 4}, {4, 5}, {4, 6}};
// 同一张图再加一条 5 → 3,于是有了环
const Edges G = {{0, 1}, {0, 2}, {1, 3}, {2, 3}, {3, 4}, {4, 5}, {5, 3}, {4, 6}};
vector<vector<int>> build(const Edges& edges, int n = N) {
vector<vector<int>> g(n);
for (auto [a, b] : edges) g[a].push_back(b);
for (auto& adj : g) sort(adj.begin(), adj.end());
return g;
}
// 数一数 Kahn 里「入度减 1」一共做了多少次
int kahn_cost(const Edges& edges, int n = N) {
vector<vector<int>> g = build(edges, n);
vector<int> d(n, 0);
for (auto [a, b] : edges) d[b]++;
priority_queue<int, vector<int>, greater<int>> ready;
for (int u = 0; u < n; u++) {
if (d[u] == 0) ready.push(u);
}
int steps = 0;
while (!ready.empty()) {
int u = ready.top();
ready.pop();
for (int v : g[u]) {
d[v]--;
steps++;
if (d[v] == 0) ready.push(v);
}
}
return steps;
}
int main() {
cout << kahn_cost(DEP) << "/" << kahn_cost(G) << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论