-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathMinRouterPeripherality.java
More file actions
58 lines (52 loc) · 1.23 KB
/
MinRouterPeripherality.java
File metadata and controls
58 lines (52 loc) · 1.23 KB
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
import java.util.Arrays;
public class MinRouterPeripherality {
public int solution(int[] T) {
int N = T.length;
int[] degrees = new int[N];
for (int current = 0; current < N; current++) {
int parent = T[current];
if (parent != current) {
degrees[parent]++;
}
}
int[] orders = new int[N];
int orderIndex = 0;
for (int i = 0; i < N; i++) {
if (degrees[i] == 0) {
orders[orderIndex] = i;
orderIndex++;
}
}
for (int i = 0; i < N - 1; i++) {
int current = orders[i];
int parent = T[current];
degrees[parent]--;
if (degrees[parent] == 0) {
orders[orderIndex] = parent;
orderIndex++;
}
}
long[] pathLens = new long[N];
int[] sizes = new int[N];
Arrays.fill(sizes, 1);
for (int i = 0; i < N - 1; i++) {
int current = orders[i];
int parent = T[current];
sizes[parent] += sizes[current];
pathLens[parent] += pathLens[current] + sizes[current];
}
for (int i = N - 2; i >= 0; i--) {
int current = orders[i];
int parent = T[current];
pathLens[current] = pathLens[parent] - sizes[current]
+ (N - sizes[current]);
}
int result = 0;
for (int i = 1; i < N; i++) {
if (pathLens[i] < pathLens[result]) {
result = i;
}
}
return result;
}
}