刷题题解:【牛客网】树学(树形dp)

题目描述:

在这里插入图片描述在这里插入图片描述

解题思路:

AC代码:

#include<bits/stdc++.h>
    using namespace std;
    const int maxn=1e6+100;
    typedef long long LL;
    struct edge{
    
    
    int v;
    int next;
    }e[2*maxn];
    int cnt=0,head[2*maxn],vis[maxn];
    LL  sz[maxn],depsum[maxn],dp[maxn];
    void Insert(int u,int v){
    
    
    cnt++;
    e[cnt].v=v;
    e[cnt].next=head[u];
    head[u]=cnt;
    }
    void dfs(int u){
    
    
    vis[u]=1;
    sz[u]=1;
    for(int i=head[u];i>=0;i=e[i].next){
    
    
    int v=e[i].v;
    if(!vis[v]){
    
    
    dfs(v);
    sz[u]+=sz[v];
    depsum[u]+=depsum[v]+sz[v];
    }
    }
    }
    LL ans,n;
    void getans(int u){
    
    
    vis[u]=1;
    for(int i=head[u];i>=0;i=e[i].next){
    
    
    int v=e[i].v;
    if(!vis[v]){
    
    
    dp[v]=dp[u]+n-2*sz[v];
    ans=min(ans,dp[v]);
    getans(v);
    }
    }
    }
    int main(){
    
    
    memset(vis,0,sizeof(vis));
    memset(head,-1,sizeof(head));
    cin>>n;
    for(int i=1;i<=n-1;i++){
    
    
    int x,y;
    cin>>x>>y;
    Insert(x,y);
    Insert(y,x);
    }
    dfs(1);
    ans=depsum[1];
    dp[1]=depsum[1];
    memset(vis,0,sizeof(vis));
    getans(1);
    cout<<ans;
    return 0;
    }



上一篇博客:[leetcode] LCP 09. 最小跳跃次数(搜索、bfs)

猜你喜欢

转载自blog.csdn.net/IAMLSL/article/details/114242949