Virtual 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 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.

1
3
Fred Barney
Barney Betty
Betty Wilma

Sample Output

2
3
4

#include<iostream>
#include<cstdio>
#include<map>
#include<algorithm>
#include<vector>
#include<cstring>

using namespace std;
int n,f;

map<string,int>q;
int a[100005];
int num[100005];

int find(int x){
int y=x;
while(a[y]!=y){
y=a[y];
}
a[x]=y;
return y;
}
int unionx(int x,int y){
int fa=find(x);
int fb=find(y);
if(fa!=fb){
a[fa]=fb;
num[fb]=num[fa]+num[fb];

}
return num[fb];
}

int main(){
ios::sync_with_stdio(0);
while(cin>>n){

for(int i=0;i<n;i++){

for(int j=0;j<100005;j++){
a[j]=j;
num[j]=1;
}
q.clear();
cin>>f;
int count=1;
for(int j=0;j<f;j++){

string s1,s2;
cin>>s1>>s2;
//	repr(ans);
if(q[s1]==0)
q[s1]=count++;
if(q[s2]==0)
q[s2]=count++;
//if(!cnt.count(s1))cnt[s1]=s1;
//if(!cnt.count(s2))cnt[s2]=s2;

//	cout<<unite(s1,s2)<<endl;
cout<<unionx(q[s1],q[s2])<<endl;
}

}
}
return 0;
}