-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCthulhu.java
66 lines (62 loc) · 1.51 KB
/
Cthulhu.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
/** https://codeforces.com/problemset/problem/103/B #dfs #dsu */
import java.util.Scanner;
public class Cthulhu {
public static void makeSet(int[] parent, int[] size) {
int sz = parent.length;
for (int i = 0; i < sz; i++) {
parent[i] = i;
size[i] = 1;
}
}
public static int findSet(int u, int[] parent) {
if (parent[u] != u) {
parent[u] = findSet(parent[u], parent);
}
return parent[u];
}
public static boolean unionSet(int[] parent, int[] size, int u, int v, int[] cycle) {
int up = findSet(u, parent);
int vp = findSet(v, parent);
if (up == vp) {
return false;
}
if (size[up] > size[vp]) {
parent[vp] = up;
size[up] += size[vp];
} else if (size[up] < size[vp]) {
parent[up] = vp;
size[vp] += size[up];
} else {
parent[up] = vp;
size[vp] += size[up];
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int sz = n + 1;
int[] parent = new int[sz];
int[] size = new int[sz];
int[] cycle = new int[sz];
makeSet(parent, size);
// N == M
// > 1 -> 1
// N - 1
if (n != m) {
System.out.println("NO");
return;
}
int a, b, ans = n;
for (int i = 0; i < m; i++) {
a = sc.nextInt();
b = sc.nextInt();
if (unionSet(parent, size, a, b, cycle)) {
ans -= 1;
}
}
System.out.println(ans == 1 ? "FHTAGN!" : "NO");
return;
}
}