759 字
4 分钟
Day 77 924. 尽量减少恶意软件的传播

924. 尽量减少恶意软件的传播#

题目#

在节点网络中,只有当 graph[i][j] = 1 时,每个节点 i 能够直接连接到另一个节点 j。
一些节点 initial 最初被恶意软件感染。
只要两个节点直接连接,且其中至少一个节点受到恶意软件的感染,那么两个节点都将被恶意软件感染。
这种恶意软件的传播将继续,直到没有更多的节点可以被这种方式感染。
假设 M(initial) 是在恶意软件停止传播之后,整个网络中感染恶意软件的最终节点数。
如果从初始列表中移除某一节点能够最小化 M(initial),
返回该节点。如果有多个节点满足条件,就返回索引最小的节点。
请注意,如果某个节点已从受感染节点的列表 initial 中删除,
它以后可能仍然因恶意软件传播而受到感染。
示例 1
输入:graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
输出:0
示例 2
输入:graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]
输出:0
示例 3
输入:graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]
输出:1
提示:
1 < graph.length = graph[0].length <= 300
0 <= graph[i][j] == graph[j][i] <= 1
graph[i][i] == 1
1 <= initial.length < graph.length
0 <= initial[i] < graph.length

题目思路#

这道题有些小难。首先要计算图中每个连通分量块的大小,然后统计 initial 表中每个节点所在连通分量块的大小。当某个连通分量块只含一个 initial 节点时,删除该节点即可使整个块免于感染,找到满足条件的最大连通块并返回对应节点,块大小相等时返回索引最小的节点;如果不存在这样的连通分量块,则返回 initial 中的最小值。

题目代码#

class UnionFind {
public:
vector<int> data;
vector<int> cnt; // 每个节点连通块大小
void init(int n) {
data.resize(n, 0);
for(int i = 0; i < n; i++) {
data[i] = i;
}
cnt.resize(n, 1);
}
int find(int x) {
/* int root = x;
while (data[root] >= 0) root = data[root];
//路径压缩
while (x != root) {
int tmp = data[x]; //tmp 指向 x 的父节点
data[x] = root; //挂到根节点下
x = tmp;
}
return root; //返回根节点的编号。 */
//上述的优化会超时!
if(data[x] != x) {
return find(data[x]);
} else {
return x;
}
}
void Union(int x, int y) {
int p = find(x);
int q = find(y);
data[p] = q;
if (p != q) {
cnt[q] += cnt[p];
}
}
int GetCnt(int x) {
return cnt[find(x)];
}
};
class Solution {
public:
int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {
UnionFind u;
int n = graph.size(), m = graph[0].size();
u.init(n);
sort(initial.begin(), initial.end());
for(int i = 0; i < n; i++) {
for (int j = i + 1; j < m; j++) {
if (graph[i][j] == 1) u.Union(i, j);
}
}
// 计算initial中共连通块元素个数
map<int, int> count;
for (auto c : initial) {
count[u.find(c)]++;
}
int ans = -1;
int res = -1;
for (auto c : initial) {
if (count[u.find(c)] == 1) {
int size = u.GetCnt(c);
if (size > res) {
res = size;
ans = c;
}
}
}
if (ans == -1) return initial[0];
return ans;
}
};

复杂度#

  • 时间复杂度:O(n2n^2)
  • 空间复杂度:O(n)
Day 77 924. 尽量减少恶意软件的传播
https://chaggle.github.io/posts/2021/11/25/day-77-924-minimize-malware-spread/
作者
chaggle
发布于
2021-11-25
许可协议
CC BY-NC-SA 4.0