日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【HDU - 3172】Virtual Friends(带权并查集--权为集合元素个数)

發(fā)布時間:2023/12/10 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【HDU - 3172】Virtual Friends(带权并查集--权为集合元素个数) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

題干:

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 Wilma

Sample Output

2 3 4

題目大意:

有多個測試組T,每個測試組第一行n,接下來n行表示甲與乙認(rèn)識,每給出一個關(guān)系,求出一共有多少個朋友。朋友的朋友也是朋友。

解題報(bào)告 :

先用map映射一下每個字符串對應(yīng)一個序號(因?yàn)椴蝗坏脑挷缓梅诺絝數(shù)組num數(shù)組 的下標(biāo)上)然后查詢祖先節(jié)點(diǎn)那個集合的元素個數(shù)。

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 ; }

總結(jié):

? ?無。

?

總結(jié)

以上是生活随笔為你收集整理的【HDU - 3172】Virtual Friends(带权并查集--权为集合元素个数)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。