HDU 3172 Virtual Friends(并查集)

时空隧道


题目意思是说,有多组测试数据,每组一个t表示有t个社交网络,接下来f 表示有f个朋友链形成(原谅我贫乏的语文...)


然后,问,当每个朋友链形成时,当前朋友网中有多少个人(大体就是这个意思...)


其实就是个很简单的并查集....因为最近很不在状态,导致读题各种挫。


然后wa了好几次...以前学的map太久没用,也不会用了,然后,算是复习了一下,虽然很多还是没懂。

(也可以用字典树,不过感觉字典树挺麻烦的)


纪念一下错了好几次的题...

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<map>
#include<algorithm>
using namespace std;
const int maxn=100010;
int bleg[maxn<<1],cnt[maxn<<1];
int n,_cnt;
map<string,int> m;
int Insert(char *s)
{
    string str(s);
    if(m.find(str)==m.end()){// 查找是否有str 若没有就返回m.end()
		m[str]=_cnt++;
    }
    return m[str];
}
void Init()
{
	for(int i=0;i<=2*n;i++)
		bleg[i]=i,cnt[i]=1;
}
int Find(int x)
{
	int y=x;
	while(x!=bleg[x])
		x=bleg[x];
	while(y!=bleg[y])
	{
		int px=bleg[y];
		bleg[y]=x;
		y=px;
	}
	return x;
}
int Union(int x,int y)
{
	int px=Find(x),py=Find(y);
	if(px==py) return cnt[px];
	if(cnt[px]>=cnt[py])
	{
		bleg[py]=px;
		cnt[px]+=cnt[py];
		return cnt[px];
	}
	else{
		bleg[px]=py;
		cnt[py]+=cnt[px];
		return cnt[py];
	}
}
int main()
{
    int t;
    char str[100],s[100];
    while(~scanf("%d",&t))
    {
		while(t--)
		{
			scanf("%d",&n);
			_cnt=0;
			Init();
			m.clear();
			for(int i=0;i<n;i++)
			{
				scanf("%s%s",str,s);
				int a=Insert(str),b=Insert(s);
				int tmp=Union(a,b);
				printf("%d\n",tmp);
			}
		}
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值