summaryrefslogtreecommitdiff
path: root/src/main/Toposort.java
blob: a59ad1acff903ac982d260ae24741ab0f5cad79a (plain)
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
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.IntStream;

public class Toposort {
    private static ArrayList<Integer> toposort(ArrayList<Integer>[] adj) {
        boolean[] visited = new boolean[adj.length];
        ArrayList<Integer> order = new ArrayList<Integer>();
        int[] postV = new int[adj.length];
        int[] clock = new int[1];
        dfs(adj, visited, postV, clock);
        // https://stackoverflow.com/questions/951848/java-array-sort-quick-way-to-get-a-sorted-list-of-indices-of-an-array/35701049
        int[] temp = IntStream.range(0, postV.length).boxed().sorted((i, j) -> postV[i] - postV[j]).mapToInt(ele -> ele).toArray();
        Arrays.sort(postV);

        for (int i = adj.length - 1; i > -1; i--) {
            order.add(temp[i]);
        }
        return order;
    }

    private static void dfs(ArrayList<Integer>[] adj, boolean[] visited, int[] postV, int[] clock) {
        for (int v = 0; v < adj.length; v++) {
            if (!visited[v])
                explore(v, adj, visited, postV, clock);
        }
    }

    private static void explore(int v, ArrayList<Integer>[] adj, boolean[] visited, int[] postV, int[] clock) {
        visited[v] = true;
        for (int w : adj[v]) {
            if (!visited[w])
                explore(w, adj, visited, postV, clock);
        }
        postVisit(v, clock, postV);
    }

    private static void postVisit(int v, int[] clock, int[] postV) {
        postV[v] = clock[0];
        clock[0] = clock[0] + 1;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();
        ArrayList<Integer>[] adj = (ArrayList<Integer>[]) new ArrayList[n];
        for (int i = 0; i < n; i++) {
            adj[i] = new ArrayList<Integer>();
        }
        for (int i = 0; i < m; i++) {
            int x, y;
            x = scanner.nextInt();
            y = scanner.nextInt();
            adj[x - 1].add(y - 1);
        }
        ArrayList<Integer> order = toposort(adj);
        for (int x : order) {
            System.out.print((x + 1) + " ");
        }
    }
}