luogu P3833 [SHOI2012]魔法树

题面传送门
直接树链剖分即可,还比模板少两个操作。
代码实现:

#include<cstdio>
#include<cstring>
using namespace std;
int n,m,k,x,y,idea,son[100039],d[100039],fa[100039],top[100039],id[100039],siz[100039];
char _s;
long long z,f[400039],sum[400039];
struct yyy{int to,z;};
struct ljb{
	int head,h[100039];
	yyy f[200039];
	inline void add(int x,int y){
		f[++head]=(yyy){y,h[x]};
		h[x]=head;
	}
}s;
inline void push(int l,int r,int now){
	int m=(l+r)>>1;
	f[now<<1]+=f[now];
	f[now<<1|1]+=f[now];
	sum[now<<1]+=f[now]*(m-l+1);
	sum[now<<1|1]+=f[now]*(r-m);
	f[now]=0;
}
inline void get(int x,int y,int z,int l,int r,int now){
	if(x<=l&&r<=y){f[now]+=z;sum[now]+=(r-l+1)*z;return;}
	if(f[now]) push(l,r,now);
	int m=(l+r)>>1;
	if(x<=m) get(x,y,z,l,m,now<<1);
	if(y>m) get(x,y,z,m+1,r,now<<1|1);
	sum[now]=sum[now<<1]+sum[now<<1|1];
}
inline long long find(int x,int y,int l,int r,int now){
	if(x<=l&&r<=y) return sum[now];
	if(f[now]) push(l,r,now);
	int m=(l+r)>>1;
	long long fs=0;
	if(x<=m) fs+=find(x,y,l,m,now<<1);
	if(y>m) fs+=find(x,y,m+1,r,now<<1|1);
	return fs;
}
inline void dfs1(int x,int last){
	d[x]=d[last]+1;
	fa[x]=last;
	siz[x]=1;
	int cur=s.h[x],pus=-1;
	yyy tmp;
	while(cur!=-1){
		tmp=s.f[cur];
		if(tmp.to!=last){
			dfs1(tmp.to,x);
			siz[x]+=siz[tmp.to];
			if(pus<siz[tmp.to]) pus=siz[tmp.to],son[x]=tmp.to;
		}
		cur=tmp.z;
	}
}
inline void dfs2(int x,int y){
	top[x]=y;
	id[x]=++idea;
	if(!son[x])return;
	dfs2(son[x],y);
	int cur=s.h[x];
	yyy tmp;
	while(cur!=-1){
		tmp=s.f[cur];
		if(tmp.to!=fa[x]&&tmp.to!=son[x]) dfs2(tmp.to,tmp.to);
		cur=tmp.z;
	}
}
inline void swap(int &x,int &y){x^=y,y^=x,x^=y;}
inline void get1(int x,int y,int z){
	while(top[x]!=top[y]){
		if(d[top[x]]<d[top[y]]) swap(x,y);
		get(id[top[x]],id[x],z,1,n,1);
		x=fa[top[x]];
	}
	if(d[x]>d[y]) swap(x,y);
	get(id[x],id[y],z,1,n,1);
}
inline long long find1(int x){return find(id[x],id[x]+siz[x]-1,1,n,1);}
int main(){
	register int i;
	memset(s.h,-1,sizeof(s.h));
	scanf("%d",&n);
	for(i=1;i<n;i++) scanf("%d%d",&x,&y),x++,y++,s.add(x,y),s.add(y,x);
	dfs1(1,0);
	dfs2(1,1);
	scanf("%d",&m);
	for(i=1;i<=m;i++){
		_s=getchar();
		while(_s<'A'||_s>'Z') _s=getchar();
		if(_s=='A'){
			scanf("%d%d%lld",&x,&y,&z);
			x++;y++;
			get1(x,y,z);
		}
		else {
			scanf("%d",&x);
			x++;
			printf("%lld\n",find1(x));
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值