zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    74HC165并转串级联芯片学习记录
    道砟电阻 钢轨阻抗 列车分路电阻
    电压的有效值、平均值与峰值
    铁路信号继电器
    C语言语法记录
    程序编译过程中错误记录
    min-max容斥
    矩阵树定理
    题解 SP1812 【LCS2
    杜教筛
  • 原文地址:https://www.cnblogs.com/smallhester/p/10305365.html
Copyright © 2011-2022 走看看