-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathMinimize Malware Spread II.cpp
54 lines (44 loc) · 1.52 KB
/
Minimize Malware Spread II.cpp
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
class Solution {
public:
int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {
sort(initial.begin(), initial.end());
int ans = -1, mn = INT_MAX, n = graph.size();
vector<vector<int>> new_graph(n);
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
if(graph[i][j])
new_graph[i].push_back(j);
for(auto &k : initial)
{
vector<int> dsu(n, -1);
for(int i = 0; i < n; i++)
for(auto &j : new_graph[i])
if(i != k && j != k)
{
int a = findParent(dsu, i), b = findParent(dsu, j);
if(a != b)
dsu[b] += dsu[a], dsu[a] = b;
}
vector<int> infected(n, 0);
for(auto &i : initial)
if(i != k)
infected[findParent(dsu, i)]++;
int total_infected = 0;
for(int i = 0; i < n; i++)
if(infected[i])
total_infected += abs(dsu[i]);
if(total_infected < mn)
mn = total_infected, ans = k;
}
return ans == -1 ? initial[0] : ans;
}
int findParent(vector<int> &dsu, int i)
{
int a = i;
while(dsu[i] >= 0)
i = dsu[i];
if(i != a)
dsu[a] = i;
return i;
}
};