拓扑排序 C++实现

(1) Directed Acyclic Graph 无环有向图

            检测一个工程是否顺利进行

            若以图中顶点表示活动,,有向边表示活动之间的优先关系,此图为AOV(Activity On Vertex network)

           Vi -> Vj ,表示 Vi 是 Vj 的前趋,Vj 是 Vi 的后继

(2)对AOV排序,即拓扑排序,算法:

             1.从AOV中选取无前趋的点(即入度为0的点)且输出

             2.从网中删去该点,并且删除所有由该点发出的边

             3.重复1,2,直到网中不存在无前趋的点

(3)结果

             1. 网中无点,成功。

             2.有点,说明网中有回路,排序失败。

(4)具体实现

#include <iostream>
using namespace std;
#define N 9

/* if (Vi -> Vj)  matrix[i][j] = 1   */
int matrix[N][N]=
{
0,1,1,1,0,0,0,0,0,
0,0,0,0,1,0,0,0,0,
0,0,0,0,1,0,0,0,0,
0,0,0,0,0,1,0,0,0,
0,0,0,0,0,0,1,1,0,
0,0,0,0,0,0,0,1,0,
0,0,0,0,0,0,0,0,1,
0,0,0,0,0,0,0,0,1,
0,0,0,0,0,0,0,0,0
};


int into[N];  // Vertex N 's  indegrees
/* functions declaration */
void get_into_degree(int n);
void toposort(int n);


/* functions definition */
// in degrees
void get_into_degree(int n){
	for(int j = 0; j < n; ++j){
		into[j] = 0;
		for(int i = 0; i < n; ++i)
			if(matrix[i][j] == 1)
				into[j]++;
	}
}


// calculate and output
void toposort(int n){
	//需要输出n个结点,排序结束
	for(int i = 1; i <= n; ++i){
	   int j = 0;
	   // find the vertex which indegree is 0
	   while(j < n && into[j] != 0) j++; 
	   // output the vertex
	   cout<<j + 1<<" ";

	   into[j] = N; // in order not to output the j again

	   // clear the Vertex's edge
	   for(int k = 0; k < n; ++k)
			if(matrix[j][k] == 1)
				into[k]--;
	}
}

int main(){
	get_into_degree(N);
	toposort(N);
	return 0;
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

信知阁

您的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值