-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClassmates2.java
87 lines (65 loc) · 2.13 KB
/
Classmates2.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
81
82
83
84
85
86
87
import java.util.stream.*;
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Classmates2
{
static Map<Integer, Integer> managers;
static Map<Integer, Set<Integer>> table;
protected static void changeRoot(int newRoot) {
while (managers.containsKey(newRoot)) {
int m = managers.get(newRoot);
if (!table.containsKey(newRoot)) {
table.put(newRoot, new HashSet<>());
}
table.get(m).remove(newRoot);
table.get(newRoot).add(m);
newRoot = m;
}
}
protected static int calc(int root)
{
int offt = 1;
if (!table.containsKey(root))
return 0;
List<Integer> sortedSublings =
table.get(root).stream()
.map( e -> calc(e) )
.sorted()
.collect(Collectors.toList());
int result=0;
for (int i = sortedSublings.size() - 1; i >= 0; i--) {
int rc = sortedSublings.get(i) + offt;
offt++;
if (rc > result) {
result = rc;
}
}
return result;
}
public static void main(String[] argv) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int employees = in.nextInt();
managers = new HashMap<>();
int manager = 0;
table = new HashMap<>();
while(manager < employees) {
int nextSubordinate = in.nextInt();
if (nextSubordinate > 0) {
if (!table.containsKey(manager)) {
table.put(manager, new HashSet<>());
}
table.get(manager).add(nextSubordinate-1);
managers.put(nextSubordinate-1, manager);
}
else {
manager++;
}
}
int tanya = in.nextInt();
tanya--;
changeRoot(tanya);
System.out.println(""+calc(tanya));
}
}