Hdu3172 - Virtual Friends - 并查集

来源:互联网 发布:曲面软件 编辑:程序博客网 时间:2024/05/19 23:04
#include<map>  #include<stdio.h>  #include<string>  using namespace std;  #define N 30#define M 100005  int n;  int p[M];  int t[M];  map<string,int>Map;  int find(int x){  if(p[x]!= x){  int fa=p[x];  p[x]=find(fa);  t[x]+=t[fa];  }  return p[x];  }  void h(int x , int y){  int fx=find(x);  int fy=find(y);  if(fx!=fy){  p[fx]=fy;  t[fy]+=t[fx];  }  printf("%d\n",t[fy]);  }  int main(){   int x,y,m,tot;  char str[N];  while(scanf("%d",&m)!=EOF){  while(m--){  scanf("%d",&n);   Map.clear();  for(int i=0;i<M;i++){  p[i]=i;  t[i]=1;  }  tot=1;  while(n--){  scanf("%s",str);   if(Map.find(str)==Map.end()) {Map[str]=tot++;}x=Map[str];  scanf("%s",str);   if(Map.find(str)==Map.end())  {Map[str]=tot++;}y=Map[str];  h(x,y);  }  }  }  return 0;  }  

0 0