HDU - 3172 Virtual Friends(并查集)
2017-08-07 15:25
405 查看
Virtual Friends
hese 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
13
Fred Barney
Barney Betty
Betty Wilma
Sample Output
23
4
题意:
给n对关系,对于每一对关系询问给出这次关系后,这两个人所在的社交圈大小是多少容易想到,给每一个名字标号,这样就变成一个并查集查询size的问题,标号可以利用map实现,需要留意的是名字可能是2*n,fa数组要开2*n,不然会RE或者WA。。。
#include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #include<map> using namespace std; const int maxn=2e5+5; int fa[maxn],n,x,y,cnt,size[maxn]; string s1,s2; map<string,int>Q; inline int get(int u) { if(fa[u]==u)return u; return fa[u]=get(fa[u]); } int main() { int T; while(~scanf("%d",&T)) { while(T--) { Q.clear(); //memset(size,1,sizeof(size)); scanf("%d",&n); for(int i=1;i<maxn;++i)fa[i]=i,size[i]=1; cnt=0; for(int i=1;i<=n;++i) { cin>>s1>>s2; //cout<<s1<<" "<<s2<<endl; if(Q[s1]==0)x=Q[s1]=++cnt; else x=Q[s1]; if(Q[s2]==0)y=Q[s2]=++cnt; else y=Q[s2]; //printf("x=%d y=%d\n",x,y); x=get(x);y=get(y); if(x!=y) { fa[x]=y; size[y]+=size[x]; size[x]=0; printf("%d\n",size[y]); } else printf("%d\n",size[x]); } } } return 0; }
相关文章推荐
- hdu 3172 Virtual Friends(并查集)University of Waterloo Local Contest 2008.09
- hdu 3172 Virtual Friends(并查集)
- HDU 3172 Virtual Friends (并查集)
- hdu 3172 virtual friends 并查集
- HDU 3172 Virtual Friends (并查集)
- HDU 3172 Virtual Friends(并查集)
- HDU 3172 Virtual Friends 带权并查集 -秩
- hdu 3172 Virtual Friends(简单并查集)
- HDU 3172 Virtual Friends (并查集与map的运用,同HDU1829)
- HDU 3172 并查集-Virtual Friends
- hdu 3172 Virtual Friends(并查集,字典树)
- HDU 3172 Virtual Friends (并查集节点统计)
- hdu 3172 Virtual Friends (并查集)
- HDU 并查集 - 3172 Virtual Friends
- hdu 3172 Virtual Friends(加权并查集)
- HDU 3172 Virtual Friends(带权并查集)
- hdu 3172 Virtual Friends (并查集 + 字典树)
- 并查集 HDU 3172 Virtual Friends
- HDU 3172 Virtual Friends(带权并查集,map)
- hdu 3172 Virtual Friends