POJ 2631 Roads in the North(树形dp)

来源:互联网 发布:带鱼 网络用语 编辑:程序博客网 时间:2024/06/05 07:39

题目链接: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
原创粉丝点击