BZOJ 3653 主席树
2024-08-30 03:43:39
思路:
(抄一波公式)
$$ans=min(dep[x],k)×(size[x]-1)+\sum_{y在x的子树中,且dis(x,y)<=k}(size[y]-1)$$
顺着DFS序
按照deep往线段树里插就好了...
//By SiriusRen
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N=;
int n,q,xx,yy,first[N],next[N*],v[N*],tot,root[N];
int dfn[N],revdfn[N],last[N],cnt,deep[N],size[N],lson[N*],rson[N*];
long long tree[N*];
void add(int x,int y){v[tot]=y,next[tot]=first[x],first[x]=tot++;}
void dfs(int x,int fa){
dfn[x]=++cnt,revdfn[cnt]=x,size[x]=;
for(int i=first[x];~i;i=next[i])if(v[i]!=fa){
deep[v[i]]=deep[x]+,dfs(v[i],x),size[x]+=size[v[i]];
}last[x]=cnt;
}
void insert(int l,int r,int &pos,int last,int num,int wei){
pos=++cnt,tree[pos]=tree[last]+wei;
if(l==r)return;
int mid=(l+r)>>;
if(mid<num)lson[pos]=lson[last],insert(mid+,r,rson[pos],rson[last],num,wei);
else rson[pos]=rson[last],insert(l,mid,lson[pos],lson[last],num,wei);
}
long long query(int l,int r,int pos,int last,int L,int R){
if(l>=L&&r<=R)return tree[pos]-tree[last];
int mid=(l+r)>>;
if(mid<L)return query(mid+,r,rson[pos],rson[last],L,R);
else if(mid>=R)return query(l,mid,lson[pos],lson[last],L,R);
else return query(l,mid,lson[pos],lson[last],L,R)+query(mid+,r,rson[pos],rson[last],L,R);
}
int main(){
memset(first,-,sizeof(first));
scanf("%d%d",&n,&q);
for(int i=;i<n;i++)scanf("%d%d",&xx,&yy),add(xx,yy),add(yy,xx);
deep[]=,dfs(,);
for(int i=;i<=n;i++)insert(,n,root[i],root[i-],deep[revdfn[i]],size[revdfn[i]]-);
while(q--){
scanf("%d%d",&xx,&yy);
printf("%lld\n",query(,n,root[last[xx]],root[dfn[xx]],deep[xx],deep[xx]+yy)+min(deep[xx]-,yy)*(1ll*size[xx]-));
}
}
最新文章
- 人人都是 DBA(XII)查询信息收集脚本汇编
- Eclipse 工程迁移到 Android Studio
- 谈谈 Google 的 Test Certified
- hdu 2057 A+B
- leetcode105:Construct Binary Tree from Preorder and Inorder Traversal
- 设计模式总结篇系列:观察者模式(Observer)
- 【STL】- vector的用法
- ruby 疑难点之—— yield 和 yield self
- JS 封装类
- NSURLConnection请求时间
- js 全国城市3级联动
- ADO读取EXCEL
- poolingHttpclientConnectionmanager 使用
- 疯狂的 JAVA 后++
- 某厂java算法题实现及改进【有n个人成一圈,顺序排号(编号为1到n),从第一个人开始报数1到3报数】
- MyCat-简介
- redis 4.x 安装哨兵模式 sentinel
- Unity3d-AngryBots实例解读
- centos6安装mysql8 shell脚本
- Python基础数据类型-字典(dict)