Educational Codeforces Round 52F(樹形DP,vector)

來源:互聯網
上載者:User

標籤:can   names   最大   深度   點距   mil   ros   style   min   

#include<bits/stdc++.h>
using namespace std;
int n,k;
vector<int>son[1000007];
int dp[1000007],depth[1000007],ans[1000007];//dp【i】表示離i最近的葉子節點距離i的深度,depth【i】表示以i為根,回到i所能到達的葉子節點的數量,ans【i】表示以i為根,能到達的葉子節點數目最大,即題意所需
void dfs(int now){
    if(!son[now].size()){//本身為葉子結點
        depth[now]=0;
        dp[now]=1;
        return;
    }
    int mn=1e9,mx=0;
    for(const int&tmp:son[now]){//遍曆孩子結點
        dfs(tmp);//繼續深搜
        if(depth[tmp]<k)//小於k的話從now向下走可以走到孩子結點tmp所能觸及的葉子結點
            dp[now]+=dp[tmp];//把孩子能碰到的葉子向上傳遞給父親
        mx=max(mx,ans[tmp]-(depth[tmp]<k?dp[tmp]:0));//depth【tmp】<k時,dp【tmp】已經加到了dp【now】裡,把它減掉,mx留下的是最大的一次下去回不來所能碰到的葉子結點數
        mn=min(mn,depth[tmp]+1);//now的深度為最小的孩子深度+1
    }
    depth[now]=mn;//mn只放最小的深度,那些子節點深度過大的都碰不到,只會碰一次符合題意的葉子結點(這次下去了就回不到祖先節點(這一次dfs的參數)了)
    ans[now]=dp[now]+mx;//mx只能加一個所以放在迴圈之外
}
int main(){
    scanf("%d%d",&n,&k);
    int x;
    for(int i=2;i<=n;i++){
        scanf("%d",&x);
        son[x].push_back(i);
    }
    dfs(1);
    printf("%d\n",ans[1]);
    return 0;
}

//有一種數組類比鏈表的遍曆結點方式,暫待瞭解

Educational Codeforces Round 52F(樹形DP,vector)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.