-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathDFSTopo.h
More file actions
72 lines (62 loc) · 1.6 KB
/
Copy pathDFSTopo.h
File metadata and controls
72 lines (62 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#ifndef DFSTOPO_H_INCLUDED
#define DFSTOPO_H_INCLUDED
#include"Digraph.h"
#include"EdgeWeightedDigraph.h"
/*
拓扑排序 DFS+一行代码
BFS是将入度为零的先加入queue
*/
class DFSTopo{
private:
vector<bool> marked;
stack<int> reversePost;
public:
DFSTopo(Digraph* G){
marked.resize(G->getV(),false);
}
vector<int> getTopo(Digraph* G){
for(int v=0;v<G->getV();v++){ //可能是多连通分量图
if(!marked[v])
dfs(G,v);
}
vector<int> res;
while(!reversePost.empty()){
res.push_back(reversePost.top());
reversePost.pop();
}
return res;
}
void dfs(Digraph* G,int v){
marked[v] = true;
for(int w:G->getadj(v)){
if(!marked[w])
dfs(G,w);
}
reversePost.push(v);
}
//****************************关于加权Weighted 有向图的重载
DFSTopo(EdgeWeightedDigraph* G){
marked.resize(G->getV(),false);
}
vector<int> getTopo(EdgeWeightedDigraph* G){
for(int v=0;v<G->getV();v++){ //可能是多连通分量图
if(!marked[v])
dfs(G,v);
}
vector<int> res;
while(!reversePost.empty()){
res.push_back(reversePost.top());
reversePost.pop();
}
return res;
}
void dfs(EdgeWeightedDigraph* G,int v){
marked[v] = true;
for(DiEdge e:G->getadj(v)){
if(!marked[e.to()])
dfs(G,e.to());
}
reversePost.push(v);
}
};
#endif // DFSTOPO_H_INCLUDED