跳到正文

个人记录

可撤销并查集

Llx2022约 16 分钟
原文
文章信息与版本

文章信息

发布
2023年5月15日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 16 分钟
获赞
3

版本

  1. v1当前

可撤销并查集,是在并查集的基础上增加了可以倒退回之前某一历史状态的功能。

首先看一下最朴素版本的并查集。

C++
int find(int x)
{
    while(x!=p[x])//这里可以是迭代或者递归
        x=p[x];
    return p[x];
}

void merge(int x,int y)
{
    x=find(x);
    y=find(y);
    p[x]=y;
}

find 操作的复杂度为 O(n)O(n)。

一般并查集有两个优化,一个是路径压缩,一个是启发式合并。

路径压缩的原理是在 find 过程中将路径上的每个点的父节点都指向它的祖先节点。

对于一个集合,我们并不关心集合里每个元素的父节点是谁,我们只关心他们的祖先节点是谁,通过路径压缩可以降低树的深度,使得 find 操作达到 α(n)≈4\alpha( n)\approx4 的复杂度。

对于一般并查集用路径压缩优化就足够了。

C++
int find(int x)//路径压缩
{
    if(x!=p[x])
        p[x]=find(p[x]);
    return p[x];
}

void union_set(int x,int y)
{
    x=find(x);
    y=find(y);
    p[x]=y;
}

启发式合并的原理是在集合合并时将小的集合合并到大的集合里,也可以使 find 操作复杂度降低到 O(log⁡n)O(\log n),在集合合并时还要增加一个更新集合大小的操作。

C++
int find(int x)
{
    while(x!=p[x])
        x=p[x];
    return p[x];
}

void union_set(int x,int y)//启发式合并
{
    x=find(x);
    y=find(y);
    if(x!=y)
    {
        if(sz[x]<sz[y])
            swap(x,y);
        sz[x]+=sz[y];
        p[y]=x;
    }
}

启发式合并(复杂度加上 log⁡n\log n):让高度小的树成为高度较大的树的子树,这个优化可以称为启发式合并算法。

[HNOI2009] 梦幻布丁

C++
#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

const int N = 100010, M = 1000010;

int n, m;
int h[M], e[N], ne[N], idx;
int color[N], sz[M], p[M];
int ans;

void add(int a, int b)
{
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
    sz[a]++;
}

void merge(int &x, int &y)
{
    if (x == y)
        return;
    if (sz[x] > sz[y])
        swap(x, y);
    for (int i = h[x]; ~i; i = ne[i])
    {
        int j = e[i];
        ans -= (color[j - 1] == y) + (color[j + 1] == y);
    }
    for (int i = h[x]; ~i; i = ne[i])
    {
        int j = e[i];
        color[j] = y;
        if (ne[i] == -1)
        {
            ne[i] = h[y], h[y] = h[x];
            break;
        }
    }
    h[x] = -1;
    sz[y] += sz[x], sz[x] = 0;
}

int main()
{
    scanf("%d%d", &n, &m);
    memset(h, -1, sizeof h);
    for (int i = 1; i <= n; i++)
    {
        scanf("%d", &color[i]);
        if (color[i] != color[i - 1])
            ans++;
        add(color[i], i);
    }
    for (int i = 0; i < M; i++)
        p[i] = i;
    while (m--)
    {
        int op;
        scanf("%d", &op);
        if (op == 2)
            printf("%d\n", ans);
        else
        {
            int x, y;
            scanf("%d%d", &x, &y);
            merge(p[x], p[y]);
        }
    }

    return 0;
}

并查集的应用主要是 kruskal 算法和连通块,可撤销并查集就可以支持一些更复杂的 kruskal 和连通块的问题。

如果要并查集支持返回之前某个历史状态的话就不能用路径压缩优化了,因为路径压缩会破坏和父节点之间的关系。

以下是可撤销并查集。

C++
int n;
int p[N],sz[N];
vector<pair<int&,int>> his_sz,his_fa;

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

void union_set(int x,int y)
{
    x=find(x);
    y=find(y);
    if(x!=y)
    {
        if(sz[x]<sz[y]) swap(x,y);
        his_sz.push_back({sz[x],sz[x]});
        sz[x]+=sz[y];
        his_fa.push_back({p[y],p[y]});
        p[y]=x;
    }
}
int history()
{
    return his_fa.size();
}
void roll(int h) //回滚到h的历史状态
{
    while(his_fa.size()>h)
    {
        his_fa.back().first=his_fa.back().second;
        his_fa.pop_back();
        his_sz.back().first=his_sz.back().second;
        his_sz.pop_back();
    }
}

注意 his_fa 和 his_sz 中 pair 的前一个元素是引用,表示的是被改变之后的状态,后一个元素表示的是改变前的状态。


I. Envy

题意:给定一张图以及 qq 个查询,输出每个查询中的边是否全部会出现在某个最小生成树里。

首先如果只考虑一次查询,这一次查询只有一条边,那么只要用 kruskal 算法处理完所有边权小于这条边的边,此时如果这条边的两点已经在同一个连通块里了,那么这条边不可能在 MST 里,反之则一定可以在某一个 MST 里。

对于多次查询,每次查询多条边来说类似,先存下所有的询问,然后按照边从小到大开始遍历,如果一组询问中有一条边不符合,那么这个询问就是 NO 的。

但是问题是对于正在查询的某一个边权,它可能存在在很多的查询中,那么就要把每个查询分开讨论了,也就是说对于包含某一个边权的某一组询问,合并这组询问里包含这一边权的边后,需要回滚到合并前的状态才能考虑下一组询问,这就要用到可撤销并查集了。

C++
#include<map>
#include<vector>
#include<iostream>
using namespace std;
const int N=5e5+9;
int ans[N];
struct edge{
    int u,v,w;
}e[N];
vector<pair<int&,int>> size,father;
map<int,vector<int>> mp[N];
vector<int> g[N];
int n,m,fa[N],sz[N];
int q;
template<typename T>inline void read(T &x){
	x=0;T f=1;char ch=getchar();
	while(ch<48||ch>57){if(ch=='-'){f=-1;}ch=getchar();}
	while(ch>=48&&ch<=57){x=x*10+ch-48;ch=getchar();}
	x*=f;
}
template<typename T>inline void write(T x) {
    if(x<0) putchar('-'),x=-x;
    if(x>9) write(x/10);
    putchar(x%10+48);
}
//这是不修改祖宗的
int find(int x)
{
    while(x!=fa[x])
        x=fa[x];
    return fa[x];
}
inline void merge(int x,int y){
    x=find(x);
    y=find(y);
    if(x!=y){
        if(sz[x]<sz[y]) swap(x,y);
        size.push_back({sz[x],sz[x]});
        sz[x]+=sz[y];
        father.push_back({fa[y],fa[y]});
        fa[y]=x;

    }

}
inline int history(){
    return father.size();
}
void roll(int h){
    while(father.size()>h){
        father.back().first=father.back().second;
        father.pop_back();
        size.back().first=size.back().second;
        size.pop_back();
    }
}
int mx;
int main(){
    read(n),read(m);
    for(int i=1;i<=n;++i){
        fa[i]=i;
        sz[i]=1;
    }
    for(int i=1;i<=m;++i){
        read(e[i].u),read(e[i].v),read(e[i].w);
        g[e[i].w].push_back(i);
        mx=max(mx,e[i].w);
    }
    read(q);
    for(int i=1;i<=q;++i){
        ans[i]=1;
        int k;
        read(k);
        while(k--){
            int idx;
            read(idx);
            mp[e[idx].w][i].push_back(idx);
        }
    }
    for(int w=1;w<=mx;++w){
        if(g[w].empty()) continue;
        for(auto p:mp[w]){
            if(!ans[p.first]){
                continue;
            }
            int h=history();
            for(int i:p.second){
                if(find(e[i].u)==find(e[i].v)){
                    ans[p.first]=0;
                }
                merge(e[i].u,e[i].v);
            }
            roll(h);
        }
        for(int i:g[w]){
            merge(e[i].u,e[i].v);
        }
    }
    for(int i=1;i<=q;++i){
        if(ans[i]){
            puts("YES");
        }
        else{
            puts("NO");
        }
    }
    return 0;
}

II.Unique Occurrences

题意:

  • 给定一棵 nn 个节点的树,每条边有颜色 cc 。

  • 求 ∑u=1n∑v=u+1nf(u,v)\sum_{u=1}^{n} \sum_{v=u+1}^{n} f(u,v) 。

  • 其中 f(u,v)f(u,v) 的意义是点 uu 到点 vv 的简单路径上恰好出现一次的颜色的数量。

  • n∈[2,5⋅105],c∈[1,n]n\in [2,5\cdot 10^5],c\in [1,n] 。

考虑一种边权的贡献,那么答案显然就是一条边的左边连通块集合乘上右边集合大小,分治权值获得答案。

C++
#include<map>
#include<vector>
#include<iostream>
using namespace std;
const int N=5e5+9;
int ans[N];
struct edge{
    int u,v,w;
}e[N];
vector<pair<int&,int>> size,father;
vector<pair<int,int>> g[N];
int n,m,fa[N],sz[N];
int q;
template<typename T>inline void read(T &x){
	x=0;T f=1;char ch=getchar();
	while(ch<48||ch>57){if(ch=='-'){f=-1;}ch=getchar();}
	while(ch>=48&&ch<=57){x=x*10+ch-48;ch=getchar();}
	x*=f;
}
template<typename T>inline void write(T x) {
    if(x<0) putchar('-'),x=-x;
    if(x>9) write(x/10);
    putchar(x%10+48);
}
int find(int x)
{
    while(x!=fa[x])
        x=fa[x];
    return fa[x];
}
inline void merge(int x,int y){
    x=find(x);
    y=find(y);
    if(x!=y){
        if(sz[x]<sz[y]) swap(x,y);
        size.push_back({sz[x],sz[x]});
        sz[x]+=sz[y];
        father.push_back({fa[y],fa[y]});
        fa[y]=x;

    }

}
inline int history(){
    return father.size();
}
void roll(int h){
    while(father.size()>h){
        father.back().first=father.back().second;
        father.pop_back();
        size.back().first=size.back().second;
        size.pop_back();
    }
}
typedef long long ll;
ll dfs(int l,int r)
{
    if(l==r)
    {
        ll res=0;
        for(auto p:g[l])
            res+=(ll)sz[find(p.first)]*sz[find(p.second)];
        return res;
    }
    ll res=0;
    int mid=(l+r)/2;
    int h=history();
    for(int i=mid+1;i<=r;i++)
        for(auto p:g[i])
            merge(p.first,p.second);
    res+=dfs(l,mid);
    roll(h);
    h=history();
    for(int i=l;i<=mid;i++)
        for(auto p:g[i])
            merge(p.first,p.second);
    res+=dfs(mid+1,r);
    roll(h);
    return res;
}
int main(){
    read(n);
    for(int i=1;i<=n;++i){
        fa[i]=i;
        sz[i]=1;
    }
    for(int i=1;i<n;++i){
        read(e[i].u),read(e[i].v),read(e[i].w);
        g[e[i].w].push_back({e[i].u,e[i].v});
    }
    cout<<dfs(1,n);
    return 0;
}
原文
存档评论3 条抓取于