UVA10308 Roads in the North 树的最长路径

Posted chanceyu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVA10308 Roads in the North 树的最长路径相关的知识,希望对你有一定的参考价值。

Description

Building and maintaining roads among communities in the far North is an expensive business. With this in mind, the roads are build such 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

Input to the problem 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.

Output

You are to output 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

Analysis

树的结点往上长型dp
Note:

  • 图的邻接表模板
  • 字符串的处理

Code

#include<bits/stdc++.h>
using namespace std;
int dp1[10001],dp2[10001],head[10001];
int cnt=0,maxi=0;
struct edge{int v,w,next;}Edge[20001];
inline void add_edge(int u,int v,int w){
    Edge[++cnt]={v,w,head[u]};head[u]=cnt;
}
void dfs(int s,int pre){
    for(int i=head[s];i;i=Edge[i].next){
        int v=Edge[i].v;
        if(v==pre)continue;dfs(v,s);
        if(dp1[v]+Edge[i].w>dp1[s])dp2[s]=dp1[s],dp1[s]=dp1[v]+Edge[i].w;
        else if(dp1[v]+Edge[i].w>dp2[s])dp2[s]=dp1[v]+Edge[i].w;
    }maxi=max(maxi,dp1[s]+dp2[s]);
}
int main(){
    int a,b,c,flag;char m[20];
    while(1){
        memset(head,-1,sizeof(head));memset(dp1,0,sizeof(dp1));
        flag=cnt=maxi=0;memset(dp2,0,sizeof(dp2));
        while(gets(m)!=NULL&&m[0]!=''){
            sscanf(m,"%d%d%d",&a,&b,&c);
            add_edge(a,b,c),add_edge(b,a,c);flag=1;
        }
        if(flag==1){
            dfs(1,0);
            printf("%d
",maxi);
        }if(m[0]!='')break;
    }
    return 0;
}

以上是关于UVA10308 Roads in the North 树的最长路径的主要内容,如果未能解决你的问题,请参考以下文章

Roads in the North (树的直径)

Poj2631--Roads in the North(树的直径)

Codeforces 835 F. Roads in the Kingdom

题解报告:poj 2631 Roads in the North(最长链)

[Poj] Roads in the North

poj2631 ?Roads in the North(求树的直径)