图论-拓扑排序

有向无环图(Directed Acyclic Graph,简称DAG)拓扑排序

简单化来讲,把有向图比作按顺序做事,拓扑排序就是输出做事的顺序

 

算法过程:

1> 找入度为0的点访问输出,断其出边

2> 重复1,没有入度为0的点时结束



#include <iostream>
using namespace std;

int n, m, num;                      //num记录访问过的点的个数 
int a[2001][2001];                  //邻接矩阵 
int In[2001];                       //记录每个点的入度

int In_zero() {                     //找图中入度为0的点返回
	for(int i=1; i<=n; i++) if(In[i] == 0) return i;
	return 0;                      //没有找到
}

void topology() {
	int x = In_zero();
	if(x == 0) return;
	cout << x << " -> ";
	In[x] = -1;                    //不需要标记数组,直接使入度=-1
	num ++;
	for(int i=1; i<=n; i++) {
		if(a[x][i] == 1) {
			In[i] --;            //断x的出边
			//a[x][i] = 0;
		}
	}
	topology();
}

void build_graph() {
	int x, y;
	cin >> n >> m;
	for(int i=1; i<=m; i++) {
		cin >> x >> y;
		a[x][y] = 1;
		In[y] ++;
	}
}

int main() {
	build_graph();
	topology();
	if(num < n) cout << "Is not DAG!" << endl; //图中有环 
	cout << endl << num << endl;
	return 0;
}

随意举个栗子:


测试数据:

6 5
5 2
5 4
1 3
1 6
2 1


上图的拓扑排序结果:5 2 1 3 4 6




###

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值