#include <iostream>
#include <map>
#include <cstdio>
#include <string>
#define MAXN 100003
using namespace std;
map<string,int>m;
int father[MAXN],num[MAXN];
int find(int x)
{//带路径压缩的查找算法
int r=x;
while(r!=father[r])//循环结束,则找到根节点
r=father[r];
int i=x;
while(i!=r)//本循环修改查找路径中所有节点
{
int j=father[i];
father[i]=r;
i=j;
}
return r;
}
void Union(int x,int y)
{
int fx=find(x);
int fy=find(y);
if (fx!=fy)
{
father[fx]=fy;
num[fy]+=num[fx];
printf("%d\n",num[fy]);
}
else
{
printf("%d\n",num[fy]);
}
}
int main()
{
int t,i,n,cnt;
char s1[25],s2[25];
while(scanf("%d",&t)!=EOF)
{
while(t--)
{
for (i=1;i<=100002;i++)
{
father[i]=i;
num[i]=1;
}
scanf("%d",&n);
m.clear();
cnt=1;//每个人的下标
for (i=1;i<=n;i++)
{
scanf("%s %s",&s1,&s2);
if(!m[s1])
{
m[s1]=cnt++;
}
if(!m[s2])
{
m[s2]=cnt++;
}
Union(m[s1],m[s2]);
}
}//while
}//while
return 0;
}
hdu3172 Virtual Friends
最新推荐文章于 2015-06-14 16:47:55 发布