跳到正文

个人记录

图的拓扑排序笔记

Frederick123约 3 分钟
原文
文章信息与版本

文章信息

发布
2022年11月13日
收录
2025年12月12日
更新
2026年10月24日
篇幅
约 3 分钟
获赞
1

版本

  1. v1当前

读入一个有向图,输出其拓扑排序。

输入格式

第 11 行一个数 nn.

第 22 至 n+1n+1 行中,第 kk 行第一个数是 k−1k-1 ,紧接着是多个数,以 00 为结束标志。这些数所代表的点与 k−1k-1 所代表的点间有一条单向的路。

输入格式

其拓扑排序。

样例输入

代码
7
1 0
2 1 0
3 2 0
4 1 0
5 2 4 0
6 2 4 0
7 3 5 6 0

样例输出

代码
1 2 4 3 5 6 7

代码

C++
#include<bits/stdc++.h>
typedef long long ll;
const int INF=2e8;
const ll LLINF=LLONG_MAX;
const int N=10007;
using namespace std;
void swap(int &a,int &b);
inline int read();
inline int write(int);
int n,x,y,a[N],in[N],ans;
//in[i] is in-degree;
//a[i] is time;
vector<int> q[N];//dynamic array
queue<int> s;//queue
int t[N],temp=0;
int main(int argc,char **argv)
{
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	n=read();
	for(int i=1;i<=n;i++)
	{
		x=i;
		//a[i]=read();
		y=read();
		while(y)
		{
			in[x]++;
			q[y].push_back(x);
			y=read();
		} 
	}
	for(int i=1;i<=n;i++)
	{
		if(!in[i])//in-degree equals to 0
		{
			s.push(i);
		}
	}
	while(!s.empty())
	{
		int x=s.front();
		s.pop();
		t[++temp]=x;
		for(int i=0;i<q[x].size();i++)
		{
			int y=q[x][i];
			in[y]--;
			if(in[y]==0)s.push(y);
		}
	}
	for(int i=1;i<=temp;i++)
	write(t[i]),putchar(32);
	return 0;
}
inline int read()
{
	char ch=getchar();
	int x=0,f=1;
	while(ch<'0'||ch>'9')
	{
		if(ch=='-')f=-1;
		ch=getchar();
	}
	while(ch>='0'&&ch<='9')
	{
		x=(x<<1)+(x<<3)+(ch^48);
		ch=getchar();
	}
	return x*f;
}
inline int write(int x)
{
	if(x<0) putchar('-'),x=-x;
	if(x>9) write(x/10);
	putchar(x%10+'0');
	return x;
}
void swap(int &a,int &b)
{
	a = a^b;
    b = a^b;
    a = a^b;
}
原文