拓扑排序模板题。值得注意的是,题目中要求编号小的队伍排名靠前,所以我们这里引入一个优先队列来确保答案满足该性质。
拓扑排序伪代码:
- 随机取出一个入度为0的点$v$放入队列$L$。
- 删除以$v$为顶点的所有边,若删除过后其另一顶点入度为0,将其加入队列。
- 重复步骤2,当没有点再被加入集合后,检查图中是否有任何边,若有,则图中存在环,若无,则$L$为拓扑排序结果。
#include <bits/stdc++.h>
using namespace std;
const int N = 501;
int n, m;
vector<int> G[N];
int id[N];
queue<int> ans;
void toposort() {
priority_queue< int, vector<int>, greater<int> > pq;
for ( int i = 1; i <= n; ++i )
if ( id[i] == 0 )
pq.push(i);
while ( !pq.empty() ) {
int cur = pq.top();
ans.push(cur);
pq.pop();
for ( auto x : G[cur] ) {
--id[x];
if ( id[x] == 0 )
pq.push(x);
}
}
}
int main() {
ios::sync_with_stdio(false);
while (cin >> n >> m ) {
for ( int i = 1; i <= n; ++i )
G[i].clear();
memset(id, 0, sizeof id);
int a, b;
for ( int i = 1; i <= m; ++i ) {
cin >> a >> b;
G[a].push_back(b);
++id[b];
}
toposort();
while ( !ans.empty() ) {
if ( ans.size() == 1 ) {
cout << ans.front();
ans.pop();
continue;
}
cout << ans.front() << ' ';
ans.pop();
}
cout << endl;
}
return 0;
}