bzoj 3653: 谈笑风生

题意:

设T 为一棵有根树,我们做如下的定义:
设a和b为T 中的两个不同节点。如果a是b的祖先,那么称“a比b不知道高明到哪里去了”。
设a 和 b 为 T 中的两个不同节点。如果 a 与 b 在树上的距离不超过某个给定常数x,那么称“a 与b 谈笑风生”。
给定一棵n个节点的有根树T,节点的编号为1 到 n,根节点为1号节点。你需要回答q 个询问,询问给定两个整数p和k,问有多少个有序三元组(a;b;c)满足:
1. a、b和 c为 T 中三个不同的点,且 a为p 号节点;
2. a和b 都比 c不知道高明到哪里去了;
3. a和b 谈笑风生。这里谈笑风生中的常数为给定的 k。

题解:

因为 too naive 所以主席树都写错,调了大半小时……
显然 a,b 在一条直链上,当b是a的祖先时直接算答案即可,关键是b是a的儿子比较难搞。
暴力显然就是枚举与a距离不超过k的儿子,答案加上 tot[y]1
那么用主席树加速即可。
code:

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#define LL long long
using namespace std;
struct node{
    LL y,next;
}a[600010];LL len=0,last[300010];
LL dep[300010],la[300010],ys[300010],z=0,tot[300010];
struct trnode{
    LL lc,rc,c;
}tr[6000010];LL Tot=0,root[300010];
void ins(LL x,LL y)
{
    a[++len].y=y;
    a[len].next=last[x];last[x]=len;
}
void update(LL &x,LL fr,LL l,LL r,LL k,LL c)
{
    x=++Tot;tr[x]=tr[fr];
    if(l==r) {tr[x].c+=c;return;}
    LL mid=(l+r)/2;
    if(k<=mid) update(tr[x].lc,tr[fr].lc,l,mid,k,c);
    else update(tr[x].rc,tr[fr].rc,mid+1,r,k,c);
    tr[x].c=tr[tr[x].lc].c+tr[tr[x].rc].c;
}
LL findans(LL x1,LL x2,LL l,LL r,LL fl,LL fr)
{
    if(l==fl&&r==fr) return tr[x2].c-tr[x1].c;
    LL mid=(l+r)/2;
    if(fr<=mid) return findans(tr[x1].lc,tr[x2].lc,l,mid,fl,fr);
    if(fl>mid) return findans(tr[x1].rc,tr[x2].rc,mid+1,r,fl,fr);
    return findans(tr[x1].lc,tr[x2].lc,l,mid,fl,mid)+findans(tr[x1].rc,tr[x2].rc,mid+1,r,mid+1,fr);
}
void dfs(LL x,LL fa)
{
    dep[x]=dep[fa]+1;ys[x]=la[x]=++z;tot[x]=1;
    for(LL i=last[x];i;i=a[i].next)
    {
        LL y=a[i].y;
        if(y==fa) continue;
        dfs(y,x);la[x]=la[y];
        tot[x]+=tot[y];
    }
}
LL n,q;
void build(LL x,LL fa)
{
    update(root[ys[x]],root[ys[x]-1],1,n,dep[x],tot[x]-1);
    for(LL i=last[x];i;i=a[i].next)
    {
        LL y=a[i].y;
        if(y==fa) continue;
        build(y,x);
    }
}
int main()
{
    scanf("%lld %lld",&n,&q);
    for(LL i=1;i<n;i++)
    {
        LL x,y;scanf("%lld %lld",&x,&y);
        ins(x,y);ins(y,x);
    }
    dfs(1,0);build(1,0);
    while(q--)
    {
        LL x,k;scanf("%lld %lld",&x,&k);
        printf("%lld\n",findans(root[ys[x]],root[la[x]],1,n,min(dep[x]+1,n),min(n,dep[x]+k))+min(dep[x]-1,k)*(tot[x]-1));
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值