题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3172
Assume that every friendship is mutual. If Fred is Barney's friend, then Barney is also Fred's friend.
InputInput 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).OutputWhenever 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 题解:带权并查集 可以记录每个集合中元素的个数
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <iomanip>
#include <cmath>
#include <ctime>
#include <map>
#include <set>
#include <queue>
using namespace std;
#define lowbit(x) (x&(-x))
#define max(x,y) (x>y?x:y)
#define min(x,y) (x<y?x:y)
#define MAX 100000000000000000
#define MOD 1000000007
#define pi acos(-1.0)
#define ei exp(1)
#define PI 3.141592653589793238462
#define INF 0x3f3f3f3f3f
#define mem(a) (memset(a,0,sizeof(a)))
typedef long long ll;
ll gcd(ll a,ll b){
return b?gcd(b,a%b):a;
}
const int N=;
const int mod=1e9+;
map<string,int> mp;
int sum[N],f[N];
void init()
{
for(int i=;i<N;i++)
f[i]=i,sum[i]=;
}
int Find(int x)
{
if(x!=f[x])
f[x]=Find(f[x]);
return f[x];
}
int Union(int a,int b)
{
int p=Find(a);
int q=Find(b);
if(p!=q){
f[p]=q;
sum[q]+=sum[p];
}
return sum[q];
}
int main()
{
int t,n;
while(scanf("%d",&t)!=EOF){
while(t--){
mp.clear();
scanf("%d",&n);
init();
int num=;
char a[],b[];
while(n--){
int u,v;
scanf("%s%s",a,b);
if(mp[a]==) mp[a]=num++;
if(mp[b]==) mp[b]=num++;
u=mp[a],v=mp[b];
int k=Union(u,v);
printf("%d\n",k);
}
}
}
return ;
}