[Codeforces208E]Blood Cousins(dsu on the tree+倍增)

19 篇文章 0 订阅
6 篇文章 0 订阅

题目描述

传送门
题意:给出一棵家谱树,定义向上走k步到达的节点为该点的k-ancestor。每次询问与v同P-ancestor的节点有多少个。

题解

题目可以转化为在v的P-ancestor的子树里和v同一深度的有多少个点
用dsu on the tree搞一搞。。
倍增求出v的P-ancestor,然后对于每一个询问加一个链表,一遍dfs就行了。
注意这是一个森林
时间复杂度 O(nlogn)

代码

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
#define N 100005
#define sz 17

int n,m,Son;
int tot,point[N],nxt[N],v[N];
int cq,pq[N],nxtq[N],vq[N],idq[N];
int root[N],size[N],h[N],f[N][sz],son[N],cnt[N],ans[N];

void add(int x,int y)
{
    ++tot; nxt[tot]=point[x]; point[x]=tot; v[tot]=y;
}
void addq(int x,int y,int z)
{
    ++cq; nxtq[cq]=pq[x]; pq[x]=cq; vq[cq]=y; idq[cq]=z;
}
void build(int x,int dep)
{
    size[x]=1;h[x]=dep;
    for (int i=1;i<sz;++i) f[x][i]=f[f[x][i-1]][i-1];
    for (int i=point[x];i;i=nxt[i])
    {
        f[v[i]][0]=x;
        build(v[i],dep+1);
        size[x]+=size[v[i]];
        if (size[v[i]]>size[son[x]]) son[x]=v[i];
    }
}
int find(int x,int y)
{
    for (int i=0;i<sz;++i)
        if ((y>>i)&1) x=f[x][i];
    return x;
}
void calc(int x,int opt)
{
    cnt[h[x]]+=opt;
    for (int i=point[x];i;i=nxt[i])
        if (v[i]!=Son) calc(v[i],opt);
}
void dfs(int x,int k)
{
    for (int i=point[x];i;i=nxt[i])
        if (v[i]!=son[x]) dfs(v[i],0);
    if (son[x]) dfs(son[x],1),Son=son[x];
    calc(x,1);Son=0;
    for (int i=pq[x];i;i=nxtq[i])
    {
        int H=vq[i];
        ans[idq[i]]=cnt[H]-1;
    }
    if (!k) calc(x,-1);
}
int main()
{
    scanf("%d",&n);
    for (int i=1;i<=n;++i)
    {
        int fa;scanf("%d",&fa);
        if (!fa) root[++root[0]]=i;
        add(fa,i);
    }
    for (int i=1;i<=root[0];++i) build(root[i],1);
    scanf("%d",&m);
    for (int i=1;i<=m;++i)
    {
        int x,y,z;scanf("%d%d",&x,&y);
        z=find(x,y);
        addq(z,h[x],i);
    }
    for (int i=1;i<=root[0];++i) dfs(root[i],0);
    for (int i=1;i<=m;++i) printf("%d%c",ans[i]," \n"[i==m]);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值