拓扑排序 字典序输出

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
#define N 1000005
#define M 1000005

using namespace std;

inline int wread(){
	char c(getchar ());int wans(0),flag(1);
	while (c<'0' || c>'9'){if (c=='-') flag=-1;c=getchar ();}
	while (c>='0' && c<='9'){wans=wans*10+c-'0';c=getchar ();}
	return wans*=flag;
}

inline void init (){
	freopen (" ","r",stdin);
	freopen (" ","w",stdout);
}

int n,m;
int K,hed[N];
struct node {int v,nxt;}e[M];
inline void ad (int u,int v){e[++K]=(node){v,hed[u]};hed[u]=K;}
priority_queue < int , vector <int > , greater <int > > Q;
int ins[N],pr[N],top;
bool vis[N];

void topsort (){
	for (int i(1);i<=n;++i)
		if (!ins[i])	Q.push(i),vis[i]=true;
	while (!Q.empty()){
		int x(Q.top());
		pr[++top]=x;
		vis[x]=false; 
		Q.pop();
		for (int i(hed[x]);i!=-1;i=e[i].nxt){
			int v(e[i].v);
			ins[v] --;
			if (!ins[v])
				if (!vis[v])	
				Q.push(v),vis[v]=true;
		}
	}
	for (int i(1);i<=n;++i)
		if (ins[i])	{puts("Orz.");return ;}
	for (int i(1);i<=n;++i)
		printf("%d ",pr[i]);
	return ;
}

int main (){
//	init ();
	memset (hed,-1,sizeof hed);
	n=wread();m=wread();
	for (int i(1);i<=m;++i){
		int u(wread()),v(wread());
		ad (u,v);ins[v] ++;
	}
	topsort ();
	return 0;
}

 

    原文作者:拓扑排序
    原文地址: https://blog.csdn.net/violinlove/article/details/83587528
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞