题目描述
有N个比赛队(1<=N<=500),编号依次为1,2,3,。。。。,N进行比赛,比赛结束后,裁判委员会要将所有参赛队伍从前往后依次排名,但现在裁判委员会不能直接获得每个队的比赛成绩,只知道每场比赛的结果,即P1赢P2,用P1,P2表示,排名时P1在P2之前。现在请你编程序确定排名。
输入
输入有若干组,每组中的第一行为二个数N(1<=N<=500),M;其中N表示队伍的个数,M表示接着有M行的输入数据。接下来的M行数据中,每行也有两个整数P1,P2表示即P1队赢了P2队。
输出
给出一个符合要求的排名。输出时队伍号之间有空格,最后一名后面没有空格。
其他说明:符合条件的排名可能不是唯一的,此时要求输出时编号小的队伍在前;输入数据保证是正确的,即输入数据确保一定能有一个符合要求的排名。
样例输入
3 2
3 1
3 2
17 16
16 1
13 2
7 3
12 4
12 5
17 6
10 7
11 8
11 9
16 10
13 11
15 12
15 13
17 14
17 15
17 16
0 0
样例输出
3 1 2
17 6 14 15 12 4 5 13 2 11 8 9 16 1 10 7 3
这题感觉出的有问题,排名方式,用队列和栈做不行
用优先队列做才行
#define MAX_SIZE 501
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#include <stack>
const int INF = 0x3fffffff;
using namespace std;
int inque[MAX_SIZE];
vector<int> gra[MAX_SIZE],out;
void init(int n){
fill(inque,inque+n+1,0);
for(int i= 0;i<=n;i++){
gra[i].clear();
}
}
void topologicalSort(int n){
out.clear();
priority_queue<int,vector<int>,greater<int> > q;
for(int i = 1;i<=n;i++){
if(inque[i] == 0){
q.push(i);
}
}
while(!q.empty()){
int u = q.top();
q.pop();
for(int i = 0;i<gra[u].size();i++){
--inque[gra[u][i]];
if(inque[gra[u][i]] == 0){
q.push(gra[u][i]);
}
}
gra[u].clear();
out.push_back( u);
}
}
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0);
int n,m,p1,p2;
while(true){
cin>>n>>m;
if(n == m && m ==0){
break;
}
init(n);
for(int i= 0;i<m;i++){
cin>>p1>>p2;
++inque[p2];
gra[p1].push_back(p2);
}
topologicalSort(n);
for(int i= 0;i<out.size();i++){
if(i !=0){
cout<<" ";
}
cout<<out[i];
}
cout<<endl;
}
return 0;
}