【模板】并查集简单版模板(路径压缩、按size合并双重优化版,C#)

前言:

        在游戏开发写某个功能(暂不能透露)的时候没想到要用到以前打算法用的并查集。啊...(此处省略几个字的感慨)。

        于是打开了以前刷题的网站把自己之前闭着眼睛都能敲出来的并查集代码找了出来(现在是怎么了,怎么睁着眼睛也写不出来了???)

        没啥亮点,就是用了大家常用的路径压缩和按大小合并(按大小比按秩合并和路径压缩更配傲!)

代码:

using System.Collections.Generic;
/// <summary>
/// 并查集 
/// </summary>
public class UnionFind
{
    
    private List<int> p;
    private List<int> s;
    private int count;      // 连通的个数
    /// <summary>
    /// 初始化
    /// </summary>
    public UnionFind(int a)
    {
        p = new List<int>();
        s = new List<int>();
        for (int i = 0; i < a; ++i)
        {
            p.Add(i);
            s.Add(1);
        }
        count = a;
    }
    /// <summary>
    /// 查找连通根节点
    /// </summary>
    public int Find(int a)
    {
        return a == p[a] ? a : p[a] = Find(p[a]);
    }
    /// <summary>
    /// 合并
    /// </summary>
    public void Union(int a, int b)
    {
        int pa = Find(a);
        int pb = Find(b);
        if (pa == pb) return;
        if (s[pa] < s[pb])
        {
            p[pa] = pb;
            s[pb] += s[pa];
        }
        else
        {
            p[pb] = pa;
            s[pa] += s[pb];
        }
        count--;
    }
    /// <summary>
    /// 返回连通数
    /// </summary>
    public int Liantong()
    {
        return count;
    }
    /// <summary>
    /// 连通大小
    /// </summary>
    public int Size(int a)
    {
        int pa = Find(a);
        return s[pa];
    }
};

讲解:

        网上讲解博客一大堆!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

咖啡咖_CoffCa

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值