using
System;
using
System.Collections.Generic;
using
System.Linq;
public
class
GFG {
static
int
Find(List<
int
> unionFind,
int
ind)
{
while
(unionFind[ind] != ind)
ind = unionFind[ind];
return
ind;
}
static
List<List<
string
> >
MergeDetails(List<List<
string
> > accounts)
{
Dictionary<
string
,
int
> emailToAccountIndex
=
new
Dictionary<
string
,
int
>();
List<
int
> unionFind
= Enumerable.Range(0, accounts.Count).ToList();
Dictionary<
int
, List<
string
> > resultMap
=
new
Dictionary<
int
, List<
string
> >();
for
(
int
i = 0; i < accounts.Count; i++) {
for
(
int
j = 1; j < accounts[i].Count; j++) {
if
(emailToAccountIndex.ContainsKey(
accounts[i][j])) {
int
root1 = Find(unionFind, i);
int
root2 = Find(
unionFind,
emailToAccountIndex[accounts[i]
[j]]);
unionFind[root1] = root2;
}
else
emailToAccountIndex[accounts[i][j]]
= unionFind[i];
}
}
foreach
(
var
entry
in
emailToAccountIndex)
{
int
ind = Find(unionFind, entry.Value);
if
(!resultMap.ContainsKey(ind))
resultMap[ind] =
new
List<
string
>();
resultMap[ind].Add(entry.Key);
}
List<List<
string
> > result
=
new
List<List<
string
> >();
foreach
(
var
entry
in
resultMap)
{
List<
string
> email = entry.Value;
email.Sort();
email.Insert(0, accounts[entry.Key][0]);
result.Add(email);
}
return
result;
}
public
static
void
Main(
string
[] args)
{
List<List<
string
> > details
=
new
List<List<
string
> >{
new
List<
string
>{
"John"
,
"johnsmith@mail.com"
,
"john_newyork@mail.com"
},
new
List<
string
>{
"John"
,
"johnsmith@mail.com"
,
"john00@mail.com"
},
new
List<
string
>{
"Mary"
,
"mary@mail.com"
},
new
List<
string
>{
"John"
,
"johnnybravo@mail.com"
}
};
List<List<
string
> > result = MergeDetails(details);
foreach
(
var
detail
in
result)
{
foreach
(
var
item
in
detail)
{
Console.Write(item +
" "
);
}
Console.WriteLine();
}
}
}