Problem Statement:
Given a Directed and Acyclic Graph having vertices and edges, print topological sorting of the vertices.
Input:
First line consists of two space separated integers denoting and .
Each of the following lines consists of two space separated integers and denoting there is an from directed towards .
First line consists of two space separated integers denoting and .
Each of the following lines consists of two space separated integers and denoting there is an from directed towards .
Output:
Print space separated integers denoting the topological sort, if there are multiple ordering print the lexicographically smallest one.
Print space separated integers denoting the topological sort, if there are multiple ordering print the lexicographically smallest one.
Constraints:
Code:
import java.util.*;import java.io.*;
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
ArrayList<Integer> res=new ArrayList();
int indegree[]=new int[n+1];
ArrayList <Integer>adj[]=new ArrayList[n+1];
for(int i=0;i<=n;i++)
{
adj[i]=new ArrayList<Integer>();
}
for(int i=0;i<m;i++)
{
int u=sc.nextInt();
int v=sc.nextInt();
adj[u].add(v);
indegree[v]++;
}
LinkedList<Integer> q=new LinkedList<Integer>();
for(int i=1;i<=n;i++)
{
if(indegree[i]==0){q.add(i);}
}
Collections.sort(q);//sort to get lexicographical order
int count=0;
while(q.size()!=0)
{
int x=q.poll();
res.add(x);
count++;
//making indegree of adjacent vertices decrease by 1
for(int i=0;i<adj[x].size();i++)
{
indegree[(int)adj[x].get(i)]--;
if(indegree[(int)adj[x].get(i)]==0)
{
q.add((int)adj[x].get(i));
}
}
Collections.sort(q);//sort to get lexicographical order
}
for(int i=0;i<res.size();i++)
{
System.out.print(res.get(i)+" ");
}
System.out.println("");
}
}
Comments
Post a Comment