邻接表拓扑排序,保证从小到大输出(未测试)

#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
const int N=100009;
int head[N],tot,pre[N],edge[N],n,m,b[N],cnt[N],a[N];
void add(int x,int y)
{
	edge[++tot]=y;pre[tot]=head[x];head[x]=tot;
}
int main()
{
	scanf("%d%d",&n,&m);
	int x,y;
	while (m--)
	{
		scanf("%d%d",&x,&y);
		cnt[y]++;
		add(x,y);
	}
	priority_queue<int,vector<int>,greater<int> > q;
	for (int i=1;i<=n;i++) if (cnt[i]==0) q.push(i);
	int z=0;
	while (!q.empty())
	{
		int u=q.top();
		q.pop();
		a[u]=++z;
		for (int i=head[u];i;i=pre[i])
		{
			int v=edge[i];
			cnt[v]--;
			if (cnt[v]==0) q.push(v);
		}
	}
	for (int i=1;i<=n;i++) printf("%d ",a[i]);
	return 0;
} 
    原文作者:拓扑排序
    原文地址: https://blog.csdn.net/zhhx2001/article/details/51769505
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞