拓扑排序
vector <int> an[505];
an的下标为P1,vector中储存被P1打败的P2
其次就是利用优先队列储存入度为0的元素(优先级设为编号小的优先级高)
最后就是迭代器的使用
其实,不用stl的函数也能写出来,不过代码量就很多了
有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
#include<cstdio>
#include<vector>
#include<queue>
using namespace std;
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
vector <int> an[505];
int pre[505]={0}; //入度
int i,j,f;
priority_queue <int,vector<int>,greater<int> > q;
for(i=0;i<m;i++)
{
int P1,P2;
scanf("%d%d",&P1,&P2);
pre[P2]++;
an[P1].push_back(P2);
}
for(i=1;i<=n;i++)
{
if(pre[i]==0)
{
q.push(i);
}
}
for(j=0;j<n;j++)
{
f=q.top();
if(!q.empty())
q.pop();
pre[f]=-1;
printf("%d",f);
if(j!=n-1)
putchar(' ');
else
putchar('\n');
for(vector<int>::iterator it=an[f].begin();it!=an[f].end();it++)
{
pre[*it]--;
if(pre[*it]==0)
q.push(*it);
}
}
}
return 0;
}