并查集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;
}
相关推荐
The_cute_cat6 分钟前
试除法判断素数优化【C语言】
算法
Darkwanderor24 分钟前
一般枚举题目合集
c++·算法
@我漫长的孤独流浪1 小时前
最短路与拓扑(2)
数据结构·c++·算法
٩( 'ω' )و2601 小时前
哈希表的实现01
数据结构·c++·哈希算法·散列表
<但凡.2 小时前
C++修炼:多态
开发语言·c++·算法
买了一束花2 小时前
数据预处理之数据平滑处理详解
开发语言·人工智能·算法·matlab
YuforiaCode2 小时前
LeetCode 热题 100 35.搜索插入位置
数据结构·算法·leetcode
Jasmine_llq3 小时前
《P4391 [BalticOI 2009] Radio Transmission 无线传输 题解》
算法·字符串·substr
水水沝淼㵘4 小时前
嵌入式开发学习日志(数据结构--单链表)Day20
c语言·开发语言·数据结构·学习·算法
算法给的安全感4 小时前
bfs-最小步数问题
java·算法·宽度优先