描述
You are given a list of usernames and their email addresses in the following format:
alice 2 alice@hihocoder.com alice@gmail.com
bob 1 bob@qq.com
alicebest 2 alice@gmail.com alice@qq.com
alice2016 1 alice@qq.com
Your task is to merge the usernames if they share common email address:
alice alicebest alice2016
bob
输入
The first lines contain an integer N, denoting the number of usernames. (1 < N ≤ 10000)
The following N lines contain N usernames and their emails in the previous mentioned format.
Each username may have 10 emails at most.
输出
Output one merged group per line.
In each group output the usernames in the same order as the input.
Output the groups in the same order as their first usernames appear in the input.
样例输入
4 alice 2 alice@hihocoder.com alice@gmail.com
bob 1 bob@qq.com
alicebest 2 alice@gmail.com alice@qq.com
alice2016 1 alice@qq.com
样例输出
alice alicebest alice2016
bob
描述
You are given a list of usernames and their email addresses in the following format:
alice 2 alice@hihocoder.com alice@gmail.com
bob 1 bob@qq.com
alicebest 2 alice@gmail.com alice@qq.com
alice2016 1 alice@qq.com
Your task is to merge the usernames if they share common email address:
alice alicebest alice2016
bob
输入
The first lines contain an integer N, denoting the number of usernames. (1 < N ≤ 10000)
The following N lines contain N usernames and their emails in the previous mentioned format.
Each username may have 10 emails at most.
输出
Output one merged group per line.
In each group output the usernames in the same order as the input.
Output the groups in the same order as their first usernames appear in the input.
4 alice 2 alice@hihocoder.com alice@gmail.com bob 1 bob@qq.com alicebest 2 alice@gmail.com alice@qq.com alice2016 1 alice@qq.com
alice alicebest alice2016 bob
#include<iostream>
#include<map>
#include<string>
#include<cstring>
#include<vector>
#include<algorithm>
#include<set>
#include<sstream>
#include<cstdio>
#include<unordered_map>
#include<unordered_set>
#include<cmath>
#include<climits>
using namespace std;
unordered_map<int,int> Father;
int findFather(int x) {
if(Father[x]!=x) Father[x]=findFather(Father[x]);
return Father[x];
}
void Union(int x,int y) {
int fx=findFather(x);
int fy=findFather(y);
if(fx!=fy) {
if(fy>fx) //小trick,按顺序输出name
Father[fy]=fx;
else Father[fx]=fy;
}
}
int main()
{
int n;
scanf("%d",&n);
getchar();
string name[10001];
unordered_map<string,vector<int>> Map;
for(int i=0;i<n;i++) {
cin>>name[i];
Father[i]=i;
int num;
scanf("%d",&num);
for(int j=0;j<num;j++) {
string email;
cin>>email;
int len=Map[email].size();
for(int k=0;k<len;k++) {
Union(Map[email][k],i);
}
Map[email].push_back(i);
}
}
map<int,vector<int>> path;
for(int i=0;i<n;i++) {
int fx=findFather(i);
path[fx].push_back(i);
}
map<int,vector<int>>::iterator it;
for(it=path.begin();it!=path.end();it++) {
vector<int> tmp=it->second;
cout<<name[tmp[0]];
for(int i=1;i<tmp.size();i++) {
cout<<" "<<name[tmp[i]];
}
cout<<endl;
}
return 0;
}