拓扑排序(未完善 谨慎套用)

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define LL long long
#define MAXN 0x3f3f3f3f
#define INF 1000000005
inline LL read()
{
	char ch=0;
	LL x=0,w=1;
	while(ch<'0'||ch>'9')
	{
		if(ch=='-')
			w=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9')
	{
		x=x*10+ch-'0';
		ch=getchar();
	}
	return w*x;
}
LL r[30005],a,b,head[30005],n,t,m,cnt,v[30005];
struct node
{
	int to,next;
};
struct nn
{
	int r,x;
	bool operator <(const nn& bb)const
	{
		if(r==bb.r)
			return x>bb.x;
		return r>bb.r;
	}
};
node edge[100005];
inline void add(int x,int y)
{
	edge[++cnt].to=y;
	edge[cnt].next=head[x];
	head[x]=cnt;
}
priority_queue <int,vector<int>,greater<int> > qq;
priority_queue <int,vector<int>,greater<int> > q;//从小到大   不需要头文件vector 
inline LL find()
{
	int now=0;
	int min=MAXN;
	for(register int i=1;i<=n;i++)
	{
		if(!v[i])
		{
			if(min>r[i])
			{
				min=r[i];
				now=i;
			}
		}
	}
	v[now]=1;
	return now;

}
inline void tp()
{
	int tt;
	bool ok=0;
	while(!q.empty())
	{
		tt=q.top();
		q.pop();
		if(ok)
		{
			cout<<' ';
		}
		else
		{
			ok=1;
		}
		cout<<tt; 
		for(register int i=head[tt];i>0;i=edge[i].next)
		{
			r[edge[i].to]--;
			if(r[edge[i].to]==0)
			{
				q.push(edge[i].to);
			}
		}
	}
}
int main()
{
	t=read();
	while(t--)
	{
		cnt=0;
		memset(v,0,sizeof(v));
		memset(edge,0,sizeof(edge));
		memset(r,0,sizeof(r));
		memset(head,0,sizeof(head));
		n=read();
		q=qq;
		m=read();
		for(register int i=1;i<=m;i++)//建边 确定初始入度
		{
			a=read();
			b=read();
			add(a,b);
			r[b]++;
		}
		for(register int i=1;i<=n;i++)
		{
			if(r[i]==0)
			{
				q.push(i);
			}
		}
		tp();
		cout<<endl;
	}
	return 0;
}

你可能感兴趣的:(拓扑排序(未完善 谨慎套用))