• 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
  • 相关阅读:
    实用Javascript调试技巧
    fetch的常见问题及其解决办法
    为什么重复的GET请求变慢了?
    JavaScript深入浅出第4课:V8引擎是如何工作的?
    一步一步搭建前端监控系统:如何定位前端线上问题?
    如何使用 Set 来提高JS代码的性能
    详解Vue的slot新用法
    详解Vue响应式原理
    BeautyWe.js 一套专注于微信小程序的开发范式
    await Task.Yield()和await Task.CompletedTask有什么不同
  • 原文地址:https://www.cnblogs.com/smallhester/p/10305365.html
Copyright © 2020-2023  润新知