【正经题解】裁判员Gold King
2024-03-15 11:15:10
发布于:浙江
31阅读
0回复
0点赞
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <unordered_set>
using namespace std;
// 拓扑排序
vector<int> topologicalSort(int n, vector<vector<int>>& adjList, vector<int>& inDegree) {
vector<int> result;
priority_queue<int, vector<int>, greater<int>> pq;
// 初始化入度为0的节点
for (int i = 1; i <= n; ++i) {
if (inDegree[i] == 0) {
pq.push(i);
}
}
// 拓扑排序过程
while (!pq.empty()) {
int u = pq.top();
pq.pop();
result.push_back(u);
// 更新相邻节点的入度
for (int v : adjList[u]) {
--inDegree[v];
if (inDegree[v] == 0) {
pq.push(v);
}
}
}
return result;
}
int main() {
int numTeams, numMatches;
cin >> numTeams >> numMatches;
vector<vector<int>> adjacencyList(numTeams + 1); // 邻接表表示比赛结果
vector<int> inDegree(numTeams + 1, 0); // 节点入度
// 构建邻接表和入度数组
for (int i = 0; i < numMatches; ++i) {
int team1, team2;
cin >> team1 >> team2;
adjacencyList[team1].push_back(team2);
++inDegree[team2];
}
// 执行拓扑排序
vector<int> result = topologicalSort(numTeams, adjacencyList, inDegree);
// 输出排序结果
for (int i = 0; i < numTeams; ++i) {
cout << result[i];
if (i < numTeams - 1) {
cout << " ";
}
}
return 0;
}
这里空空如也
有帮助,赞一个