hdu 2196 dfs

两次dfs

第一次记录从下向上最长距离

第二次记录从父节点到儿子节点最长距离

 

ACcode:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int nsize=11111;

struct tre
{
    int to,w,next;
} c[nsize<<1];

int n,p,k;
int head[nsize],v[nsize],top;
int dp[nsize],max2[nsize],pos[nsize];

void add(int fa,int s,int w)
{
    c[top].next=head[fa];
    c[top].to=s;
    c[top].w=w;
    head[fa]=top++;
}

int Max(int a1,int a2)
{
    return a1>a2?a1:a2;
}

void dfs1(int r)
{
    v[r]=1;
    int w,to;
    for (int i=head[r]; i!=-1; i=c[i].next)
    {

        to=c[i].to,w=c[i].w;
        if (v[to]) continue;
        dfs1(to);
        if (dp[to]+w>dp[r])
        {
            max2[r]=Max(max2[r],dp[r]);
            pos[r]=to;
            dp[r]=dp[to]+w;
        }
        else max2[r]=Max(max2[r],dp[to]+w);
    }
}

void dfs2(int r)
{
    v[r]=1;
    int to,w;
    for (int i=head[r]; i!=-1; i=c[i].next)
    {

        to=c[i].to,w=c[i].w;
        if (v[to]) continue;
        if (pos[r]!=to)
        {
             if (dp[r]+w>dp[to])
             {
                 dp[to]=dp[r]+w;
                 pos[to]=r;
             }
             else max2[to]=Max(max2[to],dp[r]+w);
        }
         else
         {
             if (max2[r]+w>dp[to])
             {
                 dp[to]=max2[r]+w;
                 pos[to]=r;
             }
             else max2[to]=Max(max2[to],max2[r]+w);
         }
         dfs2(to);
    }
}

int main()
{
    while (~scanf("%d",&n))
    {
        top=0;
        memset(v,0,sizeof(v));
        memset(dp,0,sizeof(dp));
        memset(max2,0,sizeof(max2));
        memset(head,-1,sizeof(head));
        for (int i=2; i<=n; i++)
        {
            scanf("%d %d",&p,&k);
            add(p,i,k);
            add(i,p,k);
        }
        dfs1(1);
        memset(v,0,sizeof(v));
        dfs2(1);
        for (int i=1; i<=n; i++) printf("%d\n",dp[i]);
    }
    return 0;
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值