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
  • 相关阅读:
    awk常用命令
    Linux 指令篇:使用者管理--sudo
    sax解析xml案例一
    DefaultHandler类
    Linux上vi(vim)编辑器使用教程
    SecureCRT上传下载数据的方法
    K近邻的决策边界以及K的影响
    KNN交叉验证,找出合适的K值
    KNN(K邻近值算法)手动版与库函数调用版
    linear_model.LinearRegression()线性回归之身高预测体重
  • 原文地址:https://www.cnblogs.com/smallhester/p/10305365.html
Copyright © 2011-2022 走看看