Merging Customer Accounts
Your CRM exported n account records. Each record has a display name and the list of email
addresses that were used to sign into it. Over the years the same customer has sometimes created
several separate accounts — the system has no customer ID, but any two accounts that were ever
used with the same email address definitely belong to the same person. This relation is
transitive: if account A shares an email with account B, and account B shares a (possibly
different) email with account C, then A, B and C are all the same person.
Display names are not reliable: two different customers can happen to share a display name, so names must never be used to decide a merge, only shared emails can.
Merge the n records into one record per real customer, and for each customer print their name
together with the sorted set of every distinct email address that appeared on any of their
accounts.
It is guaranteed that whenever two input accounts end up merged into the same customer, both were recorded with the exact same display name string, so the merged customer's name is unambiguous.
Input
The first line contains an integer n (1 ≤ n ≤ 10^5) — the number of account records.
Each of the next n lines describes one account in the form:
name k email_1 email_2 ... email_k
nameis 1 to 20 English letters (A-Z,a-z), case-sensitive, with no spaces.k(1 ≤k≤ 20) is the number of emails on this account.- each
email_iis 1 to 50 characters from lowercase letters, digits,.,_and@, with no spaces. The same email may repeat more than once on the same account.
The total number of emails listed across all accounts (counting repeats) is at most 2·10^5.
Output
Print one line per merged customer. Each line must contain the customer's name followed by every distinct email address that ever appeared on one of their accounts, sorted ascending by ASCII value, all separated by single spaces.
Order the customers' lines by the smallest email address in their line, ascending by ASCII value.
Notes
In the first example, the first two accounts share both [email protected] and
[email protected], so they merge into one customer with three emails. The last account also has
the name John but shares no email with anyone else, so it stays separate and is printed as its
own customer.
The second example shows that a shared display name never causes a merge: Alice's two accounts
have disjoint emails and stay separate, and the ordering of lines is driven purely by the smallest
email on each line, not by name.