zoukankan      html  css  js  c++  java
  • CodeForces 161D Distance in Tree【树形DP】

    <题目链接>

    题目大意:
    一颗无向无环树,有n个顶点,求其中距离为k的点对数是多少,(u,v)与(v,u)为同一点对。

     1 #include <cstdio>
     2 #include <cstring>
     3 #include <algorithm>
     4 using namespace std;
     5 
     6 #define N int(5e4+10)
     7 int n,k,ans,cnt;
     8 int dp[N][510],head[N];
     9 struct Edge{
    10     int to,nxt;
    11 }edge[N<<1];
    12 void init(){
    13     cnt=0;ans=0;
    14     memset(head,-1,sizeof(head));
    15     memset(dp,0,sizeof(dp));
    16 }
    17 void addedge(int u,int v){
    18     edge[cnt].to=v,edge[cnt].nxt=head[u];
    19     head[u]=cnt++;
    20 }
    21 void dfs(int u,int fa){
    22     dp[u][0]=1;        //dp[i][j]表示以u为根的子树中,距u的距离为j的点的数量
    23     for(int i=head[u];~i;i=edge[i].nxt){
    24         int v=edge[i].to;
    25         if(v==fa)continue;
    26         dfs(v,u);
    27         for(int j=0;j<k;j++)ans+=dp[u][j]*dp[v][k-j-1];     
    28         for(int j=1;j<=k;j++)dp[u][j]+=dp[v][j-1];      
    29     }
    30 }
    31 int main(){
    32     while(~scanf("%d%d",&n,&k)){
    33         init();
    34         for(int i=1;i<n;i++){
    35             int u,v;scanf("%d%d",&u,&v);
    36             addedge(u,v);addedge(v,u);
    37         }
    38         dfs(1,-1);
    39         printf("%d
    ",ans); 
    40     }
    41 }

    2019-02-07

  • 相关阅读:
    HTML 页面的 批量删除的按钮
    HTML 选择器
    ....
    java 反射机制
    插件库
    向上滚动
    浮动元素定位float
    中文字体对应的英文名称
    echarts入门教程
    ie9浏览器window.openbug
  • 原文地址:https://www.cnblogs.com/00isok/p/10355774.html
Copyright © 2011-2022 走看看