From 05fbe8483f52bc11796e24112971bd77664bb0ff Mon Sep 17 00:00:00 2001 From: Disha167 Date: Tue, 20 Oct 2020 03:19:28 +0530 Subject: [PATCH] Create topological sort.cpp --- CPP/graphs/topological sort.cpp | 88 +++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 CPP/graphs/topological sort.cpp diff --git a/CPP/graphs/topological sort.cpp b/CPP/graphs/topological sort.cpp new file mode 100644 index 0000000..0d77e8d --- /dev/null +++ b/CPP/graphs/topological sort.cpp @@ -0,0 +1,88 @@ +//This sort algorithm is used to find dependency among files . Below is its simple to understand implementation using bfs +#include + +using namespace std; + +int *topoSort(int N, vector adj[]); + +/* 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 adj[]) { + vector map(V, -1); + for (int i = 0; i < V; i++) { + map[res[i]] = i; + } + for (int i = 0; i < V; i++) { + for (int v : adj[i]) { + if (map[i] > map[v]) return false; + } + } + return true; +} + +int main() { + int T; + cin >> T; + while (T--) { + int N, E; + cin >> E >> N; + int u, v; + + vector 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; + } + +// 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* topoSort(int V, vector adj[]) { + int indegree[V]={0}; + int index=0; + int *result=new int[V]; + for(int i=0;iq; + for(int i=0;i