• Roads in the North POJ


    Roads in the North POJ - 2631 

    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

    题意:找出最长路
    题解:树的直径板子
    #include<iostream>
    #include<cstdio>
    #include<algorithm>
    #include<cstring>
    using namespace std;
    #define ll long long
    const int maxn=1e5+5;
    const int INF=0x3f3f3f3f;
    
    struct Edge{
        int v,l,next;
    }edge[maxn<<2];
    int vis[maxn],d[maxn],head[maxn],k,node,ans;
    
    void init(){
        k = 0;
        memset(head,-1,sizeof head);
    }
    
    void addedge(int u,int v,int l){
        edge[k].v = v;
        edge[k].l = l;
        edge[k].next = head[u];
        head[u] = k++;
    
        edge[k].v = u;
        edge[k].l = l;
        edge[k].next = head[v];
        head[v] = k++;
    }
    void dfs(int u,int t){
        for(int i=head[u];i!=-1;i=edge[i].next)
        {
            int v = edge[i].v;
            if(vis[v] == 0)
            {
                vis[v] = 1;
                d[v] = t + edge[i].l;
                if(d[v] > ans)
                {
                    ans = d[v];
                    node = v;
                }
                dfs(v,d[v]);
            }
        }
    }
    int main()
    {
        init();
        int l,r,len;
        while(scanf("%d%d%d",&l,&r,&len) == 3)
            addedge(l,r,len);
        memset(vis,0,sizeof vis);
        vis[1] = 1;
        ans = 0;
        dfs(1,0);
    
        memset(vis,0,sizeof vis);
        vis[node] = 1;
        ans = 0;
        dfs(node,0);
    
        printf("%d
    ",ans);
    };
    View Code
  • 相关阅读:
    正则表达式
    Java 枚举(enum) 详解7种常见的用法
    【20170921】(Unfinished)2017暑假北京学习 day 2
    (Unfinished)2017暑假北京学习 day 2
    Openjudge NOI题库 数论4975 两只鼹鼠
    Openjudge NOI题库 数论185 反正切函数的应用
    Noip1998 提高组3 卢斯加法表
    【自己的小玩具程序】化学方程式配平【测试中】【未完成】
    Code Vs 1010 过河卒
    NOI 练手题 图像旋转翻转变换
  • 原文地址:https://www.cnblogs.com/smallhester/p/10305365.html
Copyright © 2020-2023  润新知