File tree Expand file tree Collapse file tree 2 files changed +73
-0
lines changed Expand file tree Collapse file tree 2 files changed +73
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Topological Sorting of directed and acyclic graph.
2
+ // It is done by BFS and using in_degree array.
3
+ // It has one property that it returns the sorting in lexographical order.
4
+ #include < bits/stdc++.h>
5
+ using namespace std ;
6
+
7
+ int vertices,edges;
8
+ vector<int >adjcency_list[100001 ];
9
+
10
+ vector<int > topological_sort (){
11
+ vector<int > topo;
12
+ int in_degree[vertices+1 ];
13
+ bool visited[vertices+1 ];
14
+ priority_queue<int ,vector<int >,greater<int >> q;
15
+
16
+ for (int i=1 ;i<=vertices;i++){
17
+ visited[i]=false ;
18
+ in_degree[i]=0 ;
19
+ }
20
+
21
+ for (int i=1 ;i<=vertices;i++){
22
+ for (int j:adjcency_list[i]){
23
+ in_degree[j]=in_degree[j]+1 ;
24
+ }
25
+ }
26
+
27
+ for (int i=1 ;i<=vertices;i++){
28
+ if (in_degree[i]==0 ){
29
+ visited[i]=true ;
30
+ q.push (i);
31
+ }
32
+ }
33
+ int k=0 ;
34
+ while (!q.empty ()){
35
+ int v=q.top ();
36
+ q.pop ();
37
+ topo.push_back (v);
38
+ for (int i:adjcency_list[v]){
39
+ if (visited[i]==false ){
40
+ in_degree[i]=in_degree[i]-1 ;
41
+ if (in_degree[i]==0 ){
42
+ q.push (i);
43
+ visited[i]=true ;
44
+ }
45
+ }
46
+ }
47
+ }
48
+ return topo;
49
+ }
50
+
51
+ int main (){
52
+ cout<<" Enter number of vertices and edges:\n " ;
53
+ cin>>vertices>>edges;
54
+
55
+ vector<int > topological_sorted;
56
+
57
+ cout<<" Enter the edges directed from X (first number) to Y (second number):\n " ;
58
+ for (int i=0 ;i<edges;i++){
59
+ int u,v;
60
+ cin>>u>>v;
61
+ adjcency_list[u].push_back (v);
62
+ }
63
+
64
+ topological_sorted=topological_sort ();
65
+
66
+ cout<<" Topological Sort of the given graph: " ;
67
+ for (int i=0 ;i<topological_sorted.size ();i++){
68
+ cout<<topological_sorted[i]<<" " ;
69
+ }
70
+ cout<<" \n " ;
71
+ return 0 ;
72
+ }
Original file line number Diff line number Diff line change @@ -43,6 +43,7 @@ Code | Test
43
43
[ Quick Sort] ( https://github.com/kartikeysingh6/code_problems/blob/master/classical_algorithms/c++/quicksort.cpp ) | Missing tests
44
44
[ 0/1 Knapsack Problem] ( https://github.com/ErR0rpj/code_problems/blob/master/classical_algorithms/c%2B%2B/01_knapsack_problem.cpp ) | Missing tests
45
45
[ Kadane's Algorithm] ( https://github.com/ErR0rpj/code_problems/blob/master/classical_algorithms/c%2B%2B/Kadane_Algorithm.cpp ) | Missing tests
46
+ [ Topological Sort] ( https://github.com/ErR0rpj/code_problems/blob/master/classical_algorithms/c%2B%2B/Topological_sort.cpp ) | Missing Tests
46
47
47
48
# Codeforces
48
49
You can’t perform that action at this time.
0 commit comments