有N个比赛队(1<=N<=500),编号依次为1,2,3,。。。。,N进行比赛,比赛结束后,裁判委员会要将所有参赛队伍从前往后依次排名,但现在裁判委员会不能直接获得每个队的比赛成绩,只知道每场比赛的结果,即P1赢P2,用P1,P2表示,排名时P1在P2之前。现在请你编程序确定排名。
其他说明:符合条件的排名可能不是唯一的,此时要求输出时编号小的队伍在前;输入数据保证是正确的,即输入数据确保一定能有一个符合要求的排名。
4 3 1 2 2 3 4 3
1 2 4 3
很裸的toposort,
先选择没有前趋的顶点;
从AOV网图中删除该顶点,并且删去从该顶点出发的全部有向边;
重复上述操作;
可以选择用优先队列 priority_queue<int,vertor<int>,greater> > q;//>>会报错,得有空格
代码如下
#include <bits/stdc++.h> using namespace std; int AOV[505][505]; int ind[505]; priority_queue<int , vector<int> , greater<int> > q; void toposort(int n) { for(int i = 1; i <= n; i++) { if(ind[i] == 0) q.push(i); } int t = 1, v; while(!q.empty()) { v = q.top(); q.pop(); if(t != n) { printf("%d ",v); t++; } else { printf("%d\n",v); } for(int i = 1; i <= n; i++) { if(AOV[v][i]) { ind[i]--; if(ind[i] == 0) { q.push(i); } } } } return ; } int main() { int n, m; int p1, p2; while(cin>>n>>m) { memset(AOV , 0 , sizeof(AOV)); memset(ind , 0 , sizeof(ind)); for(int i = 0; i < m; i++) { scanf("%d%d",&p1,&p2); if(AOV[p1][p2]) continue; AOV[p1][p2] = 1; ind[p2]++; } toposort(n); } return 0; }