学习笔记:拓扑排序

对一个有向无环图(Directed Acyclic Graph简称DAG)G进行拓扑排序,是将G中所有顶点排成一个线性序列,使得图中任意一对顶点u和v,若边<u,v>∈E(G),则u在线性序列中出现在v之前。通常,这样的线性序列称为满足拓扑次序(Topological Order)的序列,简称拓扑序列。简单的说,由某个集合上的一个偏序得到该集合上的一个全序,这个操作称之为拓扑排序。

有向图的拓扑序列:
给定一个n个点m条边的有向图,点的编号是1到n,图中可能存在重边和自环。
请输出任意一个该有向图的拓扑序列,如果拓扑序列不存在,则输出-1。
若一个由图中所有点构成的序列A满足:对于图中的每条边(x, y),x在A中都出现在y之前,则称A是该图的一个拓扑序列。

输入格式
第一行包含两个整数n和m
接下来m行,每行包含两个整数x和y,表示存在一条从点x到点y的有向边(x, y)。

输出格式
共一行,如果存在拓扑序列,则输出任意一个合法的拓扑序列即可。否则输出-1。

#include<cstdio>
#include<cmath>
#include<ctime>
#include<cstring>
#include<iostream>
#include<map>
#include<set>
#include<stack>
#include<queue>
#include<string>
#include<vector>
#define ll long long
#define ull unsigned long long
#define up_b upper_bound
#define low_b lower_bound
#define m_p make_pair
#define mem(a) memset(a,0,sizeof(a))
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define inf 0x3f3f3f3f
#define endl "\n"
#include<algorithm>
using namespace std;

inline ll read()
{
	ll x=0,f=1; char ch=getchar();
	while(ch<'0'||ch>'9')	{ if(ch=='-') f=-1; ch=getchar(); }
	while('0'<=ch&&ch<='9')	x=x*10+ch-'0', ch=getchar();
	return f*x;
}

const int N = 1e5+5;

int n,m,in[N];
struct node{int v,next;}edge[N];
int head[N],idx;

void add(int u,int v)
{
	edge[idx]=(node){v,head[u]};
	head[u]=idx++;
}

vector<int> path;

bool topo()
{
	queue<int> q; //如果要求输出字典序最小的拓扑序列,可以用优先队列
	
	for(int i=1;i<=n;i++)
		if(in[i]==0)	q.push(i);
	while(!q.empty())
	{
		int u=q.front();	q.pop();
		path.push_back(u);
		
		for(int i=head[u];~i;i=edge[i].next)
		{
			int v=edge[i].v;
			in[v]--;
			if(in[v]==0)	q.push(v);
		}
	}
	return path.size()==n; //如果最终入队的点数不足n点,说明图中出现了环,不存在拓扑排序
}

int main()
{
    memset(head,-1,sizeof(head));
    
	cin>>n>>m;
	while(m--)
	{
		int u=read(),v=read();
		add(u,v);
		in[v]++; //入度
	}
	if(topo())
	{
		for(int i=0;i<path.size();i++)	cout<<path[i]<<" ";
	}
	else	cout<<-1<<endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值