【并查集+Map】

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.
 
Sample Input
1
3
Fred Barney
Barney Betty
Betty Wilma
 
Sample Output
2
3
4
题目大意:
输入T,表示有T组数据。T可以重复输入。。。
然后再输入N,表示有N对关系,下面有N行,每一行输入两个人得名字,表示这两个人刚刚成为了朋友。
问你,再这些输入的人中,刚刚成为朋友的那一对,他们两的朋友圈有多少个人。
 
解法:用Map来把名字转化为数字表示,然后用并查集维护。注意输入的N不是表示人数而是对数!!!
 
代码:
 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <map>
 4 #include <string>
 5 #include <string.h>
 6 #define Max 2000010
 7 using namespace std;
 8 int Count[Max];
 9 int ID[Max];
10 void Cread(int N)
11 {
12     for(int i=1;i<=2*N;i++){ID[i]=i;Count[i]=1;}
13 }
14 int Find(int x)
15 {
16     if(x!=ID[x])
17         ID[x]=Find(ID[x]);
18     return ID[x];
19 }
20 void Updata(int x,int y)
21 {
22     int A=Find(x);
23     int B=Find(y);
24     if(A!=B)
25     {
26         ID[B]=A;
27         Count[A]+=Count[B];
28     }
29     return ;
30 }
31 int main()
32 {
33     int T,i,j,N,A,B;
34     int Sign=1;
35     char Str1[100];
36     char Str2[100];
37     map<string,int>Map;
38     while(scanf("%d",&T)!=EOF)
39    {
40         while(T--)
41         {
42             Sign=1;
43             scanf("%d",&N);
44             Cread(N);
45             Map.clear();
46             for(i=0;i<N;i++)
47             {
48                 scanf(" %s%s",Str1,Str2);
49                 if(!Map[Str1])Map[Str1]=Sign++;
50                 if(!Map[Str2])Map[Str2]=Sign++;
51                 Updata(Map[Str1],Map[Str2]);
52                 printf("%d\n",Count[Find(Map[Str1])]);
53             }
54         }
55    }
56     return 0;
57 }
View Code
posted @ 2015-07-28 09:52  Wurq  阅读(242)  评论(0编辑  收藏  举报