经典拓扑排序模板

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

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

猜你喜欢

转载自blog.csdn.net/gls_nuaa/article/details/115102635