并查集initial,find,union+应用

initial:

cpp 复制代码
void initial(int n) {
    for (int i = 0; i < n; i++) {
        p[i] = i;
        h[i] = 1;
    }
}

find:

cpp 复制代码
int find(int x) {
    if (p[x] == x) return x;
    else return p[x] = find(p[x]);
}

union:

cpp 复制代码
void union(int x, int y) {
    int rootx = find(x);
    int rooty = find(y);
    if (rootx != rooty) {
        if (h[rootx] < h[rooty]) p[rootx] = rooty;
        else if (h[rootx] > h[rooty]) p[rooty] = rootx;
        else p[rootx] = rooty, h[rooty]++;
    }
}

例题:

cpp 复制代码
#include <iostream>
using namespace std;

const int N = 10010;

int p[N], h[N];
bool visited[N];         // 记录鸟是否出现过
bool isroot[N];          // 记录某个根节点是否已被计入树
int photos[10000][10];   // 每张照片中最多10只鸟,最多10000张照片
int photosize[10000];    // 每张照片的鸟的数量

void initial(int n) {
    for (int i = 0; i < n; i++) {
        p[i] = i;
        h[i] = 1;
        visited[i] = false;
        isroot[i] = false;
    }
}

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

void unionset(int x, int y) {
    int rootx = find(x);
    int rooty = find(y);
    if (rootx != rooty) {
        if (h[rootx] < h[rooty]) p[rootx] = rooty;
        else if (h[rootx] > h[rooty]) p[rooty] = rootx;
        else p[rootx] = rooty, h[rooty]++;
    }
}

int main() {
    int n;
    cin >> n;

    initial(N);

    int maxid = 0;

    // 输入照片数据
    for (int i = 0; i < n; i++) {
        int k;
        cin >> k;
        photosize[i] = k;
        for (int j = 0; j < k; j++) {
            int bird;
            cin >> bird;
            photos[i][j] = bird;
            visited[bird] = true;
            if (bird > maxid) maxid = bird;
        }
    }

    // 合并同一张照片的鸟
    for (int i = 0; i < n; i++) {
        int k = photosize[i];
        for (int j = 1; j < k; j++) {
            unionset(photos[i][0], photos[i][j]);
        }
    }

    int birdcnt = 0, treecnt = 0;

    // 统计鸟的数量和树的数量(去重根节点)
    for (int i = 1; i <= maxid; i++) {
        if (visited[i]) {
            birdcnt++;
            int root = find(i);
            if (!isroot[root]) {
                isroot[root] = true;
                treecnt++;
            }
        }
    }

    cout << treecnt << " " << birdcnt << endl;

    // 处理查询
    int q;
    cin >> q;
    while (q--) {
        int x, y;
        cin >> x >> y;
        if (find(x) == find(y)) cout << "Yes" << endl;
        else cout << "No" << endl;
    }

    return 0;
}
相关推荐
这儿有一堆花40 分钟前
比特币:固若金汤的数字堡垒与它的四道防线
算法·区块链·哈希算法
客卿1231 小时前
力扣100-移动0
算法·leetcode·职场和发展
多吃蔬菜!!!4 小时前
排序算法C语言实现
数据结构
零叹4 小时前
篇章六 数据结构——链表(二)
数据结构·链表·linkedlist
CM莫问4 小时前
<论文>(微软)WINA:用于加速大语言模型推理的权重感知神经元激活
人工智能·算法·语言模型·自然语言处理·大模型·推理加速
计信金边罗6 小时前
是否存在路径(FIFOBB算法)
算法·蓝桥杯·图论
MZWeiei6 小时前
KMP 算法中 next 数组的构建函数 get_next
算法·kmp
Fanxt_Ja7 小时前
【JVM】三色标记法原理
java·开发语言·jvm·算法
luofeiju7 小时前
行列式的性质
线性代数·算法·矩阵
緈福的街口7 小时前
【leetcode】347. 前k个高频元素
算法·leetcode·职场和发展