在网络社交的过程中,通过朋友,也能认识新的朋友。在某个朋友关系图中,假定 A 和 B 是朋友,B 和 C 是朋友,那么 A 和 C 也会成为朋友。即,我们规定朋友的朋友也是朋友。
现在要求你每当有一对新的朋友认识的时候,你需要计算两人的朋友圈合并以后的大小。
先输入数字n
再输入n对人名
就比并查集多了一个大小,这个大小用f[]保存
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <stack>
#include <set>
#include <queue>
#include <map>
using namespace std;
const int inf=0x3f3f3f3f;
int n,f[5005];
map<string,int> name;
int find(int u){
return f[u]<0?u:find(f[u]);
}
void merge(int u,int v){
int tu=find(u);
int tv=find(v);
if(tu!=tv){
f[tv]+=f[tu];//增加
f[tu]=tv;
}
printf("%d\n",0-f[tv]);
}
int main()
{
scanf("%d%",&n);
memset(f,-1,sizeof(f));//初始化父结点为-1
int cnt=1;
for(int i=1;i<=n;i++){
string str1,str2;
cin>>str1>>str2;
if(name.count(str1)!=1)//判断这个名字是否已经存在
name[str1]=cnt++;
if(name.count(str2)!=1)
name[str2]=cnt++;
int u=name[str1],v=name[str2];
merge(u,v);
}
return 0;
}
/*
3
Fred Barney
Barney Betty
Betty Wilma
*/