#Problem

#⭐️⭐️⭐️⭐️

给一个matrix表示Internet中connect的结点, graph[i][j] = 1表示server i和server j是connect的. 然后再给一个数组initial表示中毒的server.

问如果从initial中取掉一个server, 把这个server的病毒给清了, 那要清楚哪个server能使得最终Internet里被感染的结点数最少?

#Solution

Union-find

先把internet给union起来. 然后遍历一遍中毒的数组, 找包含中毒server的component, 哪个component size最大就给哪个server杀毒.

#Code

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
class Solution {
public int minMalwareSpread(int[][] graph, int[] initial) {
int n = graph.length;
int[] roots = new int[n];
int[] size = new int[n];
for (int i = 0; i < n; i++) {
roots[i] = i;
size[i] = 1;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i != j && graph[i][j] == 1) {
union(roots, size, i, j);
}
}
}
Arrays.sort(initial);
int infects = -1;
int res = -1;
for (int bad : initial) {
int currInfects = size[root(roots, bad)];
if (currInfects > infects) {
infects = currInfects;
res = bad;
}
}
return res;
}
private int root(int[] roots, int i) {
while (i != roots[i]) {
roots[i] = roots[roots[i]];
i = roots[i];
}
return i;
}
private void union(int[] roots, int[] size, int i, int j) {
int r1 = root(roots, i);
int r2 = root(roots, j);
if (size[r1] < size[r2]) {
roots[r1] = r2;
size[r2] += size[r1];
} else {
roots[r2] = r1;
size[r1] += size[r2];
}
}
}

Comments