拓扑排序 字典序输出

#include 
#include 
#include 
#include 
#include 
#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  , greater  > 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;
}

 

你可能感兴趣的:(STL,图论)