题目描述:
In a network of nodes, each node i is directly connected to another node j if and only if graph[i][j] = 1.
Some nodes initial are initially infected by malware. Whenever two nodes are directly connected and at least one of those two nodes is infected by malware, both nodes will be infected by malware. This spread of malware will continue until no more nodes can be infected in this manner.
Suppose M(initial) is the final number of nodes infected with malware in the entire network, after the spread of malware stops.
We will remove one node from the initial list. Return the node that if removed, would minimize M(initial). If multiple nodes could be removed to minimize M(initial), return such a node with the smallest index.
Note that if a node was removed from the initial list of infected nodes, it may still be infected later as a result of the malware spread.
Example 1:
Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]
Output: 0
Example 2:
Input: graph = [[1,0,0],[0,1,0],[0,0,1]], initial = [0,2]
Output: 0
Example 3:
Input: graph = [[1,1,1],[1,1,1],[1,1,1]], initial = [1,2]
Output: 1
Note:
1. 1 < graph.length = graph[0].length <= 300
2. 0 <= graph[i][j] == graph[j][i] <= 1
3. graph[i][i] = 1
4. 1 <= initial.length < graph.length
5. 0 <= initial[i] < graph.length
class Solution {
public:
int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {
int result=INT_MAX;
for(auto x:initial)
result=min(result,x); //将result初始化为initial中的最小值
int n=graph.size();
for(int i=0;i<n;i++) parent[i]=i;
for(int i=0;i<n;i++)
for(int j=0;j<i;j++) //用j<i而不是j<n可以降低时间复杂度
if(graph[i][j]==1) uni(i,j);
unordered_map<int,int> node_count; //根节点对应的所有子节点数
unordered_map<int,int> ini_count; //根节点对应的所有被感染的子节点数
for(int i=0;i<n;i++) node_count[find(i)]++;
for(auto i:initial) ini_count[find(i)]++;
int max_size=0;
for(auto x:initial) //遍历initial,是为了减少时间复杂度,因为可能节点很多,但是感染节点很少
{ //ini_set中只存在一个被恶意软件感染的节点,将这个节点删除,整个node_set都可以恢复
int root=find(x);
if(ini_count[root]==1)
{
if(node_count[root]==max_size) result=min(result,x);
else if(node_count[root]>max_size) //node_set中节点越多,越能减少被感染的节点
{
result=x;
max_size=node_count[root];
}
}
}
return result;
}
int find(int x)
{
if(parent[x]==x) return x;
else return find(parent[x]);
}
void uni(int a, int b)
{
int x=find(a);
int y=find(b);
parent[x]=y;
}
private:
unordered_map<int,int> parent;
};
3978



被折叠的 条评论
为什么被折叠?



