summaryrefslogtreecommitdiff
path: root/src/main/Toposort.java
blob: ede04b41664449b1eb7215a64c208babe259c93b (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.Collections;
import java.util.Scanner;

public class Toposort {
    private static ArrayList<Integer> toposort(ArrayList<ArrayList<Integer>> adj) {
        int[] visited = new int[adj.size()];
        ArrayList<Integer> postv = new ArrayList<>(Collections.nCopies(adj.size(),0));
        int[] clock = new int[1];
        dfs(adj, visited, postv, clock);

        ArrayList<Integer> reverse_postv = (ArrayList<Integer>) postv.clone();
        Collections.sort(reverse_postv, Collections.reverseOrder());

        ArrayList<Integer> order = new ArrayList<Integer>();

        for (int n : reverse_postv) {
            order.add(postv.indexOf(n));
        }

        return order;
    }

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

    private static void explore(ArrayList<ArrayList<Integer>> adj, int v, int[] visited, ArrayList<Integer> postv, int[] clock) {
        visited[v] = 1;
        clock[0] = clock[0] + 1;

        for (int n : adj.get(v)) {
            if (visited[n] == 0)
                explore(adj, n, visited, postv, clock);
        }
        postv.set(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<ArrayList<Integer>> adj = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            adj.add(new ArrayList<Integer>());
        }
        for (int i = 0; i < m; i++) {
            int x, y;
            x = scanner.nextInt();
            y = scanner.nextInt();
            adj.get(x - 1).add(y - 1);
        }
        ArrayList<Integer> order = toposort(adj);
        for (int x : order) {
            System.out.print((x + 1) + " ");
        }
    }
}