-
Notifications
You must be signed in to change notification settings - Fork 1
/
Account Merge.cpp
82 lines (78 loc) · 2.23 KB
/
Account Merge.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
class DisjointSet{
public:
DisjointSet() = delete;
DisjointSet(int n){
rank.resize(n+1, 0); //N+1 because graph might be 1 based indexing
parent.resize(n+1);
size.resize(n+1, 1);
std::iota(begin(parent), end(parent), 0);
}
int getUlParent(int node){ //get ultimate parent
if(node == parent[node]){
return node;
}else{
return parent[node] = getUlParent(parent[node]);
}
}
void unionByRank(int u, int v){
int ulp_u = getUlParent(u);
int ulp_v = getUlParent(v);
if(ulp_u == ulp_v){
return;
}
if(rank[ulp_u] < rank[ulp_v]){
parent[ulp_u] = ulp_v;
}else if(rank[ulp_v] < rank[ulp_u]){
parent[ulp_v] = ulp_u;
}else{
parent[ulp_u] = ulp_v;
rank[ulp_u]++;
}
}
void unionBySize(int u, int v){
int ulp_u = getUlParent(u);
int ulp_v = getUlParent(v);
if(ulp_u == ulp_v){
return;
}
if(rank[ulp_u] < rank[ulp_v]){
parent[ulp_u] = ulp_v;
size[ulp_u] += size[ulp_v];
}else{
parent[ulp_v] = ulp_u;
size[ulp_v] += size[ulp_u];
}
}
private:
vector<int> rank, parent, size;
};
class Solution{
public:
vector<vector<string>> accountsMerge(vector<vector<string>> &accounts) {
int n = accounts.size(), i, j;
DisjointSet dsj(n+1);
unordered_map<string, int> mp;
vector<vector<string>> res;
for(i = 0;i<n;i++){
for(j = 1;j<accounts[i].size();j++){
if(!mp[accounts[i][j]]){
mp[std::move(accounts[i][j])] = i+1;
}else{
dsj.unionByRank(mp[accounts[i][j]], i+1);
}
}
}
vector<string> adj[n+1];
for(auto itr{begin(mp)}; itr != end(mp); ++itr){
adj[dsj.getUlParent(itr->second)].push_back(std::move(string(itr->first)));
}
for(i = 1;i<=n;i++){
if(adj[i].size()){
sort(adj[i].begin(), adj[i].end());
adj[i].insert(adj[i].begin(), std::move(accounts[i-1][0]));
res.push_back(std::move(adj[i]));
}
}
return res;
}
};