跳到正文

个人记录

一种神奇的树剖-线段树写法

Pizar约 17 分钟
原文
文章信息与版本

文章信息

发布
2026年11月28日
收录
2026年12月2日
更新
2026年12月2日
篇幅
约 17 分钟

版本

  1. v1当前

一种神奇的树剖-线段树写法,可以做到 O(log⁡n)O(\log n) 链加链查询。

设 w(x)=siz[x]−siz[son[x]]w(x) = siz[x] - siz[son[x]],也即其轻子树大小和 +1+1。

考虑对每条重链分别开一棵线段树,对于线段树上节点 [l,r][l,r],我们采取按权值中位数的方式划分。

具体的,令 sum(x,y)=∑x≤i≤yw(dfn(i))sum(x,y) = \sum\limits_{x \le i \le y} w(dfn(i)),我们找到第一个满足 sum(l,j)×2>sum(l,r)sum(l,j) \times 2 > sum(l,r) 的点 jj。

若 j=lj=l 则将其分成 [l,j][l,j] 和 [j+1,r][j+1,r],否则分成 [l,j−1][l,j-1] 和 [j,r][j,r]。

考虑在当前分法下单点操作的代价,我们注意到每两次操作一定可以使其走到叶子或权值和减半,具体的:

  • 若第一次分到了左边,则一定满足一次权值和减半或直接走到叶子。
  • 若第一次分到了右边,考虑右边划分的新左区间和新右区间。
  • 若走到了新右区间,则新左区间至少包含 jj,而 sum(l,j)sum(l,j) 就已经大于权值和的一半,所以新右区间权值和至少减半。
  • 若走到了新左区间,若新左区间是单点则走到了叶子,否则新左区间不超过原右区间的一半,也就不超过原区间的一半,也即可以做到减半。

所以单点修改 xx 的代价就是令权值和从 sum(l,r)sum(l,r) 到 w(x)w(x) 的次数,也即 O(log⁡sumw(x))O(\log \frac {sum} {w(x)}),其中 sumsum 表示这条重链上的 ww 之和。

区间修改可以先考虑为前缀修改,然后每层只会递归到一个区间,于是代价是一样的。

考虑一段到根的修改:x1,⋯ ,xkx_1,\cdots,x_k,设 xix_i 对应的重链首为 hih_i,hih_i 对应的重链上 ww 之和为 sumisum_i。

则我们的代价可以写作:

∑i=1klog⁡sumiw(xi)\sum\limits_{i=1}^k \log \frac {sum_i} {w(x_i)}

=log⁡∏i=1ksumi∏i=1kw(xi)= \log \frac {\prod\limits_{i=1}^k sum_i} {\prod\limits_{i=1}^k w(x_i)}

=log⁡sum1wk+∑i=1k−1log⁡sumiw(xi+1)= \log \frac {sum_1} {w_k} + \sum\limits_{i=1}^{k-1} \log \frac {sum_i} {w(x_{i+1})}

我们注意到,hih_i 一定作为 xi+1x_{i+1} 的一个轻儿子,所以一定有 w(xi+1)≥sizhi≥sumiw(x_{i+1}) \ge siz_{h_i} \ge sum_{i},于是后面的东西每一项都 ≤0\le 0。

≤log⁡sum1wk\le \log \frac {sum_1} {w_k}

≤log⁡n\le \log n

所以这样修改 O(log⁡n)O(\log n) 条重链也是 O(log⁡n)O(\log n) 的。

比较适合只有链修改/查询的题,尤其适合 ddp。

一个比较优美的编号方式是,设当前点编号为 pp,分界点为 midmid。

由于线段树一定是一棵完美二叉树,所以左边有 mid−l+1mid-l+1 个叶子,则有 2×(mid−l+1)−12\times (mid-l+1)-1 个点,于是我们直接让左边从 p+1p+1 开始编号,右边从 p+2×(mid−l+1)p+2 \times (mid-l+1) 开始编号即可。

于是只需要记录一下 midmid 即可,不需要额外记录点的编号,现算即可。

给一个 P18107 的代码。

C++
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll inf=1e18;
const int N=2e5+5;
vector<int> e[N];
int n,q,v[N];
ll f[N][3];
void chkmax(ll &x,ll y){
	x=max(x,y);
}
struct mat{
	ll a[3][3];
};
ll max3(ll x,ll y,ll z){return max({x,y,z});}
inline mat operator*(const mat& a, const mat& b) {
    const auto& x = a.a;
    const auto& y = b.a;
    mat ret;
    ret.a[0][0]=max3(x[0][0] + y[0][0], x[0][1] + y[1][0], x[0][2] + y[2][0]);
    ret.a[0][1]=max3(x[0][0] + y[0][1], x[0][1] + y[1][1], x[0][2] + y[2][1]);
    ret.a[0][2]=max3(x[0][0] + y[0][2], x[0][1] + y[1][2], x[0][2] + y[2][2]);
    ret.a[1][0]=max3(x[1][0] + y[0][0], x[1][1] + y[1][0], x[1][2] + y[2][0]);
    ret.a[1][1]=max3(x[1][0] + y[0][1], x[1][1] + y[1][1], x[1][2] + y[2][1]);
    ret.a[1][2]=max3(x[1][0] + y[0][2], x[1][1] + y[1][2], x[1][2] + y[2][2]);
    ret.a[2][0]=max3(x[2][0] + y[0][0], x[2][1] + y[1][0], x[2][2] + y[2][0]);
    ret.a[2][1]=max3(x[2][0] + y[0][1], x[2][1] + y[1][1], x[2][2] + y[2][1]);
    ret.a[2][2]=max3(x[2][0] + y[0][2], x[2][1] + y[1][2], x[2][2] + y[2][2]);
    return ret;
}
int dfn[N],mp[N],cnt;
int dep[N],siz[N],son[N],fa[N],top[N],low[N];
int pre[N],rt[N];
mat get(int p);

namespace seg{
	struct node{
		int mid;
		mat s;
	}a[N<<1];

	void build(int p,int l,int r){
		if(l==r){
			a[p].s=get(dfn[l]);
			return;
		}
		int half=pre[l-1]+(pre[r]-pre[l-1])/2;
		int mid=max(l,int(upper_bound(pre+l,pre+r,half)-pre)-1);
		a[p].mid=mid;
		int ls=p+1,rs=p+2*(mid-l+1);
		build(ls,l,mid),build(rs,mid+1,r);
		a[p].s=a[rs].s*a[ls].s;
	}

	void init(){
		for(int i=1;i<=n;++i){
			int x=dfn[i];
			pre[i]=pre[i-1]+siz[x]-siz[son[x]];
		}
		int tot=1;
		for(int h=1;h<=n;++h)if(top[h]==h){
			// 链尾的点权直接作为行向量的初值。
			int l=mp[h],r=mp[low[h]]-1;
			if(l>r)continue;
			rt[h]=tot;
			build(tot,l,r);
			tot+=2*(r-l+1)-1;
		}
	}

	void mdf(int p,int l,int r,int idx,const mat &v){
		if(l==r){
			a[p].s=v;
			return;
		}
		int mid=a[p].mid,ls=p+1,rs=p+2*(mid-l+1);
		if(idx<=mid)mdf(ls,l,mid,idx,v);
		else mdf(rs,mid+1,r,idx,v);
		a[p].s=a[rs].s*a[ls].s;
	}

	void mdf(int x){
		if(!son[x])return;
		int h=top[x];
		mdf(rt[h],mp[h],mp[low[x]]-1,mp[x],get(x));
	}

	inline void mul(ll *f,const mat &s){
		ll x=f[0],y=f[1],z=f[2];
		f[0]=max3(x+s.a[0][0],y+s.a[1][0],z+s.a[2][0]);
		f[1]=max3(x+s.a[0][1],y+s.a[1][1],z+s.a[2][1]);
		f[2]=max3(x+s.a[0][2],y+s.a[1][2],z+s.a[2][2]);
	}

	// 查询 [L,R],按从右到左的顺序乘到 f 上。
	void qry(int p,int l,int r,int L,int R,ll *f){
		if(L<=l&&r<=R){
			mul(f,a[p].s);
			return;
		}
		int mid=a[p].mid,ls=p+1,rs=p+2*(mid-l+1);
		if(R>mid)qry(rs,mid+1,r,L,R,f);
		if(L<=mid)qry(ls,l,mid,L,R,f);
	}
}
struct Set{
	priority_queue<ll> q1,q2;
	void insert(ll x){q1.push(x);}
	void erase(ll x){q2.push(x);}
	bool empty(){return !(q1.size()-q2.size());}
	ll begin(){
		while(!q2.empty()&&q1.top()==q2.top()){q1.pop();q2.pop();}
		if(q1.empty())return 0;
		return q1.top();
	}
}st[N];
void dfs_build(int p){
	dep[p]=dep[fa[p]]+1;
	siz[p]=1;
	for(int t:e[p]){
		if(t==fa[p])continue;
		fa[t]=p;
		dfs_build(t);
		siz[p]+=siz[t];
		if(siz[son[p]]<siz[t])
			son[p]=t;
	}
}
void dfs_top(int p){
	dfn[++cnt]=p;
	mp[p]=cnt;
	top[p]=son[fa[p]]==p?top[fa[p]]:p;
	if(son[p]){
		dfs_top(son[p]);
		low[p]=low[son[p]];
	}
	else low[p]=p;
	for(int t:e[p])if(t!=son[p]&&t!=fa[p])
		dfs_top(t);
}
void dfs(int p,int fa){
	if(e[p].size()==1&&p!=1){
		f[p][0]=v[p];
		f[p][1]=f[p][2]=0;
		return;
	}
	ll s0=0,s1=0,s2=0;
	ll mx=0;
	for(int t:e[p]){
		if(t==fa)continue;
		dfs(t,p);
		s0+=f[t][0];
		s1+=f[t][1];
		s2+=f[t][2];
		mx=max(mx,f[t][0]-f[t][1]);
	}
	f[p][0]=v[p]+s2;
	f[p][1]=s1+mx;
	f[p][2]=s1;
}
ll g[N][3];
void init(int p){
	for(int t:e[p]){
		if(t==fa[p])continue;
		init(t);
		if(t!=son[p]){
			g[p][0]+=f[t][0];
			g[p][1]+=f[t][1];
			g[p][2]+=f[t][2];
			st[p].insert(f[t][0]-f[t][1]);
		}
	}
}
mat get(int p){
	mat ret;
	ll mx=(st[p].empty()?0:st[p].begin());
	mx=max(mx,0ll);
	
	ret.a[0][0]=-inf;
	ret.a[0][1]=g[p][1];
	ret.a[0][2]=-inf;
	
	ret.a[1][0]=-inf;
	ret.a[1][1]=g[p][1]+mx;
	ret.a[1][2]=g[p][1];
	
	ret.a[2][0]=v[p]+g[p][2];
	ret.a[2][1]=-inf;
	ret.a[2][2]=-inf;
	return ret;
}
void renew(int p){
	int h=top[p],bk=low[p];
	f[p][0]=v[bk];
	f[p][1]=f[p][2]=0;
	int R=mp[bk]-1;
	if(mp[p]<=R)seg::qry(rt[h],mp[h],R,mp[p],R,f[p]);
}//将 p 的 0/1/2 更新为正确的
void mdf(int p,ll val){
	int u=p;
	vector<int> vet;
	while(p!=1){
		int x=top[p];
		if(x!=p)p=x;
		else{
			vet.push_back(p);
			p=fa[p];
		}
	}
	p=u;
	for(int x:vet){
		int y=fa[x];
		g[y][0]-=f[x][0];
		g[y][1]-=f[x][1];
		g[y][2]-=f[x][2];
		st[y].erase(f[x][0]-f[x][1]);
	}
	val=max(val,0ll);
	v[p]=val;
	seg::mdf(p);
	for(int x:vet){
		renew(x);
		int y=fa[x];	
		g[y][0]+=f[x][0];
		g[y][1]+=f[x][1];
		g[y][2]+=f[x][2];
		st[y].insert(f[x][0]-f[x][1]);
		seg::mdf(y);
	}
}
// #define DEBUG 1  // 调试开关
struct IO {
#define MAXSIZE (1 << 20)
#define isdigit(x) (x >= '0' && x <= '9')
  char buf[MAXSIZE], *p1, *p2;
  char pbuf[MAXSIZE], *pp;
#if DEBUG
#else
  IO() : p1(buf), p2(buf), pp(pbuf) {}

  ~IO() { fwrite(pbuf, 1, pp - pbuf, stdout); }
#endif
  char gc() {
#if DEBUG  // 调试,可显示字符
    return getchar();
#endif
    if (p1 == p2) p2 = (p1 = buf) + fread(buf, 1, MAXSIZE, stdin);
    return p1 == p2 ? ' ' : *p1++;
  }

  void read(int &x) {
    bool neg = false;
    x = 0;
    char ch = gc();
    for (; !isdigit(ch); ch = gc())
      if (ch == '-') neg = true;
    if (neg)
      for (; isdigit(ch); ch = gc()) x = x * 10 + ('0' - ch);
    else
      for (; isdigit(ch); ch = gc()) x = x * 10 + (ch - '0');
  }

  void read(char *s) {
    char ch = gc();
    for (; isspace(ch); ch = gc());
    for (; !isspace(ch); ch = gc()) *s++ = ch;
    *s = 0;
  }

  void read(char &c) { for (c = gc(); isspace(c); c = gc()); }

  void push(const char &c) {
#if DEBUG  // 调试,可显示字符
    putchar(c);
#else
    if (pp - pbuf == MAXSIZE) fwrite(pbuf, 1, MAXSIZE, stdout), pp = pbuf;
    *pp++ = c;
#endif
  }

  void write(int x) {
    bool neg = false;
    if (x < 0) {
      neg = true;
      push('-');
    }
    static int sta[40];
    int top = 0;
    do {
      sta[top++] = x % 10;
      x /= 10;
    } while (x);
    if (neg)
      while (top) push('0' - sta[--top]);
    else
      while (top) push('0' + sta[--top]);
  }

  void write(int x, char lastChar) { write(x), push(lastChar); }
} io;
int main(){
//	freopen("xx.in","r",stdin);
	cin>>n>>q;
	for(int i=1;i<=n;++i){
		io.read(v[i]);
		v[i]=max(v[i],0);
	}
	for(int i=1;i<n;++i){
		int x,y;
		io.read(x);
		io.read(y);
		e[x].push_back(y);
		e[y].push_back(x);
	}
	dfs_build(1);
	dfs_top(1);
	dfs(1,0);
	init(1);
	seg::init();
	while(q--){
		int op,x,y;
		io.read(op),io.read(x);
		if(op==1){
			io.read(y);
			mdf(x,y);
		}
		else{
			renew(x);
			printf("%lld\n",max({f[x][0],f[x][1],f[x][2]}));
		}
	}
}

upd:这玩意居然能和 zkw 线段树结合到一起。用 6.2sol 写了一个这个获得了 P4751 最优解。

原文