您的位置:首页 > 其它

bzoj 3653: 谈笑风生

2018-02-27 09:23 316 查看

题意:

设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,f
11d3b
l,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));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: