-
Notifications
You must be signed in to change notification settings - Fork 0
/
Account Merge.cpp
88 lines (76 loc) · 1.92 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
83
84
85
86
87
88
class DisjointSetSize{
vector<int> size;
vector<int> parent;
public:
DisjointSetSize(int n)
{
size.resize(n+1,0);
parent.resize(n+1,0);
for(int i=0;i<=n;i++)
{
parent[i]=i;
size[i]=1;
}
}
int findUPar(int node)
{
if(node==parent[node])
return node;
return parent[node]=findUPar(parent[node]);
}
void unionBySize(int u,int v)
{
int ulp_u=findUPar(u);
int ulp_v=findUPar(v);
if(ulp_u==ulp_v)
return ;
if(size[ulp_u]<size[ulp_v])
{
parent[ulp_u]=ulp_v;
size[ulp_v]+=size[ulp_u];
}
else
{
parent[ulp_v]=ulp_u;
size[ulp_u]+=size[ulp_v];
}
}
};
class Solution{
public:
vector<vector<string>> accountsMerge(vector<vector<string>> &accounts) {
int n=accounts.size();
DisjointSetSize ds(n);
unordered_map<string,int> mp;
for(int i=0;i<n;i++)
{
for(int j=1;j<accounts[i].size();j++)
{
string s=accounts[i][j];
if(mp.count(s))
{
int p1=mp[s];
int p2=i;
ds.unionBySize(p1,p2);
}
else
mp[s]=i;
}
}
unordered_map<int,vector<string>> mp2;
for(auto it:mp)
{
int p1=ds.findUPar(it.second);
mp2[p1].push_back(it.first);
}
vector<vector<string>> ans;
for(auto& it:mp2)
{
sort(it.second.begin(),it.second.end());
int ind=mp[it.second[0]];
it.second.insert(it.second.begin(),accounts[ind][0]);
ans.push_back(it.second);
}
return ans;
}
};