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

#include<map>
#include<set>
#include<vector>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<string>
#include<cstring>
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值