【HDU - 3172】Virtual Friends(带权并查集--权为集合元素个数)
題干:
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 WilmaSample Output
2 3 4題目大意:
有多個測試組T,每個測試組第一行n,接下來n行表示甲與乙認識,每給出一個關系,求出一共有多少個朋友。朋友的朋友也是朋友。
解題報告 :
先用map映射一下每個字符串對應一個序號(因為不然的話不好放到f數組num數組 的下標上)然后查詢祖先節點那個集合的元素個數。
AC代碼:
#include<iostream> #include<cstdio> #include<algorithm> #include<map> #include<string>using namespace std; int n,m; char s1[50],s2[50]; int f[200000 + 5]; int num[200000 + 5]; map<string , int> mp;int getf(int v) {return v==f[v]?v:f[v]=getf(f[v]); } void merge(int u,int v) {int t1=getf(u);int t2=getf(v);if(t1!=t2) {f[t2]=t1;num[t1]+=num[t2];//別寫成t2了。。。。 } } void init() {for(int i = 1; i<=200000 + 5; i++) {f[i]=i;num[i]=1;} } int main() {int top;while(~scanf("%d",&n) ) {while(n--) {mp.clear();top = 0;init();scanf("%d",&m);while(m--) {scanf("%s",s1);scanf("%s",s2);if(mp.find(s1) == mp.end() ) mp[s1] = ++top;if(mp.find(s2) == mp.end() ) mp[s2] = ++top;merge(mp[s1],mp[s2]);printf("%d\n",num[ getf( mp[s1] ) ] );}//一共top個人 }}return 0 ; }總結:
? ?無。
?
總結
以上是生活随笔為你收集整理的【HDU - 3172】Virtual Friends(带权并查集--权为集合元素个数)的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: ACM技巧 - O(1)快速乘(玄学)
- 下一篇: 新一代iPad mini曝光:供应量称配
