并查集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;
}
相关推荐
liuluyang5302 小时前
C语言C11支持的结构体嵌套的用法
c语言·开发语言·算法·编译·c11
勤劳的进取家3 小时前
贪心算法之最小生成树问题
数据结构·python·算法·贪心算法·排序算法·动态规划
牛奶咖啡.8543 小时前
第十四届蓝桥杯大赛软件赛省赛C/C++ 大学 A 组真题
c语言·数据结构·c++·算法·蓝桥杯
亓才孓3 小时前
[leetcode]stack的基本操作的回顾
算法
小美爱刷题3 小时前
力扣DAY46-50 | 热100 | 二叉树:展开为链表、pre+inorder构建、路径总和、最近公共祖先、最大路径和
算法·leetcode·链表
Fanxt_Ja4 小时前
【数据结构】红黑树超详解 ---一篇通关红黑树原理(含源码解析+动态构建红黑树)
java·数据结构·算法·红黑树
永恒迷星.by4 小时前
全球变暖(蓝桥杯 2018 年第九届省赛)
算法
那就摆吧5 小时前
数据结构-复杂度详解
数据结构
旧时光林5 小时前
蓝桥杯 分解质因数(唯一分解定理)
数据结构·c++·算法·蓝桥杯·模拟·枚举
烁3475 小时前
每日一题(小白)模拟娱乐篇27
java·数据结构·算法·娱乐