并查集

题目链接:点击打开链接

#include<cstdio>
#define MAXN 1000 + 10
int fa[MAXN];
int find_set(int i)
{
    if(fa[i] == i) return i;
    else return (find_set(fa[i]));
}
void union_set(int x,int y)
{
    int root_x = find_set(x);
    int root_y = find_set(y);
    if(root_x != root_y) fa[root_x] = root_y;
}
int main()
{
    int n,m;
    int x,y;
    while(scanf("%d",&n) > 0)
    {
        if(!n) break;
        scanf("%d",&m);
        for(int i = 1; i <= n; i++) fa[i] = i;
        for(int i = 1; i <= m; i++)
        {
        scanf("%d%d",&x,&y);
        union_set(x,y);
        }
        int result = 0;
        for(int i = 1; i <= n; i++) if(fa[i] == i) result ++;
        printf("%d\n",result - 1);
    }
    return 0;
}

使用rank和路径压缩优化后的代码如下:

#include<cstdio>
#define MAXN 1000 + 10
int fa[MAXN];
struct Node 
{
	int father;
	int rank;
}node[MAXN];
int find_set(int i)
{
	if(node[i].father == i) return i;
	else{ 
		node[i].father = find_set(node[i].father);
		return node[i].father;
	}
}
void union_set(int x,int y)
{
	int root_x = find_set(x);
	int root_y = find_set(y);
	if(root_x != root_y){
		if (node[root_x].rank > node[root_y].rank)
		{
			node[root_y].father = root_x;
			node[root_x].rank ++;
		} 
		else
		{
			node[root_x].father = root_y;
			node[root_y].rank++;
		}
	}
}
int main()
{
	int n,m;
	int x,y;
	while(scanf("%d",&n) > 0)
	{
		if(!n) break;
		scanf("%d",&m);
		for(int i = 1; i <= n; i++){
			node[i].father = i;
			node[i].rank = 0;
		}
		for(int i = 1; i <= m; i++)
		{
			scanf("%d%d",&x,&y);
			union_set(x,y);
		}
		int result = 0;
		for(int i = 1; i <= n; i++) if(node[i].father == i) result ++;
		printf("%d\n",result - 1);
	}
	return 0;
}

但是效果不是很好。。。。下图中109ms为优化后的运行时间。呵呵。。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值