HDU 2196 Computer 树形dp

本文介绍了一种使用树形动态规划的方法来解决求解树上每一点到树上其它点最大距离的问题。通过定义状态和转移方程,有效地求出了每个节点到树上任意节点的最大距离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

http://acm.split.hdu.edu.cn/showproblem.php?pid=2196

题意

给定一颗树,求出每个点到树上任一点的最大距离。
dp[u][0] 和dp[u][1]分别表示u在以u为根结点的子树中,u能走到的最大距离和次大距离
dp[u][2] 表示u往其父节点走能走到的最大距离

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<string>
#include<queue>
#include<stack>
#include<set>
#include<map>
#define ll long long
using namespace std;
const int INF = ( 2e9 ) + 2;
const ll maxn = 10010;
struct edge
{
    int v,w,next;
}e[maxn*2];
int head[maxn],d[maxn],dp[maxn][3],longest[maxn];
int tot;
bool vis[maxn];
void add(int u,int v,int w)
{
    e[tot].v=v;
    e[tot].w=w;
    e[tot].next=head[u];
    head[u]=tot++;
}
void init()
{
    memset(head,-1,sizeof(head));
    tot=0;
}
void dfs1(int u,int fa)// 求结点到其子树上某结点的最长距离和次长距离 
{
    dp[u][0]=0;
    for(int i=head[u];i!=-1;i=e[i].next)
    {
        int v=e[i].v,w=e[i].w;
        if(v==fa)continue;
        dfs1(v,u);
        if(dp[u][0]<=dp[v][0]+w)
        {
            dp[u][1]=dp[u][0];
            dp[u][0]=dp[v][0]+w;
            longest[u]=v;
        }
        else if(dp[u][1]<dp[v][0]+w)
        dp[u][1]=dp[v][0]+w;
    }
}
void dfs2(int u,int fa)
{
    for(int i=head[u];i!=-1;i=e[i].next)
    {
        int v=e[i].v,w=e[i].w;
        if(v==fa)continue;
        if(longest[u]==v)
            dp[v][2]=max(dp[u][1],dp[u][2])+w;
        else
            dp[v][2]=max(dp[u][0],dp[u][2])+w;
        dfs2(v,u);
    }
}
int main()
{
    int n,w,v;
    while(~scanf("%d",&n))
    {
        init();
        for(int i=2;i<=n;i++)
        {
            scanf("%d%d",&v,&w);
            add(i,v,w);
            add(v,i,w);
        }
        memset(dp,0,sizeof(dp));
        dfs1(1,0);
        dp[1][2]=0;
        dfs2(1,0);
        for(int i=1;i<=n;i++)
        printf("%d\n",max(dp[i][0],dp[i][2]));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值