求字典序最小的拓扑排序
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
#include <algorithm>
using namespace std;
vector<string> lexicographicallySmallestTopologicalSort(unordered_map<string, vector<string>>& graph) {
unordered_map<string, int> inDegree;
for (const auto& p : graph) {
inDegree[p.first] = 0;
}
for (const auto& p : graph) {
for (const string& neighbor : p.second) {
inDegree[neighbor]++;
}
}
priority_queue<string, vector<string>, greater<string>> pq;
for (const auto& p : inDegree) {
if (p.second == 0) {
pq.push(p.first);
}
}
vector<string> result;
while (!pq.empty()) {
string node = pq.top();
pq.pop();
result.push_back(node);
for (const string& neighbor : graph[node]) {
inDegree[neighbor]--;
if (inDegree[neighbor] == 0) {
pq.push(neighbor);
}
}
}
return result;
}
int main() {
unordered_map<string, vector<string>> graph = {
{"A", {"C"}},
{"E", {"C", "D"}},
{"C", {"D"}},
{"B", {"C"}}
};
vector<string> result = lexicographicallySmallestTopologicalSort(graph);
for (const string& node : result) {
cout << node << " ";
}
cout << endl;
return 0;
}
- 首先初始化所有在 graph 中的节点的入度为 0
- 然后计算每个节点的实际入度
- 这样可以确保所有节点都被正确初始化,包括那些只作为后继节点的节点