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 person’s network.
Assume that every friendship is mutual. If Fred is Barney’s friend, then Barney is also Fred’s 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
题意:人与人之间交朋友,每次两个人建立朋友关系时,问这两个集合的人数有多少。
基础并查集,用姓名用map映射即可
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <math.h>
#include <string>
#include<map>
#define maxn 210000
using namespace std;
int pre[3*maxn];
int cnt[3*maxn];
map<string,int>s;
int findroot(int num)
{
int temp = num;
while(pre[num] != num)
{
num = pre[num];
}
while(pre[temp] != num)
{
int j = pre[temp];
pre[temp] = num;
temp = j;
}
return pre[num];
}
int main()
{
int t;
while(~scanf("%d",&t))
{
while(t--)
{
int n;
scanf("%d",&n);
for(int i = 1; i <= 3*n; i++)
{
pre[i] = i;
cnt[i] = 1;
}
int p = 1;
for(int i = 1; i <= n; i++)
{
string c1;
string c2;
cin>>c1;
cin>>c2;
if(s.count(c1) == 0)
{
s.insert(make_pair(c1,p++));
}
if(s.count(c2) == 0)
{
s.insert(make_pair(c2,p++));
}
int num1 = s[c1];
int num2 = s[c2];
int roota = findroot(num1);
int rootb = findroot(num2);
if(roota != rootb)
{
cnt[rootb] += cnt[roota];
pre[roota] = rootb;
printf("%d\n",cnt[rootb]);
}
else
{
printf("%d\n",cnt[roota]);
}
}
}
}
}