POJ 2631 Roads in the North(树形dp)

题目链接:POJ 2631 Roads in the North

我也不知道这到底是树形dp还是dfs。。是在树形dp专题上的。

寻找树上两个节点之间最长的距离,仔细观察树的形式可以发现这样的最长距离都可以转化为以某个节点作为父节点,求它的两个最长子链的长度和。

#include <iostream>
#include <stdio.h>
#include <cstring>

using namespace std;

const int MAX_N = 10000 + 100;
const int MAX_M = MAX_N << 1;
int head[MAX_N];
struct Edge
{
    int v, next, w;
};
Edge e[MAX_M];
int u, v, w, res, cnt;
char str[100];

int dfs(int u, int fa)
{
    int v, temp, ans, _max;
    _max = 0;
    for(int i = head[u]; i != -1; i = e[i].next)
    {
        v = e[i].v;
        if(v == fa)
            continue;
        temp = dfs(v, u) + e[i].w;
        res = max(res, temp + _max);
        _max = max(_max, temp);
    }
    return _max;
}

void addEdge(int u, int v, int w)
{
    e[cnt].w = w;
    e[cnt].v = v;
    e[cnt].next = head[u];
    head[u] = cnt;
    cnt++;
}
int main()
{
    cnt = res = 0;
    memset(head, -1 ,sizeof(head));
    /*while(gets(str))
    {
        if(!str[0])
            break;
        sscanf(str, "%d%d%d", &u, &v, &w);
        addEdge(u, v, w);
        addEdge(v, u, w);
    }*/
    while(scanf("%d%d%d", &u, &v, &w) != EOF)
    {
        addEdge(u, v, w);
        addEdge(v, u, w);
    }
    dfs(1, -1);
    printf("%d\n", res);
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值