[CodeForces 161D] Distance in Tree

题目描述:

给一个N个点的树,两点距离为1,求有多少个点对 的距离为 K(不重复统计)

题目分析:

点分治的题目每个都要变形!!!
本来套用了上上一题的做法,人家 N<=50000 ,又T成了SB
看了看题解,人家说是树形DP,mmp 说好的点分治呢!!!
其实仔细想想,我们开两个数组进行动态统计就行了 QwQ

题目链接:

Luogu 的 CF 题库

AC code:

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
const int maxm=51000;
const int inf=10000000;
int root=0,f[maxm],son[maxm],deep[maxm],d[maxm];
int head[maxm],to[maxm*2],net[maxm*2],cost[maxm*2],cnt,tot,k;
int num1[maxm],num2[maxm];
bool vis[maxm];
int ok[inf];
int sum,ans,n,q;
int flag=0;
inline void add(int x,int y,int c){cnt++,to[cnt]=y,cost[cnt]=c,net[cnt]=head[x],head[x]=cnt;}
void getroot(int now,int fa)
{
    son[now]=1,f[now]=0;
    for(int i=head[now];i;i=net[i])
        if(to[i]!=fa&&!vis[to[i]])
        {
            getroot(to[i],now);
            son[now]+=son[to[i]];
            f[now]=std::max(f[now],son[to[i]]);
        }
    f[now]=std::max(f[now],sum-son[now]);
    if(f[now]<f[root]||!root) root=now;
}
void getdeep(int now,int fa,int dep)
{
    if(dep<=k)
    {
        ans+=num1[k-dep];
        ++num2[dep];
    }
    for(int i=head[now];i;i=net[i])
     if(!vis[to[i]]&&to[i]!=fa)
      getdeep(to[i],now,dep+1);
}
void calc(int x)
{
   for(int i=0;i<=k;i++) num1[i]=0;
   num1[0]=1;
   for(int i=head[x];i;i=net[i])
   if(!vis[to[i]])
   {
      for(int j=0;j<=k;j++) num2[j]=0;
      getdeep(to[i],0,1);
      for(int j=0;j<=k;j++) num1[j]+=num2[j];
   }
}
void slove(int now)
{
    //printf("-%d-\n",now);
    vis[now]=1;
    calc(now);
    for(int i=head[now];i;i=net[i])
    if(!vis[to[i]]) 
     sum=son[to[i]],root=0,getroot(to[i],0),slove(root);
}
int main()
{
    scanf("%d%d",&n,&k);
    for(int i=1;i<n;i++)
    {
        int u,v;
        scanf("%d%d",&u,&v);
        add(u,v,1);
        add(v,u,1);
    }
    sum=n;
    root=0;
    getroot(1,0);
    slove(root);
    printf("%d\n",ans);
    return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值