zoukankan      html  css  js  c++  java
  • 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

    Solution 1:

    树的结点往上长型dp
    Note:

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

    Solution 2:

    两次DFS
    Suppose a and b are the endpoints of the path in the tree which achieve the diameter.
    Let s be any vertex in T,then a or b is the vertex whose distance from s is the greatest.

    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;
    }
    
  • 相关阅读:
    (转)sysbench部署与参数详解
    (转)MySQL自带的性能压力测试工具mysqlslap详解
    (转)mysql双机热备的实现
    (转)linux运维必会MySQL企业面试题
    (转)MySQL出现同步延迟有哪些原因?如何解决?
    (转)mysql数据库高可用高扩展性架构方案实施
    java.IO
    String类的编码和解码问题
    编码表的概述和常见编码表
    05_打字游戏
  • 原文地址:https://www.cnblogs.com/chanceYu/p/12250031.html
Copyright © 2011-2022 走看看