Problem Description
有N個比賽隊(1<=N<=500),編號依次爲1,2,3,。。。。,N進行比賽,比賽結束後,裁判委員會要將所有參賽隊伍從前往後依次排名,但現在裁判委員會不能直接獲得每個隊的比賽成績,只知道每場比賽的結果,即P1贏P2,用P1,P2表示,排名時P1在P2之前。現在請你編程序確定排名。
Input
輸入有若干組,每組中的第一行爲二個數N(1<=N<=500),M;其中N表示隊伍的個數,M表示接着有M行的輸入數據。接下來的M行數據中,每行也有兩個整數P1,P2表示即P1隊贏了P2隊。
Output
給出一個符合要求的排名。輸出時隊伍號之間有空格,最後一名後面沒有空格。
其他說明:符合條件的排名可能不是唯一的,此時要求輸出時編號小的隊伍在前;輸入數據保證是正確的,即輸入數據確保一定能有一個符合要求的排名。
Sample Input
4 3
1 2
2 3
4 3
Sample Output
1 2 4 3
解題思路:
拓撲排序模板題,不過輸出時要求編號小的隊伍在前,使用優先隊列可以有效解決該要求。
AC代碼:
#include<iostream>
#include<vector>
#include<queue>
#include<functional>
using namespace std;
int indegree[501];
int ans;
vector<int>edge[501];
priority_queue<int, vector<int>, greater<int> > q;
void init(int n) {
ans = 0;
for (int i = 0; i <= n; i++) {
indegree[i] = 0;
edge[i].clear();
}
while (!q.empty()) { q.pop(); }
}
int main() {
int n, m;
while (cin >> n >> m) {
init(n);
while (m--) {
int a, b;
cin >> a >> b;
indegree[b]++;
edge[a].push_back(b);
}
for (int i = 1; i <= n; i++) {
if (indegree[i] == 0) {
q.push(i);
}
}
while (!q.empty()) {
ans++;
int tmp = q.top();
q.pop();
if (ans == n) cout << tmp << endl;
else cout << tmp << " ";
for (int i = 0; i < edge[tmp].size(); i++) {
indegree[edge[tmp][i]]--;
if (indegree[edge[tmp][i]] == 0) {
q.push(edge[tmp][i]);
}
}
}
}
return 0;
}