-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.go
65 lines (63 loc) · 1.1 KB
/
Solution.go
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
func minMalwareSpread(graph [][]int, initial []int) int {
n := len(graph)
p := make([]int, n)
size := make([]int, n)
clean := make([]bool, n)
for i := 0; i < n; i++ {
p[i], size[i], clean[i] = i, 1, true
}
for _, i := range initial {
clean[i] = false
}
var find func(x int) int
find = func(x int) int {
if p[x] != x {
p[x] = find(p[x])
}
return p[x]
}
union := func(a, b int) {
pa, pb := find(a), find(b)
if pa != pb {
size[pb] += size[pa]
p[pa] = pb
}
}
for i := 0; i < n; i++ {
if !clean[i] {
continue
}
for j := i + 1; j < n; j++ {
if clean[j] && graph[i][j] == 1 {
union(i, j)
}
}
}
cnt := make([]int, n)
mp := make(map[int]map[int]bool)
for _, i := range initial {
s := make(map[int]bool)
for j := 0; j < n; j++ {
if clean[j] && graph[i][j] == 1 {
s[find(j)] = true
}
}
for root, _ := range s {
cnt[root]++
}
mp[i] = s
}
mx, ans := -1, 0
for i, s := range mp {
t := 0
for root, _ := range s {
if cnt[root] == 1 {
t += size[root]
}
}
if mx < t || (mx == t && i < ans) {
mx, ans = t, i
}
}
return ans
}