跳到正文

题解

题解:P1001 A+B Problem

niu_zh约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年5月10日
收录
2025年12月12日
更新
2026年11月8日
篇幅
约 4 分钟
获赞
40
题目
P1001

版本

  1. v1当前

前言

这不一眼树剖板子吗。

思路

显然,我们可以使用树链剖分,在一颗由两个点权分别为 aa 与 bb 的点构成的树上跑树剖。具体用线段树维护重链上点权的区间和,再用 lca 求两点唯一路径上点权之和。

代码

C++
/*
 * @FilePath: tmp.cpp
 * @Author: niu-zh
 */
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e5+10;
vector<int> tree[N];
int cnt,a[N];
struct node
{
	int tree[N<<2],lzy[N<<2];
	void pushup(int p)
	{
		tree[p]=tree[p<<1]+tree[p<<1|1];
	}
	void makelzy(int p,int l,int r,int x)
	{
		tree[p]+=(x*(r-l+1));
		lzy[p]+=x;
	}
	void pushdown(int p,int l,int r)
	{
		int mid=(l+r)>>1;
		makelzy(p<<1,l,mid,lzy[p]);
		makelzy(p<<1|1,mid+1,r,lzy[p]);
		lzy[p]=0;
	}
	void update(int p,int l,int r,int x,int y,int add)
	{
		if (x<=l&&r<=y)
		{
			makelzy(p,l,r,add);
			return;
		}
		pushdown(p,l,r);
		int mid=(l+r)>>1;
		if (mid>=x) update(p<<1,l,mid,x,y,add);
		if (mid<y) update(p<<1|1,mid+1,r,x,y,add);
		pushup(p);
	}
	int query(int p,int l,int r,int x,int y)
	{
		if (x<=l&&r<=y)
		{
			return tree[p];
		}
		pushdown(p,l,r);
		int mid=(l+r)>>1,ans=0;
		if (mid>=x) ans+=query(p<<1,l,mid,x,y);
		if (mid<y) ans+=query(p<<1|1,mid+1,r,x,y);
		return ans;
	}
} tr;
int fa[N],dep[N],sze[N],son[N],top[N],dfn[N],rnk[N];
void dfs1(int x)
{
	son[x]=-1;
	sze[x]=1;
	for (auto v:tree[x])
	{
		if (dep[v]) continue;
		dep[v]=dep[x]+1;
		fa[v]=x;
		dfs1(v);
		sze[x]+=sze[v];
		if (son[x]==-1||sze[v]>sze[son[x]])
		{
			son[x]=v;
		}
	}
}
void dfs2(int x, int t)
{
	top[x]=t;
	cnt++;
	dfn[x]=cnt;
	if(a[x])
	{
		tr.update(1,1,2,dfn[x],dfn[x],a[x]);
	}
	rnk[cnt]=x;
	if (son[x]==-1)
	{
		return;
	}
	dfs2(son[x],t);
	for (auto v:tree[x])
	{
		if (v!=son[x]&&v!=fa[x])
		{
			dfs2(v,v);
		}
	}
}
int query(int u,int v)
{
	int ans=0;
	while (top[u]!=top[v])
	{
		if (dep[top[u]]<dep[top[v]])
		{
			swap(u,v);
		}
		ans+=tr.query(1,1,2,dfn[top[u]],dfn[u]);
		u=fa[top[u]];
	}
	if (dep[u]>dep[v])
	{
		swap(u,v);
	}
	ans+=tr.query(1,1,2,dfn[u],dfn[v]);
	return ans;
}
signed main()
{
	for (int i=1; i<=2; i++)
	{
		cin>>a[i];
	}
	tree[1].push_back(2);
	tree[2].push_back(1);
	dep[1]=1;
	dfs1(1);
	dfs2(1,1);
	cout<<query(1,2);
	return 0;
}