#K80372. Merge Accounts Based on Email Addresses

    ID: 35516 Type: Default 1000ms 256MiB

Merge Accounts Based on Email Addresses

Merge Accounts Based on Email Addresses

You are given a list of accounts. Each account is represented as a line with a user name followed by one or more email addresses. Two accounts are considered to belong to the same person if there is at least one common email address between them. Your task is to merge such accounts and output the merged accounts.

For each merged account, the first element should be the account name and the remaining elements should be the unique email addresses in lexicographical order.

Note: Two accounts with the same name may belong to different people if they do not share any common email address.

The connection between emails can be modeled as a graph. In fact, if we consider each email as a node and add an edge between emails appearing in the same account, then the problem reduces to finding the connected components of a graph. Mathematically, if we denote the set of emails of account i as \(E_i\) and account j as \(E_j\), then accounts i and j should be merged if \(E_i \cap E_j \neq \varnothing\).

inputFormat

The input is read from standard input (stdin) and has the following format:

N
account_1
account_2
...
account_N

Here, the first line contains a single integer N indicating the number of accounts. Each of the following N lines represents one account. Each account line starts with the account name (a non‐empty string without spaces) followed by one or more email addresses separated by spaces.

For example:

4
John johnsmith@mail.com john00@mail.com
John johnnybravo@mail.com
John johnsmith@mail.com john_newyork@mail.com
Mary mary@mail.com

outputFormat

For each merged account, output a line containing the account name followed by the sorted unique email addresses (in lexicographical order), separated by spaces. The merged accounts should be sorted primarily by the account name and then lexicographically by the list of emails.

For example, the output for the sample input would be:

John john00@mail.com john_newyork@mail.com johnsmith@mail.com
John johnnybravo@mail.com
Mary mary@mail.com
## sample
1
John johnsmith@mail.com john00@mail.com
John john00@mail.com johnsmith@mail.com

</p>