[算法与数据结构][图算法][拓扑排序]尝试3
Posted xcy6666
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[算法与数据结构][图算法][拓扑排序]尝试3相关的知识,希望对你有一定的参考价值。
#include<cassert>
#include<vector>
#include<queue>
#include<iostream>
/*
e.g.1 1
e.g.2 2 -> 1
e.g.3
/- 6
4 -- 3 -- 1
5 -- 2 -/
e.g.4
2 -> 1 -> 3 -> 2
*/
using namespace std;
vector<vector<int>> adj_list(7);
vector<int> in_d(7, 0); // in degree of id
void construct(){
//e.g.3
adj_list[4].push_back(6);
adj_list[4].push_back(3);
adj_list[3].push_back(1);
adj_list[5].push_back(2);
adj_list[2].push_back(1);
//time: O(E), space O(E)
//look up; remove; insert
in_d[6]++;
in_d[3]++;
in_d[1]++;
in_d[2]++;
in_d[1]++;
//time: O(V) + O(E*log_deg*1)
//space: O(V+V+deg)
}
bool topo_sort(){
vector<int> res;
queue<int> next;
//priority_queue<int> next;
for(int i=1; i < in_d.size(); i++){
if(in_d[i] == 0) next.push(i);
}
while(next.size() > 0){
int id = next.front(); next.pop();
//int id = next.top(); next.pop();
res.push_back(id);
for(auto nbr : adj_list[id]){
in_d[nbr]--;
if(in_d[nbr] == 0) next.push(nbr);
}
}
//time: O(V*log_deg)
if(res.size()+1 != in_d.size())
return false;
for(auto e : res) cout << e << " ";
cout << endl;
return true;
}
int main(){
construct();
// print_deg_ids();
topo_sort();
}
/*
* fail to construct a data structure that can:
* store {id, degree}
* quick find minimal degree
* quick update degree
*
* deg_ids: store degree : set<id>, sorted on degree
* vector<int> degree
*
* reflection:
* deg_ids is a global structure to maintain all nodes degree info and updated all nodes order info
* on graph structure:
* bfs pattern or dfs pattern is common
* for the next degree 0 nodes, a bfs pattern can be used to simplify
*
* */
以上是关于[算法与数据结构][图算法][拓扑排序]尝试3的主要内容,如果未能解决你的问题,请参考以下文章