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

描述

You are given a list of usernames and their email addresses in the following format:

alice 2 [email protected] [email protected]
bob 1 [email protected]
alicebest 2 [email protected] [email protected]
alice2016 1 [email protected]

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 [email protected] [email protected]
bob 1 [email protected]
alicebest 2 [email protected] [email protected]
alice2016 1 [email protected] 
樣例輸出
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;
}


發佈了81 篇原創文章 · 獲贊 0 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章