码迷,mamicode.com
首页 > 其他好文 > 详细

HDU3172 Virtual Friends

时间:2020-02-13 22:48:22      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:amp   bsp   ios   void   pac   main   并查集   cin   map   

基础并查集~

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<unordered_map>
#include<iostream>
#include<string>
using namespace std;
const int maxn=1e6+14;
unordered_map<string,int> pos;
string s1,s2;
int father[maxn],cnt,N,num[maxn];
void init () {
    for (int i=0;i<maxn;i++) father[i]=i;
    fill (num,num+maxn,1);
    cnt=0;
    pos.clear();
}
int findfather (int x) {
    int a=x;
    while (x!=father[x]) x=father[x];
    while (a!=father[a]) {
        int z=a;
        a=father[a];
        father[z]=x;
    }
    return x;
} 
void Union (int a,int b) {
    int faA=findfather(a);
    int faB=findfather(b);
    if (faA!=faB) father[faA]=faB,num[faB]+=num[faA];
}
int main () {
    int T;
    while (~scanf("%d",&T)) {
        while (T--) {
            init ();
            scanf ("%d",&N);
            for (int i=0;i<N;i++) {
                cin>>s1>>s2;
                if (!pos[s1]) pos[s1]=++cnt;
                if (!pos[s2]) pos[s2]=++cnt;
                Union (pos[s1],pos[s2]); 
                printf ("%d\n",num[findfather(pos[s1])]);
            }
        }
    }
    return 0;
}

 

HDU3172 Virtual Friends

标签:amp   bsp   ios   void   pac   main   并查集   cin   map   

原文地址:https://www.cnblogs.com/zhanglichen/p/12305554.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!