-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
75 lines (72 loc) · 1.92 KB
/
Solution.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
class Solution {
private int[] p;
private int[] size;
public int minMalwareSpread(int[][] graph, int[] initial) {
int n = graph.length;
p = new int[n];
size = new int[n];
for (int i = 0; i < n; ++i) {
p[i] = i;
size[i] = 1;
}
boolean[] clean = new boolean[n];
Arrays.fill(clean, true);
for (int i : initial) {
clean[i] = false;
}
for (int i = 0; i < n; ++i) {
if (!clean[i]) {
continue;
}
for (int j = i + 1; j < n; ++j) {
if (clean[j] && graph[i][j] == 1) {
union(i, j);
}
}
}
int[] cnt = new int[n];
Map<Integer, Set<Integer>> mp = new HashMap<>();
for (int i : initial) {
Set<Integer> s = new HashSet<>();
for (int j = 0; j < n; ++j) {
if (clean[j] && graph[i][j] == 1) {
s.add(find(j));
}
}
for (int root : s) {
cnt[root] += 1;
}
mp.put(i, s);
}
int mx = -1;
int ans = 0;
for (Map.Entry<Integer, Set<Integer>> entry : mp.entrySet()) {
int i = entry.getKey();
int t = 0;
for (int root : entry.getValue()) {
if (cnt[root] == 1) {
t += size[root];
}
}
if (mx < t || (mx == t && i < ans)) {
mx = t;
ans = i;
}
}
return ans;
}
private int find(int x) {
if (p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
private void union(int a, int b) {
int pa = find(a);
int pb = find(b);
if (pa != pb) {
size[pb] += size[pa];
p[pa] = pb;
}
}
}