树分块 树上莫队

· · 个人记录

参考博客: 莫队、带修莫队、树上莫队详解

树分块

这里介绍三种分块方法

这样分块是为了莫队的排序,使在两个查询间转移时只需进行 \sqrt N 数量级的操作。

P2325 [SCOI2005]王室联邦

Description

题目链接

Solution

Code

#include <bits/stdc++.h>

using namespace std;

const int MAXN = 1e3 + 5;

int n, b, ans, u, v;
int p[MAXN], pro[MAXN], belong[MAXN];

template <class T>
void read(T &x, T f = 1, char ch = getchar()) {
    x = 0;
    while (ch < '0' || ch > '9') f = (ch == '-' ? -1 : 1), ch = getchar();
    while (ch >= '0' && ch <= '9') x = x * 10 + ch - 48, ch = getchar();
    x *= f;
}

struct edge {
    int to, nxt;
} e[MAXN << 1];

void addEdge(int from, int to) {
    static int t;
    e[t].to = to, e[t].nxt = p[from], p[from] = t++;
}

stack<int> s;
void dfs(int now, int fa) {
    int tmp = s.size();
    for (int i = p[now]; ~i; i = e[i].nxt) {
        int to = e[i].to;
        if (to != fa) {
            dfs(to, now);
            if (s.size() - tmp >= b) {
                pro[++ans] = now;
                while (s.size() > tmp) {
                    int cur = s.top();
                    s.pop();
                    belong[cur] = ans;
                }
            }
        }
    }
    s.push(now);
}

int main() {
    read(n), read(b);
    fill(p, p + n + 1, -1);
    for (int i = 1; i <= n - 1; i++) {
        read(u), read(v);
        addEdge(u, v), addEdge(v, u);
    }
    dfs(1, 1);
    if (!ans) pro[++ans] = 1;
    while (!s.empty()) {
        int tmp = s.top();
        s.pop();
        belong[tmp] = ans;
    }
    printf("%d\n", ans);
    for (int i = 1; i <= n; i++) printf("%d ", belong[i]);
    printf("\n");
    for (int i = 1; i <= ans; i++) printf("%d ", pro[i]);
    return 0;
}

普通树上莫队

SP10707 COT2 - Count on a tree II

Description

题目链接

Solution1

采用王室联邦分块法。对于所有询问 \{(u_i,v_i)\},按 u_i 所属块编号从小到大排序,若 u_i 所属块相同按 v_i 所属块编号从小到大排序。至于奇偶性优化...也许有点用,还是加上吧。

接下来两个查询间如何转移。设 S_{u,v} 为路径 u-v 上的所有点的集合,T_{u,v}表示路径 u-v 上的除 lca(u,v) 外的点构成的集合。设上一次询问为 (u,v),本次询问为 (u',v')。那么上一次询问涉及到的节点为 S_{u,v}=T_{u,v}∪lca(u,v),本次询问涉及到的节点为 S_{u',v'}=T_{u',v'}∪lca(u',v')。定义 ⊕ 表示集合的对称差运算,由 ⊕ 的交换律和结合律,有:

T_{u',v'}=T_{u',v'}⊕T_{u,v}⊕T_{v,u} =(S_{u',rt}⊕S_{rt,v'})⊕(S_{u,rt}⊕S_{rt,v})⊕T_{u,v} =(S_{u',rt}⊕S_{u,rt})⊕(S_{rt,v}⊕S_{rt,v'})⊕T_{u,v} =T_{u,u'}⊕T_{v,v'}⊕T_{u,v} =T_{u,u'}⊕T_{v,v'}⊕S_{u,v}⊕lca(u,v) = S_{u',v'}⊕lca(u',v')

移项可得:S_{u',v'}=lca(u',v')⊕lca(u,v)⊕T_{u,u'}⊕T_{v,v'}⊕S_{u,v}

求 lca 可用树链剖分(相比倍增常数小),在 dfs 分块时可顺便维护。 对于异或操作,可用一个数组记录每个节点是否在集合中。每更新一个节点,若其在集合中则将相应数值删除,否则加入集合。至于 T_{u,u'} 和 T_{v,v'},分别直接遍历整个链,更新直至 lca 处停止即可。

Code1

#include <bits/stdc++.h>

using namespace std;

const int MAXN = 1e5 + 5;

int n, m, B, cntB, tot;
int val[MAXN], p[MAXN], belong[MAXN], ans[MAXN], cntC[MAXN];
int hson[MAXN], sz[MAXN], dep[MAXN], f[MAXN], top[MAXN];
bool vis[MAXN];
vector<int> v;

template <class T>
void read(T &x, T f = 1, char ch = getchar()) {
    x = 0;
    while (ch < '0' || ch > '9') f = (ch == '-' ? -1 : 1), ch = getchar();
    while (ch >= '0' && ch <= '9') x = x * 10 + ch - 48, ch = getchar();
    x *= f;
}

struct Edge {
    int to, nxt;
} e[MAXN * 2];

struct Query {
    int x, y, id;
    friend bool operator<(const Query &a, const Query &b) {
        if (belong[a.x] == belong[b.x]) {
            if (belong[a.x] & 1) return belong[a.y] < belong[b.y];
            return belong[a.y] > belong[b.y];
        }
        return belong[a.x] < belong[b.x];
    }
} q[MAXN * 3];

void addEdge(int from, int to) {
    static int t;
    e[t].to = to, e[t].nxt = p[from], p[from] = t++;
}

stack<int> s;
void dfs(int now, int fa) {
    sz[now] = 1, dep[now] = dep[fa] + 1, f[now] = fa;
    int tmp = s.size();
    for (int i = p[now]; ~i; i = e[i].nxt) {
        int to = e[i].to;
        if (to != fa) {
            dfs(to, now);
            sz[now] += sz[to];
            if (!hson[now] || sz[to] > sz[hson[now]]) hson[now] = to;
            if (s.size() - tmp >= B) {
                cntB++;
                while (s.size() > tmp) {
                    int cur = s.top();
                    s.pop();
                    belong[cur] = cntB;
                }
            }
        }
    }
    s.push(now);
}

void dfs2(int now, int tp) {
    top[now] = tp;
    if (!hson[now]) return;
    dfs2(hson[now], tp);
    for (int i = p[now]; ~i; i = e[i].nxt) {
        int to = e[i].to;
        if (to != f[now] && to != hson[now]) dfs2(to, to);
    }
}

int lca(int u, int v) {
    if (dep[top[u]] < dep[top[v]]) swap(u, v);
    while (top[u] != top[v]) {
        u = f[top[u]];
        if (dep[top[u]] < dep[top[v]]) swap(u, v);
    }
    if (dep[u] < dep[v]) swap(u, v);
    return v;
}

void getBlock() {
    B = sqrt(n);
    dfs(1, 1);
    dfs2(1, 1);
    if (!cntB) ++cntB;
    while (!s.empty()) {
        int tmp = s.top();
        s.pop();
        belong[tmp] = cntB;
    }
}

void discretize() {
    sort(v.begin(), v.end());
    for (int i = 1; i <= n; i++)
        val[i] = lower_bound(v.begin(), v.end(), val[i]) - v.begin() + 1;
}

void modify(int now) {
    if (!vis[now]) {
        ++cntC[val[now]];
        if (cntC[val[now]] == 1) tot++;
    } else {
        --cntC[val[now]];
        if (cntC[val[now]] == 0) tot--;
    }
    vis[now] ^= 1;
}

void update(int u, int v) {
    if (dep[u] < dep[v]) swap(u, v);
    while (dep[u] > dep[v]) modify(u), u = f[u];
    while (u != v) modify(u), modify(v), u = f[u], v = f[v];
}

int main() {
    read(n), read(m);
    for (int i = 1; i <= n; i++) read(val[i]), v.push_back(val[i]);
    discretize();
    fill(p + 1, p + n + 1, -1);
    int x(0), y(0);
    for (int i = 1; i <= n - 1; i++) {
        read(x), read(y);
        addEdge(x, y), addEdge(y, x);
    }
    getBlock();
    for (int i = 1; i <= m; i++) {
        read(q[i].x), read(q[i].y);
        q[i].id = i;
    }
    sort(q + 1, q + m + 1);
    x = 1, y = 1;
    modify(1);
    for (int i = 1; i <= m; i++) {
        int lca1 = lca(x, y), lca2 = lca(q[i].x, q[i].y);
        update(x, q[i].x), x = q[i].x;
        update(y, q[i].y), y = q[i].y;
        modify(lca1), modify(lca2);
        ans[q[i].id] = tot;
    }
    for (int i = 1; i <= m; i++) printf("%d\n", ans[i]);
    return 0;
}

Solution2

考虑把树上的问题转化到序列上。

这里引入欧拉序,它的思想是:当访问到点i 时,加入序列,记录时间戳 in[i],然后访问 i 的子树,当访问完时,再把 i 加入序列,并记录时间戳 out[i]。如果将一条链映射到序列中的一段区间,那么这个区间中出现两次的节点一定不属于这条链(两端点的 lca)除外, 这样只需要统计出现一次的节点即可。

对于一条链 (u,v),设 in[u]<in[v],讨论两种情况:

注:

Code2

#include <bits/stdc++.h>

using namespace std;

const int MAXN = 1e5 + 5;

int n, m, B, tot;
int val[MAXN], p[MAXN], in[MAXN], out[MAXN], from[MAXN * 2];
int belong[MAXN * 2], ans[MAXN], cntC[MAXN];
int hson[MAXN], sz[MAXN], dep[MAXN], f[MAXN], top[MAXN];
bool vis[MAXN];
vector<int> v;

template <class T>
void read(T &x, T f = 1, char ch = getchar()) {
    x = 0;
    while (ch < '0' || ch > '9') f = (ch == '-' ? -1 : 1), ch = getchar();
    while (ch >= '0' && ch <= '9') x = x * 10 + ch - 48, ch = getchar();
    x *= f;
}

struct Edge {
    int to, nxt;
} e[MAXN * 2];

struct Query {
    int l, r, id, lca;
    friend bool operator<(const Query &a, const Query &b) {
        if (belong[a.l] == belong[b.l]) {
            if (belong[a.l] & 1) return belong[a.r] < belong[b.r];
            return belong[a.r] > belong[b.r];
        }
        return belong[a.l] < belong[b.l];
    }
} q[MAXN * 3];

void addEdge(int from, int to) {
    static int t;
    e[t].to = to, e[t].nxt = p[from], p[from] = t++;
}

void dfs(int now, int fa) {
    static int tim = 1;
    in[now] = tim, from[tim++] = now;
    sz[now] = 1, dep[now] = dep[fa] + 1, f[now] = fa;
    for (int i = p[now]; ~i; i = e[i].nxt) {
        int to = e[i].to;
        if (to != fa) {
            dfs(to, now);
            sz[now] += sz[to];
            if (!hson[now] || sz[to] > sz[hson[now]]) hson[now] = to;
        }
    }
    out[now] = tim, from[tim++] = now;
}

void dfs2(int now, int tp) {
    top[now] = tp;
    if (!hson[now]) return;
    dfs2(hson[now], tp);
    for (int i = p[now]; ~i; i = e[i].nxt) {
        int to = e[i].to;
        if (to != f[now] && to != hson[now]) dfs2(to, to);
    }
}

int lca(int u, int v) {
    if (dep[top[u]] < dep[top[v]]) swap(u, v);
    while (top[u] != top[v]) {
        u = f[top[u]];
        if (dep[top[u]] < dep[top[v]]) swap(u, v);
    }
    if (dep[u] < dep[v]) swap(u, v);
    return v;
}

void discretize() {
    sort(v.begin(), v.end());
    for (int i = 1; i <= n; i++)
        val[i] = lower_bound(v.begin(), v.end(), val[i]) - v.begin() + 1;
}

void modify(int now) {
    if (!vis[now]) {
        ++cntC[val[now]];
        if (cntC[val[now]] == 1) tot++;
    } else {
        --cntC[val[now]];
        if (cntC[val[now]] == 0) tot--;
    }
    vis[now] ^= 1;
}

int main() {
    read(n), read(m);
    for (int i = 1; i <= n; i++) read(val[i]), v.push_back(val[i]);
    discretize();
    fill(p + 1, p + n + 1, -1);
    int x(0), y(0);
    for (int i = 1; i <= n - 1; i++) {
        read(x), read(y);
        addEdge(x, y), addEdge(y, x);
    }
    B = max(1, 2 * n / (int)sqrt(m));
    dfs(1, 1), dfs2(1, 1);
    for (int i = 1; i <= m; i++) {
        read(x), read(y);
        if (in[x] > in[y]) swap(x, y);
        q[i].lca = lca(x, y);
        if (q[i].lca == x) {
            q[i].l = in[x];
            q[i].r = in[y];
            q[i].lca = 0;
        } else {
            q[i].l = out[x];
            q[i].r = in[y];
        }
        q[i].id = i;
    }
    for (int i = 1; i <= 2 * n; i++) belong[i] = (i - 1) / B + 1;
    sort(q + 1, q + m + 1);
    x = 1, y = 0;
    for (int i = 1; i <= m; i++) {
        while (x < q[i].l) modify(from[x++]);
        while (x > q[i].l) modify(from[--x]);
        while (y > q[i].r) modify(from[y--]);
        while (y < q[i].r) modify(from[++y]);
        if (q[i].lca) modify(q[i].lca);
        ans[q[i].id] = tot;
        if (q[i].lca) modify(q[i].lca);
    }
    for (int i = 1; i <= m; i++) printf("%d\n", ans[i]);
    return 0;
}

注:本题有在线做法,以后有空再补上。

树上带修莫队

处理方法和序列上的莫队相同,对每个询问增加一维时间。

P4074 [WC2013]糖果公园

Description

题目链接

Hint

记录每个询问之前的修改次数,排序的时候以修改次数为第三关键字排序即可。查询的时候,如果多修改了则回退,否则对未修改的部分进行修改,当修改位置在本次查询区间内时对答案进行更新。

Solution1

求欧拉序后转化为区间问题。

Code1

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

const int MAXN = 1e5 + 5;
int n, m, Q, B, type, cntQ, cntR;
int C[MAXN], V[MAXN], W[MAXN];
ll tot, ans[MAXN];
int p[MAXN], in[MAXN], out[MAXN], from[MAXN * 2];
int belong[MAXN * 2], cntC[MAXN];
int hson[MAXN], sz[MAXN], dep[MAXN], f[MAXN], top[MAXN];
bool vis[MAXN];

template <class T>
void read(T &x, T f = 1, char ch = getchar()) {
    x = 0;
    while (ch < '0' || ch > '9') f = (ch == '-' ? -1 : 1), ch = getchar();
    while (ch >= '0' && ch <= '9') x = x * 10 + ch - 48, ch = getchar();
    x *= f;
}

struct Edge {
    int to, nxt;
} e[MAXN * 2];

struct Query {
    int l, r, id, lca, t;
    friend bool operator<(const Query &a, const Query &b) {
        if (belong[a.l] == belong[b.l]) {
            if (belong[a.r] == belong[b.r]) return a.t < b.t;
            if (belong[a.l] & 1) return belong[a.r] < belong[b.r];
            return belong[a.r] > belong[b.r];
        }
        return belong[a.l] < belong[b.l];
    }
} q[MAXN];

struct Replace {
    int id, type;
} r[MAXN];

void addEdge(int from, int to) {
    static int t;
    e[t].to = to, e[t].nxt = p[from], p[from] = t++;
}

void dfs(int now, int fa) {
    static int tim = 1;
    in[now] = tim, from[tim++] = now;
    sz[now] = 1, dep[now] = dep[fa] + 1, f[now] = fa;
    for (int i = p[now]; ~i; i = e[i].nxt) {
        int to = e[i].to;
        if (to != fa) {
            dfs(to, now);
            sz[now] += sz[to];
            if (!hson[now] || sz[to] > sz[hson[now]]) hson[now] = to;
        }
    }
    out[now] = tim, from[tim++] = now;
}

void dfs2(int now, int tp) {
    top[now] = tp;
    if (!hson[now]) return;
    dfs2(hson[now], tp);
    for (int i = p[now]; ~i; i = e[i].nxt) {
        int to = e[i].to;
        if (to != f[now] && to != hson[now]) dfs2(to, to);
    }
}

int lca(int u, int v) {
    if (dep[top[u]] < dep[top[v]]) swap(u, v);
    while (top[u] != top[v]) {
        u = f[top[u]];
        if (dep[top[u]] < dep[top[v]]) swap(u, v);
    }
    if (dep[u] < dep[v]) swap(u, v);
    return v;
}

void modify(int now) {
    if (!vis[now]) {
        ++cntC[C[now]];
        tot += 1ll * W[cntC[C[now]]] * V[C[now]];
    } else {
        tot -= 1ll * W[cntC[C[now]]] * V[C[now]];
        --cntC[C[now]];
    }
    vis[now] ^= 1;
}

void change(Replace &rep) {
    if (vis[rep.id]) {
        modify(rep.id);
        swap(rep.type, C[rep.id]);
        modify(rep.id);
    } else
        swap(rep.type, C[rep.id]);
}

int main() {
    read(n), read(m), read(Q);
    fill(p + 1, p + n + 1, -1);
    for (int i = 1; i <= m; i++) read(V[i]);
    for (int i = 1; i <= n; i++) read(W[i]);
    int x, y, t;
    for (int i = 1; i <= n - 1; i++) {
        read(x), read(y);
        addEdge(x, y), addEdge(y, x);
    }
    for (int i = 1; i <= n; i++) read(C[i]);
    B = pow(n, 2.0 / 3);  //不要忘了.0!
    dfs(1, 1), dfs2(1, 1);
    for (int i = 1; i <= Q; i++) {
        read(type);
        if (type == 1) {
            cntQ++;
            read(x), read(y);
            if (in[x] > in[y]) swap(x, y);
            q[cntQ].lca = lca(x, y);
            if (q[cntQ].lca == x) {
                q[cntQ].l = in[x];
                q[cntQ].r = in[y];
                q[cntQ].lca = 0;
            } else {
                q[cntQ].l = out[x];
                q[cntQ].r = in[y];
            }
            q[cntQ].id = cntQ;
            q[cntQ].t = cntR;
        } else {
            cntR++;
            read(x), read(y);
            r[cntR].id = x, r[cntR].type = y;
        }
    }
    for (int i = 1; i <= 2 * n; i++) belong[i] = (i - 1) / B + 1;
    sort(q + 1, q + cntQ + 1);
    x = 1, y = 0, t = 0;
    for (int i = 1; i <= cntQ; i++) {
        while (x < q[i].l) modify(from[x++]);
        while (x > q[i].l) modify(from[--x]);
        while (y > q[i].r) modify(from[y--]);
        while (y < q[i].r) modify(from[++y]);
        while (t < q[i].t) change(r[++t]);
        while (t > q[i].t) change(r[t--]);
        if (q[i].lca) modify(q[i].lca);
        ans[q[i].id] = tot;
        if (q[i].lca) modify(q[i].lca);
    }
    for (int i = 1; i <= cntQ; i++) printf("%lld\n", ans[i]);
    return 0;
}

Solution2

采用王室联邦分块法。也许是我写假了,跑得巨慢...

Code2

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

const int MAXN = 1e5 + 5;
int n, m, Q, B, type, cntQ, cntR, cntB;
int C[MAXN], V[MAXN], W[MAXN];
ll tot, ans[MAXN];
int p[MAXN];
int belong[MAXN], cntC[MAXN];
int hson[MAXN], sz[MAXN], dep[MAXN], f[MAXN], top[MAXN];
bool vis[MAXN];

template <class T>
void read(T &x, T f = 1, char ch = getchar()) {
    x = 0;
    while (ch < '0' || ch > '9') f = (ch == '-' ? -1 : 1), ch = getchar();
    while (ch >= '0' && ch <= '9') x = x * 10 + ch - 48, ch = getchar();
    x *= f;
}

struct Edge {
    int to, nxt;
} e[MAXN * 2];

struct Query {
    int x, y, id, t;
    friend bool operator<(const Query &a, const Query &b) {
        if (belong[a.x] == belong[b.x]) {
            if (belong[a.y] == belong[b.y]) return a.t < b.t;
            if (belong[a.x] & 1) return belong[a.y] < belong[b.y];
            return belong[a.y] > belong[b.y];
        }
        return belong[a.x] < belong[b.x];
    }
} q[MAXN];

struct Replace {
    int id, type;
} r[MAXN];

void addEdge(int from, int to) {
    static int t;
    e[t].to = to, e[t].nxt = p[from], p[from] = t++;
}

stack<int> s;
void dfs(int now, int fa) {
    sz[now] = 1, dep[now] = dep[fa] + 1, f[now] = fa;
    int tmp = s.size();
    for (int i = p[now]; ~i; i = e[i].nxt) {
        int to = e[i].to;
        if (to != fa) {
            dfs(to, now);
            sz[now] += sz[to];
            if (!hson[now] || sz[to] > sz[hson[now]]) hson[now] = to;
            if (s.size() - tmp >= B) {
                cntB++;
                while (s.size() > tmp) {
                    int cur = s.top();
                    s.pop();
                    belong[cur] = cntB;
                }
            }
        }
    }
    s.push(now);
}

void dfs2(int now, int tp) {
    top[now] = tp;
    if (!hson[now]) return;
    dfs2(hson[now], tp);
    for (int i = p[now]; ~i; i = e[i].nxt) {
        int to = e[i].to;
        if (to != f[now] && to != hson[now]) dfs2(to, to);
    }
}

int lca(int u, int v) {
    if (dep[top[u]] < dep[top[v]]) swap(u, v);
    while (top[u] != top[v]) {
        u = f[top[u]];
        if (dep[top[u]] < dep[top[v]]) swap(u, v);
    }
    if (dep[u] < dep[v]) swap(u, v);
    return v;
}

void getBlock() {
    B = sqrt(n);
    dfs(1, 1);
    dfs2(1, 1);
    if (!cntB) ++cntB;
    while (!s.empty()) {
        int tmp = s.top();
        s.pop();
        belong[tmp] = cntB;
    }
}

void modify(int now) {
    if (!vis[now]) {
        ++cntC[C[now]];
        tot += 1ll * W[cntC[C[now]]] * V[C[now]];
    } else {
        tot -= 1ll * W[cntC[C[now]]] * V[C[now]];
        --cntC[C[now]];
    }
    vis[now] ^= 1;
}

void update(int u, int v) {
    if (dep[u] < dep[v]) swap(u, v);
    while (dep[u] > dep[v]) modify(u), u = f[u];
    while (u != v) modify(u), modify(v), u = f[u], v = f[v];
}

void change(Replace &rep) {
    if (vis[rep.id]) {
        modify(rep.id);
        swap(rep.type, C[rep.id]);
        modify(rep.id);
    } else
        swap(rep.type, C[rep.id]);
}

int main() {
    read(n), read(m), read(Q);
    fill(p + 1, p + n + 1, -1);
    for (int i = 1; i <= m; i++) read(V[i]);
    for (int i = 1; i <= n; i++) read(W[i]);
    int x, y, t;
    for (int i = 1; i <= n - 1; i++) {
        read(x), read(y);
        addEdge(x, y), addEdge(y, x);
    }
    for (int i = 1; i <= n; i++) read(C[i]);
    B = pow(n, 2.0 / 3);
    getBlock();
    for (int i = 1; i <= Q; i++) {
        read(type);
        if (type == 1) {
            cntQ++;
            read(x), read(y);
            q[cntQ].x = x, q[cntQ].y = y;
            q[cntQ].id = cntQ;
            q[cntQ].t = cntR;
        } else {
            cntR++;
            read(x), read(y);
            r[cntR].id = x, r[cntR].type = y;
        }
    }
    sort(q + 1, q + cntQ + 1);
    x = 1, y = 1, t = 0;
    modify(1);
    for (int i = 1; i <= cntQ; i++) {
        int lca1 = lca(x, y), lca2 = lca(q[i].x, q[i].y);
        update(x, q[i].x), x = q[i].x;
        update(y, q[i].y), y = q[i].y;
        modify(lca1), modify(lca2);
        while (t < q[i].t) change(r[++t]);
        while (t > q[i].t) change(r[t--]);
        ans[q[i].id] = tot;
    }
    for (int i = 1; i <= cntQ; i++) printf("%lld\n", ans[i]);
    return 0;
}