UVa 11503:Virtual Friends2014-10-09 shuangde800 题目链接:UVa : http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=2498HDU: http://acm.hdu.edu.cn/showproblem.php?pid=3172类型: 并查集, 哈希原题: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 Specification
The first line of input contains one integer specifying the number of test cases to follow. Each test case begins with a line containing an integer F, the number of friendships formed, 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).
Sample Input
13Fred BarneyBarney BettyBetty Wilma
Output Specification
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.
Output for Sample Input
234
题意:如果A与B是朋友, C是B的朋友,那么A和B也就是朋友。 这样的话就会形成一个朋友关系网,只有一个人在这个关系网里面,就等于认识这个朋友网里的所有人。 输入一些朋友关系,每输入一个关系,就输出两个人所在朋友网里的总人数分析与总结:很明显的并查集题目。这题关键在与把人名转换成数字。URL:http://www.bianceng.cn/Programming/sjjg/201410/45664.htm这题很坑爹的一个地方:输入的T也是多组的,要用 while(scanf("%d",&T)!=EOF){ while(T--){ ... } }1.直接用STL的map来处理。但是速度不佳: 2.124s(UVa), 625MS(HDU)
/** 并查集 + map* Time:2.124s(UVa), 625MS(HDU)*/#include<iostream>#include<map>#include<string>#include<cstdio>#include<cstring>#define N 100005using namespace std; map<string,int>mp;int father[N], num[N]; void init(){for(int i=0; i<N; ++i)father[i] = i;} int find(int x){int i, j = x;while(j!=father[j]) j = father[j];while(x!=j){i =father[x];father[x] = j;x = i;}return j;} void Union(int x, int y){int a=find(x);int b=find(y);if(a!=b){father[a] = b;num[b] += num[a];}}int main(){#ifdef LOCALfreopen("input.txt","r",stdin);#endif int T, n, K;string person1, person2;while(scanf("%d", &T)!=EOF){while(T--){scanf("%d",&n);int cnt=1;init();mp.clear();while(n--){cin >> person1 >> person2;int x1, x2;if(!(x1=mp[person1])){ x1 = mp[person1] = cnt++; num[cnt-1]=1; }if(!(x2=mp[person2])){ x2 = mp[person2] = cnt++; num[cnt-1]=1; }Union(x1, x2); int x = find(x1);printf("%d
",num[x]);}}}return 0;}