Topological sort algorithm

definition

Topological sorting of a Directed Acyclic Graph (DAG) G is to arrange all vertices in G into a linear sequence, so that any pair of vertices u and v in the graph, if the edge <u,v>∈ E(G), then u appears before v in the linear sequence. Usually, such a linear sequence is called a sequence satisfying a topological order, or a topological sequence for short. Simply put, a total order on a set is obtained from a partial order on a set, and this operation is called topological sorting.
insert image description here

As shown in the figure above, the topological sorting sequence is {1, 2, 3, 4, 5}
There may be multiple
topological sequences. The simplest
code to implement topological sorting with queues:

#include<cstdio>
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
vector<int> edge[100000];//邻接链表
int degree[100000];
int n,m; 
void top(){
    
    
	queue<int> node;
	//找到入度为零的点 
	for(int i=1;i<=n;i++){
    
    
		if(degree[i]==0){
    
    
			node.push(i);
		}
	}
	while(!node.empty()){
    
    
		int now = node.front();
		printf("%d ",now);//输出序列
		node.pop();
		for(int i=0;i<edge[now].size();i++){
    
    //找相邻节点 
			int dot = edge[now][i];
			degree[dot]--;
			if(degree[dot]==0){
    
    //入度为零入队 
				node.push(dot);
			} 
		}
	}
} 
int main(){
    
    
	cin>>n>>m;
	//建立邻接链表 
	for(int i=0;i<=m;i++){
    
    
		int x,y;
		cin>>x>>y;
		if(x==0&&y==0)break;
		degree[y]++;
		edge[x].push_back(y);
	}
	top();
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325000843&siteId=291194637