跳到正文

算法·理论

树上莫队

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

文章信息

发布
2026年7月19日
收录
2026年7月19日
更新
2026年11月15日
篇幅
约 16 分钟
获赞
1

版本

  1. v1当前

以常理来讲,莫队只能解决线性序列上的区间问题。

树上莫队秉承这样的思想,只是把树压成了序列去跑莫队。

例题SP10707 COT2 - Count on a tree II

题目大意

你需要回答若干组询问,求从一个节点到另一个节点的最短路径上,有多少种不同的点权。

“把树压成序列”?这题我会,dfs 序啊。

这棵树的 dfs 序为 1 2 4 7 5 3 6 8 9 10 11。

路径 5 → 6 上的节点:5 2 1 3 6。

对应 dfs 序上的区间:玄学。

不大行。

这里介绍一种新序列:欧拉序,又称括号序列。

还是这棵树。

欧拉序:1 2 4 7 7 4 5 5 2 3 6 8 9 9 10 10 11 11 8 6 3 1。

这是个什么东西?!它怎么求得的暂且不谈(不过你一看也应该已经知道了),先看看它的性质:

我们看一看每个编号出现的次数——两次,无一例外。再看看它出现的两个位置有什么特点:

我们以编号 22 为例,它出现在位置 22 和 99,它中间的编号有两个 44,两个 77 和两个 55。

这些编号都是其子树上的结点。

就这样,我们得出它的一条性质:树的欧拉序上两个相同编号(设为 xx )之间的所有编号都出现两次,且都位于 xx 子树上。(前半句话其实可以由后半句话间接证明)

求欧拉序,对树 dfs,点进栈时记入欧拉序列和一个时间戳 firstfirst,出栈时再记入欧拉序列和一个时间戳 lastlast。

大佬都在用树剖求欧拉序,我不会 eee。

每次询问的节点 uu 和 vv 有两种情况。

vv 在 uu 的子树中,比如 u=1u=1,v=10v=10,我们拿出 (firstu,firstv)(first_u,first_v) 这段区间 (1,2,4,7,7,4,5,5,2,3,6,8,9,9,10)(1,2,4,7,7,4,5,5,2,3,6,8,9,9,10),22、44、77、55 出现了两次,因为它们搜索的时候不属于这条链,所以进去之后就出去了,而出现一次的都在这条链上,就都可以统计。

uu 和 vv 不在同一个子树中,保证 firstu<firstvfirst_u<first_v 的前提下(否则交换一下),比如 u=2u=2,v=6v=6,这次拿出 (lastu,firstv)(last_u,first_v) 这段区间(因为 (firstv,lastu)(first_v,last_u) 没用) (2,3,6)(2,3,6),然而这次只统计了 2,3,62,3,6,所以最后再统计上 u,vu,v 的 lca 就好了。

至于如何忽略掉区间内出现了两次的点,这个很简单,我们多记录一个 visxvis_x,表示 xx 这个点有没有被加入,每次处理的时候如果 visx=0vis_x=0 则需要添加节点;如果 visx=1vis_x=1 则需要删除节点,每次处理之后都对 visxvis_x 异或 11 就可以了。

代码,码风极为毒瘤 (倍增求 lca 可爱捏)。

C++
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
#define N 200200
#define isdigit(x) ((x) >= '0' && (x) <= '9')
inline int read() {
	int res = 0;
	char c = getchar();
	while(!isdigit(c)) c = getchar();
	while(isdigit(c)) res = (res << 1) + (res << 3) + (c ^ 48), c = getchar();
	return res;
}
int aa[N], cnt[N], first[N], last[N], ans[N], belong[N], inp[N], vis[N], ncnt, l = 1, r, now, size, bnum; 
int ord[N], val[N], head[N], depth[N], fa[N][30], ecnt;
int n, m;
struct edge {
	int to, next;
} e[N];
void adde(int u, int v) {
	e[++ecnt] = (edge){v, head[u]};
	head[u] = ecnt;
	e[++ecnt] = (edge){u, head[v]};
	head[v] = ecnt;
}
void dfs(int x) {
	ord[++ncnt] = x;
	first[x] = ncnt;
	for(int k = head[x]; k; k = e[k].next) {
		int to = e[k].to;
		if(to == fa[x][0]) continue;
		depth[to] = depth[x] + 1;
		fa[to][0] = x;
		for(int i = 1; (1 << i) <= depth[to]; ++i) fa[to][i] = fa[fa[to][i - 1]][i - 1];
		dfs(to);
	}
	ord[++ncnt] = x;
	last[x] = ncnt;
}
int getlca(int u, int v) {
	if(depth[u] < depth[v]) swap(u, v);
	for(int i = 20; i + 1; --i) 
		if(depth[u] - (1 << i) >= depth[v]) u = fa[u][i];
	if(u == v) return u;
	for(int i = 20; i + 1; --i)
		if(fa[u][i] != fa[v][i]) u = fa[u][i], v = fa[v][i];
	return fa[u][0];
}
struct query {
	int l, r, lca, id;
} q[N];
int cmp(query a, query b) {
	return (belong[a.l] ^ belong[b.l]) ? (belong[a.l] < belong[b.l]) : ((belong[a.l] & 1) ? a.r < b.r : a.r > b.r);
}
void work(int pos) {
	vis[pos] ? now -= !--cnt[val[pos]] : now += !cnt[val[pos]]++;
	vis[pos] ^= 1;
}
int main() {
	n = read(); m = read();
	for(int i = 1; i <= n; ++i) 
		val[i] = inp[i] = read();
	sort(inp + 1, inp + n + 1);
	int tot = unique(inp + 1, inp + n + 1) - inp - 1;
	for(int i = 1; i <= n; ++i)
		val[i] = lower_bound(inp + 1, inp + tot + 1, val[i]) - inp;
	for(int i = 1; i < n; ++i) adde(read(), read());
	depth[1] = 1;
	dfs(1);
	size = sqrt(ncnt), bnum = ceil((double) ncnt / size);
	for(int i = 1; i <= bnum; ++i)
		for(int j = size * (i - 1) + 1; j <= i * size; ++j) belong[j] = i;
	for(int i = 1; i <= m; ++i) {
		int L = read(), R = read(), lca = getlca(L, R);
		if(first[L] > first[R]) swap(L, R);
		if(L == lca) {
			q[i].l = first[L];
			q[i].r = first[R];
		}
		else {
			q[i].l = last[L];
			q[i].r = first[R];
			q[i].lca = lca;
		}
		q[i].id = i;
	}
	sort(q + 1, q + m + 1, cmp);
	for(int i = 1; i <= m; ++i) {
		int ql = q[i].l, qr = q[i].r, lca = q[i].lca;
		while(l < ql) work(ord[l++]);
		while(l > ql) work(ord[--l]);
		while(r < qr) work(ord[++r]);
		while(r > qr) work(ord[r--]);
		if(lca) work(lca);
		ans[q[i].id] = now;
		if(lca) work(lca);
	}
	for(int i = 1; i <= m; ++i) printf("%d\n", ans[i]);
	return 0;
}

相关练习:

1.P4074 [WC2013] 糖果公园

这题要结合我讲的树上莫队和 djr dalao 讲的带修莫队。

参考代码。

C++
#include<bits/stdc++.h>
using namespace std;
#define N 300500
#define ll long long
int cnt[N], aa[N], belong[N], inp[N], n, m, Q, ncnt, size, bnum, w[N], v[N], ccnt, qcnt;
int val[N], fa[N][30], depth[N], head[N], ecnt;
int fir[N], la[N], vis[N];
int l = 1, r = 0, t = 0;
ll now, ans[N];
struct edge {
    int to, next;
} e[N];
void adde(int u, int v) {
    e[++ecnt] = (edge){v, head[u]};
    head[u] = ecnt;
    e[++ecnt] = (edge){u, head[v]};
    head[v] = ecnt;
}
void dfs(int x) {
    aa[++ncnt] = x;
    fir[x] = ncnt;
    for(int k = head[x]; k; k = e[k].next) {
        int to = e[k].to;
        if(depth[to]) continue;
        depth[to] = depth[x] + 1;
        fa[to][0] = x;
        for(int i = 1; (1 << i) <= depth[to]; ++i) fa[to][i] = fa[fa[to][i - 1]][i - 1];
        dfs(to);
    }
    aa[++ncnt] = x;
    la[x] = ncnt;
}
int getlca(int u, int v) {
    if(depth[u] < depth[v]) swap(u, v);
    for(int i = 20; i + 1; --i) if(depth[fa[u][i]] >= depth[v]) u = fa[u][i];
    if(u == v) return u;
    for(int i = 20; i + 1; --i) if(fa[u][i] != fa[v][i]) u = fa[u][i], v = fa[v][i];
    return fa[u][0];
}
struct query {
    int l, r, id, lca, t;
} q[N];
int cmp(query a, query b) {
    return (belong[a.l] ^ belong[b.l]) ? belong[a.l] < belong[b.l] : ((belong[a.r] ^ belong[b.r]) ? belong[a.r] < belong[b.r] : a.t < b.t );
}
inline void add(int pos) {
    now += 1ll * v[val[pos]] * w[++cnt[val[pos]]];
}
inline void del(int pos) {
    now -= 1ll * v[val[pos]] * w[cnt[val[pos]]--];
}
inline void work(int pos) {
    vis[pos] ? del(pos) : add(pos);
    vis[pos] ^= 1;
}
struct change {
    int pos, val;
} ch[N];
void modify(int x) {
	if(vis[ch[x].pos]) {
		work(ch[x].pos);
		swap(val[ch[x].pos], ch[x].val);
		work(ch[x].pos);
	}
	else swap(val[ch[x].pos], ch[x].val);
}
#define isdigit(x) ((x) >= '0' && (x) <= '9')
inline int read() {
    int res = 0;
    char c = getchar();
    while(!isdigit(c)) c = getchar();
    while(isdigit(c)) res = (res << 1) + (res << 3) + (c ^ 48), c = getchar();
    return res;
}
int main() {
    n = read(), m = read(), Q = read();
    for(int i = 1; i <= m; ++i) v[i] = read();
    for(int i = 1; i <= n; ++i) w[i] = read();
    for(int i = 1; i < n; ++i) {
        int u = read(), v = read();
        adde(u, v);
    }
    for(int i = 1; i <= n; ++i) val[i] = read();
    depth[1] = 1;
    dfs(1);
    size = pow(ncnt, 2.0 / 3.0);
    bnum = ceil((double)ncnt / size);
    for(int i = 1; i <= bnum; ++i)
    	for(int j = size * (i - 1) + 1; j <= i * size; ++j) belong[j] = i;
    for(int i = 1; i <= Q; ++i) {
    	int opt = read(), a = read(), b = read();
    	if(opt) {
    		int lca = getlca(a, b);
    		q[++qcnt].t = ccnt;
    		q[qcnt].id = qcnt;
    		if(fir[a] > fir[b]) swap(a, b);
    		if(a == lca) q[qcnt].l = fir[a], q[qcnt].r = fir[b];
    		else q[qcnt].l = la[a], q[qcnt].r = fir[b], q[qcnt].lca = lca;
		}
		else {
			ch[++ccnt].pos = a;
			ch[ccnt].val = b;
		}
	}
	sort(q + 1, q + qcnt + 1, cmp);
	for(int i = 1; i <= qcnt; ++i) {
		int ql = q[i].l, qr = q[i].r, qt = q[i].t, qlca = q[i].lca;
		while(l < ql) work(aa[l++]);
		while(l > ql) work(aa[--l]);
		while(r < qr) work(aa[++r]);
		while(r > qr) work(aa[r--]);
		while(t < qt) modify(++t);
		while(t > qt) modify(t--);
		if(qlca) work(qlca);
		ans[q[i].id] = now;
		if(qlca) work(qlca);
	}
	for(int i = 1; i <= qcnt; ++i) printf("%lld\n", ans[i]);
	return 0;
}

2.P9329 [JOIST 2023] 两种货币 / Two Currencies

莫队可以作为主席树的下位替代。

原文