summaryrefslogtreecommitdiff
path: root/src/main/Acyclicity.java
blob: 1d69ab88a7b69c3e3adbbb685950ec8d4930e9df (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
import java.util.ArrayList;
import java.util.Scanner;

public class Acyclicity {
    static int acyclic(ArrayList<ArrayList<Integer>> adj) {
        ArrayList<Integer> visited = new ArrayList<>();
        int[] prev = new int[adj.size()];
        int[] postv = new int[adj.size()];
        int[] clock = new int[1];
        clock[0] = 0;
        dfs(adj, visited, prev, postv, clock);

        for (int u = 0; u < adj.size(); u++) {
            for (int v : adj.get(u)) {
                if (postv[u] <= postv[v])
                    return 1;
            }
        }
        return 0;
    }

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

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

        for (int n : adj.get(v)) {
            if (!visited.contains(n))
                explore(adj, n, visited, prev, postv, clock);
        }
        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<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>();
        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);
        }
        System.out.println(acyclic(adj));
    }
}