算法 :并查集

关键函数

int find(int x)
{
    if(p[x] != x) p[x] = find(p[x]);
    return p[x];
}

find函数用来找出每个集合的根节点,然后进行路径压缩

让 x结点 直接指向根节点

例题:连通块中点的数量

https://www.acwing.com/problem/content/839/

并查集的应用 ,但是这题还要维护一个cnt 数组 用来记录每个集合点的数量

这里可以只维护根节点

#include <iostream>

using namespace std;

const int N = 100010;

int n,m;
int p[N],cnt[N];

int find(int x) //关键函数
{
    if(p[x] != x) p[x] = find(p[x]);
    return p[x];
}

int main()
{
    cin >> n >> m;
    
    for(int i = 1;i <= n;i ++) // 并查集初始化
    {
        p[i] = i; // 每个点的初始根节点为自己
        cnt[i] = 1; // 每个点为一个集合且点的数量为1
    }
    
    while(m --)
    {
        string op;
        int a, b;
        cin >> op;
        
        if(op == "C")
        {
            cin >> a >> b;
            a = find(a),b = find(b);//找到两点的跟结点
            if(a != b) //如果两点不在同一集合
            {
                p[a] = b;//将a 并到b上

                cnt[b] += cnt[a];// 求合并后的点的数量 只维护根节点
            }
        }
        else if(op == "Q1")
        {
            cin >> a >> b;
            if(find(a) == find(b))puts("Yes");
            else puts("No");
        }
        else
        {
            cin >> a;
            cout << cnt[find(a)] << endl;//直接返回所在集合点数量
        }
    }
    
    return 0;
    
}

例题:食物链
https://www.acwing.com/problem/content/242/

维护点到根节点的距离来判断动物是否为一类

#include <iostream>

using namespace std;

const int N = 50010;

int n,m;
int p[N],d[N];

int find(int x)
{
    if(p[x] != x)
    {
        int t = find(p[x]);
        d[x] += d[p[x]]; // 先更新距离
        p[x] = t;//在更新根节点
    }
    return p[x];
}

int main()
{
    cin >> n >> m;
    
    for(int i = 1;i <= n;i ++)p[i] = i;
    
    int res = 0;
    while(m --)
    {
        int t , x, y;
        cin >> t >> x >> y;
        
        if(x > n || y > n) res ++;
        else
        {
            int px = find(x),py = find(y);
            if(t == 1)
            {
                if(px == py && (d[x] - d[y]) % 3)res ++;
                else if(px != py)
                {
                    p[px] = py;
                    d[px] = d[y] - d[x];
                }
            }
            else
            {
                if(px == py && (d[x] - d[y] - 1) % 3)res ++;
                else if(px != py)
                {
                    p[px] = py;
                    d[px] = d[y] - d[x] + 1;
                }
            }
            
        }
    }
    
    cout << res << endl;
    
    return 0;
    
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

谁能告诉我未来

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

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

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

打赏作者

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

抵扣说明:

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

余额充值