高级数据结构

学习竞赛编程必备的高级数据结构:并查集、平衡树和用于复杂问题解决的专用结构。

1. 并查集

并查集数据结构,通过路径压缩和按秩合并优化高效管理不相交集合。

并查集实现

#include <iostream>
#include <vector>
using namespace std;

class UnionFind {
private:
    vector<int> parent, rank;
    int components;

public:
    UnionFind(int n) : parent(n), rank(n, 0), components(n) {
        for (int i = 0; i < n; i++) {
            parent[i] = i;
        }
    }
    
    int find(int x) {
        if (parent[x] != x) {
            parent[x] = find(parent[x]); // Path compression
        }
        return parent[x];
    }
    
    bool unite(int x, int y) {
        int px = find(x), py = find(y);
        if (px == py) return false;
        
        // Union by rank
        if (rank[px] < rank[py]) {
            parent[px] = py;
        } else if (rank[px] > rank[py]) {
            parent[py] = px;
        } else {
            parent[py] = px;
            rank[px]++;
        }
        
        components--;
        return true;
    }
    
    bool connected(int x, int y) {
        return find(x) == find(y);
    }
    
    int getComponents() {
        return components;
    }
};

int main() {
    UnionFind uf(6);
    
    cout << "Initial components: " << uf.getComponents() << endl;
    
    uf.unite(0, 1);
    uf.unite(2, 3);
    uf.unite(4, 5);
    
    cout << "After unions: " << uf.getComponents() << endl;
    cout << "0 and 1 connected: " << uf.connected(0, 1) << endl;
    cout << "0 and 2 connected: " << uf.connected(0, 2) << endl;
    
    uf.unite(1, 2);
    cout << "After uniting 1 and 2: " << uf.getComponents() << endl;
    cout << "0 and 3 connected: " << uf.connected(0, 3) << endl;
    
    return 0;
}

总结

  • 并查集:高效的不相交集合操作,平摊时间复杂度接近 O(1)
  • 路径压缩:扁平化树结构以加快后续操作
  • 按秩合并:保持树的平衡以维持效率
  • 应用:Kruskal 最小生成树、连通性问题、环检测