Virtual Friends

Problem Description
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.
 
 

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
class node
{
 public:
  int ord;
  int flag;
  char d;
  node *next[52];
  node()
  {
   flag=0;
   memset(next,0,sizeof(next));
  }

};
struct uion
{
 int num;
 int father;
};
int cnt;
uion ufs[200005];
void init(int n);
int create(node *&root,char name[]);
int find(int x);
int  uion(int fx,int fy);
void del(node *p);
int main()
{
 int n,F,x,y,fx,fy;
 char name[30];
 node *root=new node;
 while(scanf("%d",&n)!=EOF)
 {
  while(n--)
  {
   scanf("%d",&F);
   init(2*F);
   memset(root->next,0,sizeof(root->next));
   cnt=0;
   while(F--)
   {
    scanf("%s",name);
    x=create(root,name);
    scanf("%s",name);
    y=create(root,name);
    fx=find(x);
    fy=find(y);
    if(fx!=fy)
    cout<<uion(fx,fy)<<endl;
    else
     cout<<ufs[fx].num<<endl;
   }
  }
 }
 return 0;
}

void init(int n)
{
 int i;
 for(i=1;i<=n;++i)
 {
  ufs[i].num=1;
  ufs[i].father=i;
 }
}
int create(node *&root,char name[])
{
 node *p=root;
 char *q=name;
 int k;
 while(*q)
 {
  if(*q>='a'&&*q<='z')
   k=*q-'a';
  else
   k=*q-'A'+26;
  if(p->next[k]==NULL)
   p->next[k]=new node;
  p=p->next[k];
  ++q;
 }
 if(p->flag==0)
 {
  p->flag=1;
  p->ord=++cnt;
 }
 return p->ord;
}
int find(int x)
{
 if(x!=ufs[x].father)
  ufs[x].father=find(ufs[x].father);
 return ufs[x].father;
}
int  uion(int fx,int fy)
{
 if(ufs[fx].num<ufs[fy].num)
 {
  ufs[fx].father=fy;
  ufs[fy].num+=ufs[fx].num;
  return ufs[fy].num;
 }
 else
 {
  ufs[fy].father=fx;
  ufs[fx].num+=ufs[fy].num;
  return ufs[fx].num;
 }
}

posted on 2013-04-26 18:34  耶稣爱你  阅读(199)  评论(0编辑  收藏  举报