Virtual Friends
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3027 Accepted Submission(s): 883
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.
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).
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
题意:
给一次朋友配对关系就更新一次朋友圈的人数。
思路:
并查集,用Map关联容器给每个人名配对上序号,最后将序号合并就可以了。
AC:
#include<cstdio> #include<string> #include<map> using namespace std; int root[100005]; int rank[100005]; int find(int a) { int x=a,t; while(x!=root[x]) x=root[x]; while(x!=a) { t=root[a]; root[a]=x; a=t; } return x; } void merge(int a,int b) { int fa,fb; fa=find(a); fb=find(b); if(fa!=fb) { rank[fb]+=rank[fa]; root[fa]=fb; } printf("%d\n",rank[fb]); //更新完一次就输出一次 } int main() { int n; while(scanf("%d",&n)!=EOF) { map<string,int> m; while(n--) { int t,k=1; char name1[25],name2[25]; m.clear(); for(int i=1;i<100005;i++) root[i]=i,rank[i]=1; scanf("%d",&t); while(t--) { scanf("%s%s",name1,name2); if(m.find(name1)==m.end()) m[name1]=k++; if(m.find(name2)==m.end()) m[name2]=k++; //给人名配上序号 merge(m[name1],m[name2]); } } } return 0; }
总结:
1.WA了几次,因为要用while(scanf("%d",&n)!=EOF)多次输入;
2.每次合并一次就输出一次人数,不需要每次合并完再遍历一次rank数组找出最大值,这题比较特殊,只有一个集合,只要合并一次更新一次后马上输出即可。如果要遍历的话会TLE。