luogu P12274 题解

· · 题解

P12274 [蓝桥杯 2024 国 Python B] 设计 | 题目传送

前置知识:并查集、栈

思路:

首先看到操作 1 和操作 3 不难想到要用并查集。 但是操作 2 可以撤销,因此每次进行操作 1 时若合并了 x,y 结点,即 fa_{find(x)} \gets find(y) 时,可以维护此时的 find(x) ,到操作 2 时再将 fa_{find(x)} \gets find(x) 就可以实现操作 2 的效果。

注意到,先修建的边一定比后修建的边晚撤销

也就是说,我们需要用来维护 find(x) 的数据结构要满足先进后出的性质

很容易想到用栈了,代码很好写,但要注意两点:

  1. 写 find 函数时不能路径压缩!否则进行操作 2 时只会将 x 结点断开连接,不会将 x 的子节点断开!

  2. 写并查集连边时,注意当 find(x) = find(y) 时,也要将 find(x) 压入栈里!

于是便有了高达 90 pts 的代码:

#include <bits/stdc++.h>
using namespace std;

int n,m,f[900005];
stack <int> st; 

int fd(int x) {
    if (f[x] == x) return x;
    return fd(f[x]);
}

void merge(int x,int y) {
    int fx = fd(x),fy = fd(y);
    f[fx] = fy;
    st.push(fx);
}

int query(int x,int y) {
    return fd(x) == fd(y);
}

void undo(int x) {
    while (!st.empty() && x--) {
        int k = st.top();
        st.pop();
        int t = f[k];
        f[k] = k;
    }
}



int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        f[i] = i;
    } 
    while (m--) {
        int op,x,y;
        cin >> op;
        if (op == 1) {
            cin >> x >> y;
            merge(x,y);
        } else if (op == 2) {
            undo(1);
        } else {
            cin >> x >> y;
            cout << ((query(x,y)) ? "Yes\n" : "No\n");
        }
    }
    return 0;
}
记录:https://www.luogu.com.cn/record/230808485

为啥会T呢?

这是因为我们把并查集路径合并给删了,变成了朴素的并查集,因此考虑优化并查集。

不难看到在前置知识并查集往下稍微一翻就可以找到启发式合并,也就是按秩合并。(将结点个数小的连接到结点个数大的)

又看到下面一句话:

如果只使用启发式合并,而不使用路径压缩,时间复杂度为 O(m \log n)。

因此我们可以再维护并查集中每个点所在的树的大小 sz_i,合并时再将 sz 小的合并到大的即可。

AC 代码:

#include <bits/stdc++.h>
using namespace std;

int n,m,f[900005],sz[900005];
stack <int> st; 

int fd(int x) {
    if (f[x] == x) return x;
    return fd(f[x]);
}

void merge(int x,int y) {
    int fx = fd(x),fy = fd(y);
    if (sz[fx] > sz[fy]) swap(fx,fy); // 按秩合并 
    f[fx] = fy;
    if (fx != fy) sz[fy] += sz[fx];
    st.push(fx);
}

int query(int x,int y) {
    return fd(x) == fd(y);
}

void undo(int x) {
    while (!st.empty() && x--) {
        int k = st.top();
        st.pop();
        int t = f[k];
        if (fd(t) != fd(k)) sz[t] -= sz[k];
        f[k] = k;
    }
}



int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        f[i] = i;
        sz[i] = 1;
    } 
    while (m--) {
        int op,x,y;
        cin >> op;
        if (op == 1) {
            cin >> x >> y;
            merge(x,y);
        } else if (op == 2) {
            undo(1);
        } else {
            cin >> x >> y;
            cout << ((query(x,y)) ? "Yes\n" : "No\n");
        }
    }
    return 0;
}

记录:https://www.luogu.com.cn/record/230827157

(成功抢到最优解的第17名)