forked from nishitpanchal395/projecthactoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopologicalSortforGraph.cpp
More file actions
79 lines (65 loc) · 1.51 KB
/
Copy pathTopologicalSortforGraph.cpp
File metadata and controls
79 lines (65 loc) · 1.51 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
73
74
75
76
77
78
79
#include<iostream>
#include<vector>
#include<algorithm>
/*
The class accepts a directed graph in form of adjacency list and checks whether its
topological sorts exits or not and produces its corresponding topological sort.
Complexity: O(n)
*/
class TopologicalSort
{
private:
int n;
bool exist;
std::vector<int> sorted_v, visited, rank;
std::vector<std::vector<int>> &graph;
/* topological sorting */
void topo(int par)
{
visited[par] = 1;
for(int e: graph[par])
{
if(!visited[e]) topo(e);
}
sorted_v.push_back(par);
}
void generate_topological_sort()
{
sorted_v.assign(0, 0);
visited.assign(n, 0);
for(int i = 0;i < n; i++)
{
if(!visited[i]) topo(i);
}
std::reverse(sorted_v.begin(), sorted_v.end());
check_existence();
}
void check_existence()
{
rank.assign(n, 0);
for(int i =0 ;i < n; i++)
{
rank[sorted_v[i]] = i;
}
for(int i =0 ;i <n; i++)
{
for(int e: graph[i])
{
if(rank[i] > rank[e]) exist = false;
}
}
}
public:
TopologicalSort(std::vector<std::vector<int>> &graph) : graph(graph), n((int)graph.size()), exist(true)
{
generate_topological_sort();
}
std::vector<int> get_sort()
{
return sorted_v;
}
bool is_valid()
{
return exist;
}
};