forked from ZoranPandovski/al-go-rithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTopologicalSort.cpp
102 lines (91 loc) · 2.01 KB
/
TopologicalSort.cpp
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include<bits/stdc++.h>
using namespace std;
//Position this line where user code will be pasted.
/* Function to check if elements returned by user
* contains the elements in topological sorted form
* V: number of vertices
* *res: array containing elements in topological sorted form
* adj[]: graph input
*/
bool check(int V, int* res, vector<int> adj[]){
bool flag =true;
for(int i=0;i<V && flag;i++)
{
int n=adj[res[i]].size();
for(auto j : adj[res[i]])
{
for(int k=i+1;k<V;k++)
{
if(res[k]==j )
n--;
}
}
if(n!=0)
flag =false;
}
if(flag==false)
return 0;
return 1;
}
/*This is a function problem.You only need to complete the function given below*/
// The Graph structure is as folows
/* Function which sorts the graph vertices in topological form
* N: number of vertices
* adj[]: input graph
* NOTE: You must return dynamically allocated array
*/
int topSortUtil(int v,vector<int> adj[],int* vis,stack<int>& st)
{
//cout<<"V "<<v<<endl;
vis[v]=1;
for(int i=0;i<adj[v].size();++i)
{
if(vis[adj[v][i]]==0)
{
topSortUtil(adj[v][i],adj,vis,st);
}
}
st.push(v);
}
int* topoSort(int V, vector<int> adj[])
{
// Your code here
int vis[V]{};
stack<int> st;
for(int i=0;i<V;++i)
{
if(vis[i]==0)
{
//cout<<"U "<<i<<endl;
topSortUtil(i,adj,vis,st);
}
}
//cout<<"K "<<st.size()<<endl;
int* v=new int[V];
for(int i=0;i<V;++i)
{
v[i]=st.top();
st.pop();
}
return v;
}
// Driver Code
int main()
{
int T;
cin>>T;
while(T--)
{
int N,E;
cin>>E>>N;
int u,v;
vector<int> adj[N];
for(int i=0;i<E;i++)
{
cin>>u>>v;
adj[u].push_back(v);
}
int *res = topoSort(N, adj);
cout<<check(N, res, adj)<<endl;
}
}