|
| 1 | +// Time: O(n^3) |
| 2 | +// Space: O(n) |
| 3 | + |
| 4 | +class Solution { |
| 5 | +public: |
| 6 | + int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) { |
| 7 | + unordered_set<int> initial_set(initial.cbegin(), initial.cend()); |
| 8 | + UnionFind union_find(graph.size()); |
| 9 | + for (int i = 0; i < graph.size(); ++i) { |
| 10 | + if (initial_set.count(i)) { |
| 11 | + continue; |
| 12 | + } |
| 13 | + for (int j = i + 1; j < graph.size(); ++j) { |
| 14 | + if (initial_set.count(j)) { |
| 15 | + continue; |
| 16 | + } |
| 17 | + if (graph[i][j] == 1) { |
| 18 | + union_find.union_set(i, j); |
| 19 | + } |
| 20 | + } |
| 21 | + } |
| 22 | + unordered_map<int, int> union_size; |
| 23 | + for (int i = 0; i < graph.size(); ++i) { |
| 24 | + ++union_size[union_find.find_set(i)]; |
| 25 | + } |
| 26 | + int result = numeric_limits<int>::max(); |
| 27 | + int total = numeric_limits<int>::max(); |
| 28 | + for (const auto& remove: initial) { |
| 29 | + unordered_set<int> lookup; |
| 30 | + int curr = 0; |
| 31 | + for (const auto& i: initial) { |
| 32 | + if (i == remove) { |
| 33 | + continue; |
| 34 | + } |
| 35 | + for (int j = 0; j < graph.size(); ++j) { |
| 36 | + if (initial_set.count(j)) { |
| 37 | + continue; |
| 38 | + } |
| 39 | + if (graph[i][j] == 1) { |
| 40 | + auto x = union_find.find_set(j); |
| 41 | + if (!lookup.count(x)) { |
| 42 | + curr += union_size[x]; |
| 43 | + lookup.emplace(x); |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + if (curr < total || |
| 49 | + (curr == total && remove < result)) { |
| 50 | + total = curr; |
| 51 | + result = remove; |
| 52 | + } |
| 53 | + } |
| 54 | + return result; |
| 55 | + } |
| 56 | + |
| 57 | +private: |
| 58 | + class UnionFind { |
| 59 | + public: |
| 60 | + UnionFind(const int n) : set_(n) { |
| 61 | + iota(set_.begin(), set_.end(), 0); |
| 62 | + } |
| 63 | + |
| 64 | + int find_set(const int x) { |
| 65 | + if (set_[x] != x) { |
| 66 | + set_[x] = find_set(set_[x]); // Path compression. |
| 67 | + } |
| 68 | + return set_[x]; |
| 69 | + } |
| 70 | + |
| 71 | + bool union_set(const int x, const int y) { |
| 72 | + int x_root = find_set(x), y_root = find_set(y); |
| 73 | + if (x_root == y_root) { |
| 74 | + return false; |
| 75 | + } |
| 76 | + set_[min(x_root, y_root)] = max(x_root, y_root); |
| 77 | + return true; |
| 78 | + } |
| 79 | + |
| 80 | + private: |
| 81 | + vector<int> set_; |
| 82 | + }; |
| 83 | +}; |
0 commit comments