forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
83 lines (63 loc) · 1.54 KB
/
main2.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/// Source : https://leetcode.com/problems/minimize-malware-spread/description/
/// Author : liuyubobobo
/// Time : 2018-10-16
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
/// Using Union-Find
/// Time Complexity: O(n^2)
/// Space Complexity: O(n)
class UF{
private:
vector<int> parent, sz;
public:
UF(int n){
parent.clear();
for(int i = 0 ; i < n ; i ++){
parent.push_back(i);
sz.push_back(1);
}
}
int find(int p){
if( p != parent[p] )
parent[p] = find( parent[p] );
return parent[p];
}
bool isConnected(int p , int q){
return find(p) == find(q);
}
void unionElements(int p, int q){
int pRoot = find(p);
int qRoot = find(q);
if( pRoot == qRoot )
return;
parent[pRoot] = qRoot;
sz[qRoot] += sz[pRoot];
}
int size(int p){
return sz[find(p)];
}
};
class Solution {
public:
int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {
int n = graph.size();
UF uf(n);
for(int i = 0; i < n; i ++)
for(int j = i + 1; j < n; j ++)
if(graph[i][j])
uf.unionElements(i, j);
sort(initial.begin(), initial.end());
int best = 0, res = -1;
for(int v: initial)
if(uf.size(v) > best){
best = uf.size(v);
res = v;
}
return res;
}
};
int main() {
return 0;
}