HDU - 3172Virtual Friends(带权并查集--权为集合元素个数)

蹉跎莫遣韶光老,人生唯有读书好。这篇文章主要讲述HDU - 3172Virtual Friends(带权并查集--权为集合元素个数)相关的知识,希望能为你提供帮助。
题干:
These days, you can do all sorts of things online. For example, you can use various websites to make virtual friends. For some people, growing their social network (their friends, their friends friends, their friends friends friends, and so on), has become an addictive hobby. Just as some people collect stamps, other people collect virtual friends. 

Your task is to observe the interactions on such a website and keep track of the size of each persons network. 

Assume that every friendship is mutual. If Fred is Barneys friend, then Barney is also Freds friend.
Input
Input file contains multiple test cases. 
The first line of each case indicates the number of test friendship nest. 
each friendship nest begins with a line containing an integer F, the number of friendships formed in this frindship nest, which is no more than 100 000. Each of the following F lines contains the names of two people who have just become friends, separated by a space. A name is a string of 1 to 20 letters (uppercase or lowercase).
Output
Whenever a friendship is formed, print a line containing one integer, the number of people in the social network of the two people who have just become friends.
Sample Input

1
3
Fred Barney
Barney Betty
Betty Wilma

Sample Output
2
3
4

题目大意:
有多个测试组T,每个测试组第一行n,接下来n行表示甲与乙认识,每给出一个关系,求出一共有多少个朋友。朋友的朋友也是朋友。
解题报告 :
先用map映射一下每个字符串对应一个序号(因为不然的话不好放到f数组num数组 的下标上)然后查询祖先节点那个集合的元素个数。
AC代码:
#include< iostream>
#include< cstdio>
#include< algorithm>
#include< map>
#include< string>

using namespace std;
int n,m;
char s1[50],s2[50];
int f[200000 + 5];
int num[200000 + 5];
map< string , int> mp;

int getf(int v)
return v==f[v]?v:f[v]=getf(f[v]);

void merge(int u,int v)
int t1=getf(u);
int t2=getf(v);
if(t1!=t2)
f[t2]=t1;
num[t1]+=num[t2]; //别写成t2了。。。。


void init()
for(int i = 1; i< =200000 + 5; i++)
f[i]=i;
num[i]=1;


int main()

int top;
while(~scanf("%d",& n) )
while(n--)
mp.clear();
top = 0;
init();
scanf("%d",& m);
while(m--)
scanf("%s",s1);
scanf("%s",s2);
if(mp.find(s1) == mp.end() ) mp[s1] = ++top;
if(mp.find(s2) == mp.end() ) mp[s2] = ++top;
merge(mp[s1],mp[s2]);
printf("%d\\n",num[ getf( mp[s1] ) ] );

//一共top个人


return 0 ;

总结:
    无。
 
【HDU - 3172Virtual Friends(带权并查集--权为集合元素个数)】


    推荐阅读