Minimize Malware Spread II

https://leetcode.com/problems/minimize-malware-spread-ii/

(This problem is the same as Minimize Malware Spread, with the differences bolded.)

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, completely removing it and any connections from this node to any other node. 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.

Example 1:

Input: graph = [[1,1,0],[1,1,0],[0,0,1]], initial = [0,1]

Output: 0

Example 2:

Input: graph = [[1,1,0],[1,1,1],[0,1,1]], initial = [0,1]

Output: 1

Example 3:

Input: graph = [[1,1,0,0],[1,1,1,0],[0,1,1,1],[0,0,1,1]], initial = [0,1]

Output: 1

Note:

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

Thoughts

和1的区别在于移除某点后会连着边一并移除,这样感染的话当中间连接的结点被移除时,则不会再感染原同一component中剩余节点。比如0-1-2时一个component, 题1中[0,1]无论移除哪个2都会被感染,但这里移除了1之后只感染0不会再感染到2.

暴力法,以此删除每个candidate malware,算最后能有多少被感染的。

Code

class Solution {
public:
    int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {
        const auto n = graph.size();
        pair<int, int> res = {INT_MAX, 0};
        for (int ini : initial) {
            parents.clear();
            for (int i = 0; i < n; ++i) parents.push_back(i);
            for (int i = 0; i < n; ++i)
                for (int j = i + 1; j < n; ++j)
                    if (graph[i][j] && i != ini && j != ini) un(i, j);
            vector<int> size(n, 0);
            for (int i = 0; i < n; ++i) size[find(i)]++;
            int count = 0;
            unordered_set<int> visited;
            for (int i : initial) {
                if (i != ini) {
                    int a = find(i);
                    if (visited.find(a) == visited.end()) {
                        visited.insert(a);
                        count += size[a];
                    }
                }
            }
            res = min(res, {count, ini});
        }
        return res.second;
    }

private:
    vector<int> parents;
    int find(int x) {
        if (x != parents[x])
            parents[x] = find(parents[x]);
        return parents[x];
    }

    void un(int x, int y) {
        x = find(x), y = find(y);
        if (x != y) {
            parents[x] = y;
        }
    }
};

Last updated