P7215 [JOISC 2020] 首都 点分治好题

· · 个人记录

好久没打点分治了。一眨眼,第一次学点分治还是在两年前成外集训的时候,那时我才刚接触OI一年啊

对于这道题,应优先考虑暴力处理这么搞(做题的基本思路了)。考虑固定一个点为树的根并且选定该点的颜色,考虑进行颜色上的广搜,每次遍历已经加入队列颜色的点,从该点像父节点跳,不断加入新的颜色,如果遇到已经遍历过的点就不跳了(一个优化,显然再往上的都遍历过,再跳就多余了)。最后答案就是颜色队列长度减一

这题里点分治的巧妙优化真的让我感到瞬间通透!

考虑进行点分治处理上述的暴力过程,对于一个连通块,如果我搜到了该联通块以外的点,直接退出不再处理。为什么呢?因为如果存在连通块以外的点,根据点分治的过程可以知道,从那个点到当前的根,一定经过之前点分治时处理的根,那么之前的那个根也会被加进队列算答案。那么本次查询的答案显然不优于之前那次所查询的答案!!!这个性质直接决定了可进行点分治!!!

code

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 200010;
int n, K, c[N], rt, all, siz[N], mx[N], fm[N], fa[N], ps[N], vs[N], vis[N], ans = 1e18;
vector <int> col[N], v[N];
void get_root(int dad, int x) {
    siz[x] = 1, mx[x] = 0;
    for (auto i : v[x]) {
        if (i == dad || vis[i]) continue;
        get_root(x, i);
        siz[x] += siz[i];
        mx[x] = max(mx[x], siz[i]);
    }
    mx[x] = max(mx[x], all - siz[x]);
    if (mx[x] < mx[rt]) rt = x;
}
void get_tree(int dad, int x, int tp) {
    fm[x] = tp, fa[x] = dad;
    for (auto i : v[x]) {
        if (i == dad || vis[i]) continue;
        get_tree(x, i, tp);
    }
}
void solve(int x) {
    get_tree(0, x, x);
    queue <int> q;
    q.push(c[x]), vs[c[x]] = x, ps[x] = x;
    int now = 0;
    while (q.size()) {
        int op = q.front();
        q.pop();
        bool bl = 1;
        for (auto i : col[op]) {
            if (fm[i] != x) {bl = 0; break;}
        }
        if (!bl) return ;
        now++;
        for (auto i : col[op]) {
            int tmp = i;
            while (ps[tmp] != x) {
                ps[tmp] = x;
                if (vs[c[tmp]] != x) {
                    vs[c[tmp]] = x;
                    q.push(c[tmp]);
                }
                tmp = fa[tmp];
            }
        }
    }
    ans = min(ans, now - 1);
}
void dfz(int x) {
    solve(x);
    vis[x] = 1;
    for (auto i : v[x]) {
        if (!vis[i]) {
            all = siz[i], rt = 0;
            get_root(0, i);
            get_root(0, rt);
            dfz(rt);
        }
    }
}
signed main() {
    cin >> n >> K;
    for (int i = 1, x, y; i < n; i++) {
        scanf("%lld%lld", &x, &y);
        v[x].push_back(y);
        v[y].push_back(x);
    }
    for (int i = 1; i <= n; i++) {
        scanf("%lld", &c[i]);
        col[c[i]].push_back(i);
    }
    all = n, rt = 0, mx[0] = 1e18;
    get_root(0, 1);
    get_root(0, rt);
    dfz(rt);
    cout << ans;
}