forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Update 924.Minimize-Malware-Spread.cpp
- Loading branch information
1 parent
044c016
commit bb8b9f8
Showing
1 changed file
with
69 additions
and
1 deletion.
There are no files selected for viewing
70 changes: 69 additions & 1 deletion
70
Union_Find/924.Minimize-Malware-Spread/924.Minimize-Malware-Spread.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,69 @@ | ||
|
||
class Solution { | ||
unordered_map<int,int>Root; | ||
public: | ||
int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) | ||
{ | ||
int N = graph.size(); | ||
for (int i=0; i<N; i++) | ||
Root[i] = i; | ||
for (int i=0; i<N; i++) | ||
for (int j=0; j<N; j++) | ||
{ | ||
if (i==j) continue; | ||
if (graph[i][j]==0) continue; | ||
if (findRoot(i)!=findRoot(j)) | ||
Union(i,j); | ||
} | ||
|
||
unordered_map<int,vector<int>>Children; | ||
for (int i=0; i<N; i++) | ||
{ | ||
Root[i] = findRoot(i); | ||
Children[Root[i]].push_back(i); | ||
} | ||
|
||
set<int>Set(initial.begin(),initial.end()); | ||
|
||
int MaxGroup = 0; | ||
int result; | ||
for (auto a:Children) | ||
{ | ||
int count = 0; | ||
int candidate; | ||
for (auto b:a.second) | ||
{ | ||
if (Set.find(b)!=Set.end()) | ||
{ | ||
count++; | ||
candidate = b; | ||
} | ||
if (count>1) break; | ||
} | ||
if (count==1 && (a.second.size()>MaxGroup || a.second.size()==MaxGroup && candidate<result)) | ||
{ | ||
MaxGroup = a.second.size(); | ||
result = candidate; | ||
} | ||
} | ||
|
||
if (MaxGroup!=0) return result; | ||
else return *Set.begin(); | ||
} | ||
|
||
int findRoot(int x) | ||
{ | ||
if (Root[x]!=x) | ||
Root[x] = findRoot(Root[x]); | ||
return Root[x]; | ||
} | ||
|
||
void Union(int x, int y) | ||
{ | ||
x = Root[x]; | ||
y = Root[y]; | ||
if (x<y) | ||
Root[y] = x; | ||
else | ||
Root[x] = y; | ||
} | ||
}; |