[Hihocoder]1335 : Email Merge (并查集)

描述

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 

题解:并查集,注意题目中要求按Input顺序输出name
#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值