网络交友 并查集 计数

在网络社交的过程中,通过朋友,也能认识新的朋友。在某个朋友关系图中,假定 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
*/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值