思路:

(抄一波公式)

$$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]-));
}
}

最新文章

  1. 人人都是 DBA(XII)查询信息收集脚本汇编
  2. Eclipse 工程迁移到 Android Studio
  3. 谈谈 Google 的 Test Certified
  4. hdu 2057 A+B
  5. leetcode105:Construct Binary Tree from Preorder and Inorder Traversal
  6. 设计模式总结篇系列:观察者模式(Observer)
  7. 【STL】- vector的用法
  8. ruby 疑难点之—— yield 和 yield self
  9. JS 封装类
  10. NSURLConnection请求时间
  11. js 全国城市3级联动
  12. ADO读取EXCEL
  13. poolingHttpclientConnectionmanager 使用
  14. 疯狂的 JAVA 后++
  15. 某厂java算法题实现及改进【有n个人成一圈,顺序排号(编号为1到n),从第一个人开始报数1到3报数】
  16. MyCat-简介
  17. redis 4.x 安装哨兵模式 sentinel
  18. Unity3d-AngryBots实例解读
  19. centos6安装mysql8 shell脚本
  20. Python基础数据类型-字典(dict)

热门文章

  1. 哈夫曼树(Huffman Tree)
  2. 安装部署NetBeans mysql Tomact joget workflow 环境
  3. mitmproxy安装与使用
  4. SSH免密登录的错误
  5. Silverlight之我见——数据批示(1)
  6. IE7浏览器下去除flash动画边框问题
  7. sql server的 between and 日期问题
  8. ubuntu 14.04 gcc/g++版本降低
  9. noip模拟赛 拼不出的数
  10. noip模拟赛 fateice-string