经典拓扑排序模板

  拓扑排序是图论中一种典型的算法。通过拓扑排序可以梳理图的层次结构。像什么工期完成类的图论任务,就是典型的应用。第二个应用就是判断图中是否存在环路的问题。
  程序中建图的方式是邻接表形式,代码如下:

vector<vector<int> > graph(n, vector<int>{});

  下面是拓扑排序的模板:

	vector<vector<int> > graph(n, vector<int>{});
	
	根据所给有向图的指向关系,完成graph图的建立
	
	// 统计初始入度为0的
	vector<int> indegree(n, 0);
	for (int i=0; i<n; i++) {
		for (int j=0; j<graph[i].size(); j++) {
			indegree[graph[i][j]]++;
		}
	} 
	queue<int> que; // 队列存储,其实如果对于顺序没有要求栈也行
	for (int i=0; i<n; i++) {
		if (indegree[i] == 0)
			que.push(i);
	} 
	while (!que.empty()) {
		int a = que.front();
		cout << a + 1 << " ";
		que.pop();
		for (int i=0; i<graph[a].size(); i++) {
			indegree[graph[a][i]]--;
			if (indegree[graph[a][i]] == 0)
				que.push(graph[a][i]);
		}
	}
/*
	如果要判断是否存在环路,可以在最后判断一下indegree数组,如果全为0说明无环,否则说明有环。
*/

  来两道题练习一下吧!(题目是他人博客找的,不是网站来的。没有去OJ验证AC,只是通过了样例测试。输出格式也没调,勉强过关吧!)

题目一:确定比赛名次

代码如下:

#include<bits/stdc++.h>
using namespace std;

int main(void) {
	int n, m;
	cin >> n >> m;
	vector<vector<int>> graph(n, vector<int>{});
	for (int i=0; i<m; i++) {
		int u, v;
		cin >> u >> v;
		graph[u-1].push_back(v-1);
	}
	vector<int> indegree(n, 0);
	for (int i=0; i<graph.size(); i++) {
		for (int j=0; j<graph[i].size(); j++) {
			indegree[graph[i][j]]++;
		}
	}
	priority_queue<int> que; // 题目对顺序有要求,这里用了优先队列
	for (int i=0; i<n; i++) {
		if (indegree[i] == 0)
			que.push(-i);
	}
	while (!que.empty()) {
		int num = -que.top();
		cout << num + 1 << " ";
		que.pop();
		for (int i=0; i<graph[num].size(); i++) {
			indegree[graph[num][i]]--;
			if (indegree[graph[num][i]] == 0)
				que.push(-graph[num][i]);
		}
	}
	return 0;
}

题目二:POJ 2367:Genealogical tree

#include<bits/stdc++.h>
using namespace std;

int main(void) {
	int n;
	cin >> n;
	vector<vector<int> > graph(n, vector<int>{});
	int i;
	for (int j=0; j<n; j++) {
		while (1) {
			cin >> i;
			if (i != 0) 
				graph[j].push_back(i-1);
			else
				break;
		}
	}
	vector<int> indegree(n, 0);
	for (int i=0; i<n; i++) {
		for (int j=0; j<graph[i].size(); j++) {
			indegree[graph[i][j]]++;
		}
	} 
	queue<int> que;
	for (int i=0; i<n; i++) {
		if (indegree[i] == 0)
			que.push(i);
	} 
	while (!que.empty()) {
		int a = que.front();
		cout << a + 1 << " ";
		que.pop();
		for (int i=0; i<graph[a].size(); i++) {
			indegree[graph[a][i]]--;
			if (indegree[graph[a][i]] == 0)
				que.push(graph[a][i]);
		}
	}
	return 0;
}

参考资料:https://blog.csdn.net/wang_123_zy/article/details/81411683

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值