Virtual Friends
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 7475 Accepted Submission(s): 2138
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.
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).
1 3 Fred Barney Barney Betty Betty Wilma
2 34
题意:求出每次加入的两个新的关系时朋友链的长度。因为输入不是数字是字符串,所以想到用map去存。
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <map> using namespace std; #define N 100010 int pre[N]; int sum[N]; map<string,int> p; int finds(int x) { int r=x; while(r!=pre[r]) { r=pre[r]; } int k=x,l; while(k!=pre[k]) { l=k; k=pre[k]; pre[l]=r; } return r; } void mix(int a,int b) { int x=finds(a),y=finds(b); if(x!=y) { pre[x]=y; sum[y]+=sum[x]; } printf("%d\n",sum[y]); } int main() { int t,n; char a[25],b[25]; while(scanf("%d",&t)!=EOF) { while(t--) { scanf("%d",&n); p.clear(); int ans=1; for(int i=0;i<N;i++) { pre[i]=i; sum[i]=1; } for(int i=0;i<n;i++) { scanf("%s %s",a,b); if(!p[a]) p[a]=ans++; if(!p[b]) p[b]=ans++; mix(p[a],p[b]); } } } return 0; }
本文介绍了一种通过编程计算在线虚拟社交网络中好友关系规模的方法。针对每一对新建立的好友关系,算法能够即时更新并返回包含这两个人在内的社交网络总人数。利用并查集数据结构实现高效查找和合并操作。
915

被折叠的 条评论
为什么被折叠?



