Topological sort

PROBLEM :
Given a directed graph you need to complete the function topoSort which returns an array having the topologically sorted elements of the array and takes two arguments . The first argument is the Graph graph represented as adjacency list and the second is the number of vertices V .

Note : There can be multiple topological sorts of a Graph.  The driver program that calls your function doesn't match your output element by element, but checks whether the output produced by your function is a valid topological sort or not.

Input:
The first line of input takes the no of test cases then T test cases follow . Each test case contains two lines . The first  line of each test case  contains two integers E and V representing no of edges and the no of vertices . Then in the next line are E  pairs of integers u v representing an edge from u to v in the graph.

Output:
For each test case output will be 1 if the topological sort is done correctly else it will be 0 .

Constraints:
1<=T<=50
1<=E,V<=50
0<=u,v<V
Example:

Input
1
6 6
5 0 5 2 2 3 4 0 4 1 1 3

Output
1

The output 1 denotes that the order is valid.  So if you have implemented your function correctly, then output would be 1 for all test cases.

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/* You need to complete this function */

void Topological(int ,bool [],stack<int> &,vector<int> [] ) ;
int * topoSort(vector<int> graph[], int V)
{
    bool visited[V] ;
    stack<int> stak ;
   
    for(int i=0;i<V;i++)
        visited[i]=false ;
       
    for(int i=0;i<V;i++)
    {
        if(visited[i]!=true)
            Topological(i,visited,stak,graph) ;
    }
   
    int *arr=new int[V]; ;
    int i=0 ;
    while(!stak.empty())
    {
        arr[i++]=stak.top() ;
        stak.pop() ;
    }
   
    return arr ;
}

void Topological(int data,bool visited[],stack<int> &stak,vector<int> graph[])
{
    visited[data]=true ;
   
    vector<int>::iterator i ;
    for(i=graph[data].begin();i!=graph[data].end();i++)
    {
        if(visited[*i]!=true)
            Topological(*i,visited,stak,graph) ;
    }
    stak.push(data) ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )