hdu1213

hdu1213

​                                                             How Many Tables

0x00 Tags

并查集(Disjoint Set)

0x01 题目简介

有n个人一起吃饭,有些人互相认识。认识的人想坐在一起,不想跟陌生人坐。例如A认识B,B认识C,那么A,B,C会坐在一张桌子上。

给出认识的人,问需要多少张桌子?

0x02 代码

#include<bits/stdc++.h>

using namespace std;

const int maxn = 1010;

int root[maxn];


void Init()
{
	for (int i = 1; i < maxn; i++)
	{
		root[i] = i;
	}
}


int Find(int x)
{
	return x == root[x] ? x : Find(root[x]);
}


void Union(int x, int y)
{
	x = Find(x);
	y = Find(y);

	if (x != y) root[x] = y;
}



int main()
{

	int t, n, m, x, y;

	scanf("%d", &t);

	while (t--)
	{
		scanf("%d%d", &n, &m);

		Init();

		for (int i = 1; i <= m; i++)
		{
			scanf("%d%d", &x, &y);
			Union(x, y);
		}

		int ans = 0;

		for (int i = 1; i <= n; i++)
		{
			if (root[i] == i)
				ans++;
		}

		printf("%d", ans);
	}



	return 0;
}

0x03 代码优化

路径压缩

#include<bits/stdc++.h>

using namespace std;

const int maxn = 1010;

int root[maxn];


void Init()
{
	for (int i = 1; i < maxn; i++)
	{
		root[i] = i;
	}
}

// 查找的优化---路径压缩
int Find(int x)
{
	//return x == root[x] ? x : Find(root[x]);

	int r = x;

	while (root[r] != r)
	{
		r = root[r];  // 找到根结点
	}

	int i = x, j;
	
	while (i != r)
	{
		j = root[i];  // 用临时变量j记录
		root[i] = r;  // 把路径上元素的集改为根结点
		i = j;
	}

	return r;
}


void Union(int x, int y)
{
	x = Find(x);
	y = Find(y);

	if (x != y) root[x] = y;
}



int main()
{

	int t, n, m, x, y;

	scanf("%d", &t);

	while (t--)
	{
		scanf("%d%d", &n, &m);

		Init();

		for (int i = 1; i <= m; i++)
		{
			scanf("%d%d", &x, &y);
			Union(x, y);
		}

		int ans = 0;

		for (int i = 1; i <= n; i++)
		{
			if (root[i] == i)
				ans++;
		}

		printf("%d", ans);
	}



	return 0;
}

按秩优化

#include<bits/stdc++.h>

using namespace std;

const int maxn = 1010;

int root[maxn];
int Rank[maxn];


void Init()
{
	for (int i = 1; i < maxn; i++)
	{
		root[i] = i;
		Rank[i] = 0;  // 树的高度
	}
}


int Find(int x)
{
	return x == root[x] ? x : Find(root[x]);

}


void Union(int x, int y)
{
	x = Find(x);
	y = Find(y);

	if (Rank[x] == Rank[y])
	{
		Rank[x] = Rank[x] + 1;
		root[y] = x;
	}
	else
	{
		if (Rank[x] < Rank[y]) root[x] = y;
		else root[y] = x;
	}
}



int main()
{

	int t, n, m, x, y;

	scanf("%d", &t);

	while (t--)
	{
		scanf("%d%d", &n, &m);

		Init();

		for (int i = 1; i <= m; i++)
		{
			scanf("%d%d", &x, &y);
			Union(x, y);
		}

		int ans = 0;

		for (int i = 1; i <= n; i++)
		{
			if (root[i] == i)
				ans++;
		}

		printf("%d", ans);
	}


	return 0;
}

备注

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值