-
Notifications
You must be signed in to change notification settings - Fork 0
/
DuduServiceMaker.java
80 lines (75 loc) · 2.08 KB
/
DuduServiceMaker.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
/**
* https://www.urionlinejudge.com.br/judge/en/problems/view/1610 #dfs
*
* <p>X<-------T | ^ | | | | v | Y -----> Z
*
* <p>X / \ T Y \ Z
*
* <p>visited status: T = processing
*
* <p>T = processed
*
* <p>false: - unprocess 0 -- iterate (visited[false]) true: -- processing 1 -- cycle \- processed 2
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class DuduServiceMaker {
static boolean DFSRecursion(
int vertex, HashMap<Integer, ArrayList<Integer>> graphMap, int[] statusArr) {
// processing
statusArr[vertex] = 1;
if (graphMap.containsKey(vertex)) {
for (int node : graphMap.get(vertex)) {
// unproccess
if (statusArr[node] == 0) {
if (DFSRecursion(node, graphMap, statusArr)) {
return true;
}
} else if (statusArr[node] == 1) {
return true;
}
}
}
// processed
statusArr[vertex] = 2;
return false;
}
static boolean isValid(HashMap<Integer, ArrayList<Integer>> graphMap, int nodeNum) {
int[] statusArr = new int[nodeNum];
for (Map.Entry<Integer, ArrayList<Integer>> entry : graphMap.entrySet()) {
int key = entry.getKey();
if (statusArr[key] == 0) {
if (DFSRecursion(key, graphMap, statusArr)) {
return true;
}
}
}
return false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
ArrayList<String> result = new ArrayList<>();
for (int i = 0; i < t; i ) {
int n = sc.nextInt();
int m = sc.nextInt();
HashMap<Integer, ArrayList<Integer>> graphMap = new HashMap<>();
for (int x = 0; x < m; x ) {
int k = sc.nextInt();
int v = sc.nextInt();
if (!graphMap.containsKey(v)) {
graphMap.put(v, new ArrayList<>());
}
graphMap.get(v).add(k);
}
if (isValid(graphMap, n 1)) {
result.add("SIM");
} else {
result.add("NAO");
}
}
result.forEach(s -> System.out.println(s));
}
}