Roads in the North - UVa 10308 树形dp

Problem I

Roads in the North

Input: standard input

Output: standard output

Time Limit: 2 seconds

Memory Limit: 32 MB

 

Building and maintaining roads among communities in the far North is an expensive business. With this in mind, the roads are built in such a way that there is only one route from a village to a village that does not pass through some other village twice.

Given is an area in the far North comprising a number of villages and roads among them such that any village can be reached by road from any other village. Your job is to find the road distance between the two most remote villages in the area.

The area has up to 10,000 villages connected by road segments. The villages are numbered from 1.

Input

The input contains several sets of input. Each set of input is a sequence of lines, each containing three positive integers: the number of a village, the number of a different village, and the length of the road segment connecting the villages in kilometers. All road segments are two-way. Two consecutive sets are separated by a blank line.

Output

For each set of input, you are to output a single line containing a single integer: the road distance between the two most remote villages in the area.

Sample Input

5 1 6
1 4 5
6 3 9
2 6 8
6 1 7

Sample Output

22

题意:在一棵树上找距离最远的两个点。

思路:每个点找到它的子树中到叶节点距离最大的两个,答案就可能为这两个之和。

AC代码如下:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct node
{
    int v,w,next;
}edge[20010];
int Head[10010],num,dp[10010][2],maxn;
void add(int u,int v,int w)
{
    edge[++num].v=v;
    edge[num].w=w;
    edge[num].next=Head[u];
    Head[u]=num;
}
char s[110];
void dfs(int f,int u)
{
    int j,v,w;
    for(j=Head[u];j!=0;j=edge[j].next)
       if(edge[j].v!=f)
       {
           v=edge[j].v;
           dfs(u,v);
           w=edge[j].w+dp[v][0];
           if(w>dp[u][0])
           {
               dp[u][1]=dp[u][0];
               dp[u][0]=w;
           }
           else if(w>dp[u][1])
             dp[u][1]=w;
       }
    maxn=max(maxn,dp[u][0]+dp[u][1]);
}
int main()
{
    int i,j,k,u,v,w;
    while(gets(s))
    {
        if(s[0]=='\0')
        {
            dfs(0,1);
            printf("%d\n",maxn);
            memset(Head,0,sizeof(Head));
            memset(dp,0,sizeof(dp));
            maxn=0;num=0;
            continue;
        }
        sscanf(s,"%d%d%d",&u,&v,&w);
        add(u,v,w);
        add(v,u,w);
    }
    dfs(0,1);
    printf("%d\n",maxn);
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值