-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtopoSort.java
80 lines (68 loc) · 2.12 KB
/
topoSort.java
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
import java.util.*;
import java.io.*;
import java.lang.*;
class Main{
public static void main(String[] args){
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(reader.readLine());
while(t--){
ArrayList<ArrayList<Integer>>list=new ArrayList<>();
String st[]=read.readLine().trim().split("\\s+");
int edg=Integer.parseInt(st[0]);
int nov=Integer.parseInt(st[1]);
for(int i=0; i<nov+1; i++)
list.add(new ArrayList<Integer>());
int p=0;
for(int i=1;i<=edg;i++){
String s[]=read.readLine().trim().split("\s+");
int u=Integer.parseInt(s[0]);
int v=Integer.parseInt(s[1]);
list.get(u).add(v);
}
int[] res= new Solution().topoSort(nov, list);
if(check(list, nov, res)==true)
System.outrintln("1");
else
System.out.println("0");
}
}
static boolean check(ArrayList<ArrayList<Integer>>list, int V, int[] res){
int[] map=new int[V];
for(int i=0;i<V;i++){
map[res[i]]=1;
}
for(int i=0;i<V;i++){
for(int v:list.get(i)){
if(map[i]>map[v])
return false;
}
}
return true;
}
}
class Solution{
static void findTopoSort(int node, int vis[], ArrayList<ArrayList<Integer>> adj, Stack<Integer>st) {
vis[node] =1;
for(Integer it:adj.get(node)){
if(vis[it]==0){
findTopoSort(it, vis, adj, st);
}
}
st.push(node);
}
static int[] topoSort(int N, ArrayList<ArrayList<Integer>> adj){
Stack<Integer> st=new Stack<Integer>();
int vis[]=new int[N];
for(int i=0; i<N; i++){
if(vis[i]==0){
findTopoSort(i, vis, adj, st);
}
}
int topo[]=new int[N];
int ind=0;
while(!st.isEmpty()){
topo[ind++]=st.pop();
}
return topo;
}
}