-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTopologicalSort
75 lines (71 loc) · 1.37 KB
/
TopologicalSort
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
73
74
75
#include<iostream>
#include<vector>
#include<queue>
#include<list>
#include<stack>
class Node{
public:
int vertices;
std::list<int>*adj;
Node(int vertices):vertices(vertices),adj(new std::list<int>[vertices]){}
void addEdge(int u,int v){
adj[u].push_back(v);
}
int topoSort(){ //using bfs
std::vector<int>Inorder(6,0);
std::queue<int>q;
std::vector<int>visited(6,0);
for(int i=0;i<6;++i){
for(auto it:adj[i]){
Inorder[it]++;
}
}
for(int i=0;i<Inorder.size();++i){
if(Inorder[i]==0)
q.push(i);
}
int cnt = 0;
while(!q.empty()){
int x = q.front();
cnt++;
visited[x]=1;
for(auto it:adj[x]){
//std::cout<<x<<" "<<it<<"\n";
if(!visited[it] && --Inorder[it]==0)
q.push(it);
}
q.pop();
}
if(cnt==vertices)
return 1;
return 0;
}
void dfs(int u,std::stack<int>&s,std::vector<int>&visited){
visited[u]=1;
for(auto it:adj[u]){
if(!visited[it])
dfs(it,s,visited);
}
s.push(u);
}
};
int main(){
Node g(6);
g.addEdge(5,0);
g.addEdge(5,2);
g.addEdge(2,3);
g.addEdge(4,0);
g.addEdge(4,1);
g.addEdge(1,3);
std::stack<int>s;
std::vector<int>visited(6,0);
for(int i=0;i<6;++i){
if(!visited[i])
g.dfs(0,s,visited);
}
if(s.size()==6){
std::cout<<"1\n";
}else
std::cout<<"0\n";
//std::cout<<g.topoSort();
}