拓扑排序
一.大致思路
1.将入度为0的点压入队列,将V0压入队列
2.取出队首元素V0,将V1,V3,V4的入度减1;
3.再次判断入度为0的点,将V1压入队列
4.取出队首元素V1,V3的入度减1;
5.再次判断入度为0的点,将V3压入队列;
6.取出队首元素V3,V4和V2的入度减1;
7.再次判断入度为0的点,将V4和V2压入队列
8.取出队首元素V4或V2(具体先取出那个根据题目要求判断),V5和的入度减1;
9.再次判断入度为0的点,将V5压入队列;
10.取出队首元素V5,队列为空,结束
题目
有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
二.具体代码
一般代码
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<vector>
#include<queue>
#define INF 0x3fffffff
#define me(a,b) memset(a,b,sizeof(a))
const int maxn=1e3+10;
using namespace std;
int g[maxn],mp[maxn][maxn],in[maxn];
using namespace std;
vector<int>v[maxn];
int n;
void topo()
{
for(int i=1;i<=n;i++)//循环找出每次入度为0的点
{
int u=1;
while(in[u]!=0)//找到入度为0的点
u++;
g[i]=u;//将入度为0的点依次记录下来
in[u]=-1;//标记已经记录过的点
for(int j=0;j<(int)v[u].size();j++)
{
in[v[u][j]]--;
//去掉入度为0的点的所有边,所以和入度为0的边相连接的点入度都减1
}
}
}
int main()
{
int m,x,y;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=0;i<=n;i++)//初始化
{
in[i]=0;
v[i].clear();
}
while(m--)
{
scanf("%d%d",&x,&y);
v[x].push_back(y);//将x,y连接起来
in[y]++;//y点的入度加1
}
topo();
for(int i=1;i<=n;i++)
{
if(i==n)
printf("%d\n",g[i]);
else
printf("%d ",g[i]);
}
}
return 0;
}
优先队列优化的代码:
#include <iostream>
#include<stdio.h>
#include<algorithm>
#include<vector>
#include<queue>
#define INF 0x3fffffff
#define me(a,b) memset(a,b,sizeof(a))
typedef long long ll;
const int maxn=1e5+10;
using namespace std;
int in[maxn],vis[maxn];
using namespace std;
vector<int>v[maxn];
int n;
void topo()
{
priority_queue<int,vector<int>,greater<int> >q;
//此优先队列的点可从小到大自动排序
for(int i=1;i<=n;i++)
{
if(in[i]==0)
q.push(i);
}
int t=1;
while(!q.empty())
{
int u=q.top();
q.pop();
vis[t]=u;
t++;
for(int i=0;i<(int)v[u].size();i++)
{
int l=v[u][i];
in[l]--;
if(in[l]==0)
{
q.push(l);
}
}
}
}
int main()
{
int m,x,y;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=0;i<=n;i++)
{
in[i]=0;
v[i].clear();
}
while(m--)
{
scanf("%d%d",&x,&y);
{
v[x].push_back(y);
in[y]++;
}
}
topo();
for(int i=1;i<=n;i++)
{
if(i==n)
printf("%d\n",vis[i]);
else
printf("%d ",vis[i]);
}
/*for(int i=1;i<=n;i++)
printf("%d%c",vis[i],(i==n)?'\n':' ');*/
//简化后的输出
}
return 0;
}