拓扑排序(Topological Sort)

判断有向无环图的方法是对AOV网络构造它的拓扑有序序列,即将各个顶点排列成一个线性有序的序列,使得AOV网络中所有存在的前驱和后继关系都能得到满足。这种构造AOV网络全部顶点的拓扑有序序列的运算为拓扑排序。如果通过拓扑排序能将AOV网络所有顶点都排入一个拓扑有序序列中,则该AOV网络中必定不存在有向环;相反,如果得不到所有顶点的拓扑有序序列,则说明该AOV网络中存在有向环。


拓扑排序实现方法:

①从AOV网络中选择一个入度为0的顶点输出。

②从AOV网络中删除该顶点及该顶点发出的所有边。

③重复步骤1和2,直到找不到入度为0的顶点。


代码:

#include <iostream>
#include <stack>
#include <vector>


using namespace std;

const int maxn = 10;


int n,m;
vector<int> list[maxn];
int res[maxn];
int ind[maxn];		//入度 

bool Input(){
	cin>>n>>m;
	if(n == 0 && m == 0)
		return false;
	for(int i = 1; i <= n; i++){
		list[i].clear();
		ind[i] = 0;
	}
	int u,v;
	for(int i = 0; i < m; i++){
		cin>>u>>v;
		list[u].push_back(v);
		ind[v]++;
	}
	return true;
}

bool TopSort(){
	int index = 1;
	stack<int> st;
	for(int i = 1; i <= n; i++){
		if(ind[i] == 0) st.push(i);
	}
	
	for(int i = 0; i < n; i++){
		if(st.empty()) return true;//有环存在 
		else{
			int u = st.top(); st.pop();
			res[index++] = u;
			for(int j = 0; j < list[u].size(); j++){
				if(--ind[list[u][j]] == 0){
					st.push(list[u][j]);
				}
			}
		}
		
	}//end of for
	
	return false;
}

void Solve(){
	if(TopSort()){
		cout<<"Network has a cycle!\n";
		return;
	}
	else{
		for(int i = 1; i <= n; i++){
			cout<<res[i]<<" ";
		}
		cout<<"\n";
	}
}


int main(){
	while(Input()){
		Solve();
	}
	return 0;
}

/*

input: 
6 8
1 2
1 4
2 6
3 2
3 6
5 1
5 2
5 6

6 8
1 3
1 2
2 5
3 4
4 2
4 6
5 4
5 6
0 0

output:
5 1 4 3 2 6
Network has a cycle!

*/


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值