Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // { Driver Code Starts
- #include <bits/stdc++.h>
- using namespace std;
- // } Driver Code Ends
- class Solution
- {
- public:
- //Function to return list containing vertices in Topological order.
- void dfs(int src,bool *v,vector<int> &result,vector<int> adj[]){
- v[src]=true;
- for(auto node:adj[src])
- if (v[node]==false){
- dfs(node,v,result,adj);
- }
- result.push_back(src);
- }
- vector<int> topoSort(int V, vector<int> adj[])
- {
- // code here
- bool v[V]={false};
- vector<int> result;
- for(int i=0;i<V;++i)
- if (v[i]==false)
- dfs(i,v,result,adj);
- reverse(result.begin(),result.end());
- return result;
- }
- };
- // { Driver Code Starts.
- /* 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
- */
- int check(int V, vector <int> &res, vector<int> adj[]) {
- vector<int> 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 0;
- }
- }
- return 1;
- }
- 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);
- }
- Solution obj;
- vector <int> res = obj.topoSort(N, adj);
- cout << check(N, res, adj) << endl;
- }
- return 0;
- } // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement