zoukankan      html  css  js  c++  java
  • 【poj Roads in the North】 题解

    题目链接:http://poj.org/problem?id=2631

    求树的直径模板。

    定理:

    树上任意一个点的在树上的最长路一定以树的直径的两端点其中一点结束。

    做法:

    两边bfs,第一次先找到node(树的直径的两端点其中一个),再一次求node的最长路所结束的点t
    node—>t就是树的直径

    #include <queue>
    #include <cstdio>
    #include <cstring>
    #include <iostream>
    #include <algorithm>
    using namespace std;
    const int maxn = 100010;
    int n, dis[maxn], ans, node;
    bool vis[maxn];
    struct edge{
        int from, to, next, len;
    }e[maxn<<2];
    int cnt, head[maxn];
    void add(int u, int v, int w)
    {
        e[++cnt].from = u;
        e[cnt].next = head[u];
        e[cnt].len = w;
        e[cnt].to = v;
        head[u] = cnt;
    }
    queue<int> q;
    void bfs(int s)
    {
        vis[s] = 1;
        q.push(s);
        while(!q.empty())
        {
            int now = q.front(); q.pop();
            for(int i = head[now]; i != -1; i = e[i].next)
            {
                if(vis[e[i].to] == 0)
                {
                    dis[e[i].to] = dis[now] + e[i].len;
                    vis[e[i].to] = 1;
                    q.push(e[i].to);
                    if(dis[e[i].to] > ans)
                    {
                        ans = dis[e[i].to];
                        node = e[i].to;
                    }
                }
            }
        }
    }
    int main()
    {
        memset(head, -1, sizeof(head));
        int u, v, w;
        while(scanf("%d%d%d",&u, &v, &w) == 3)
        {
            add(u, v, w);
            add(v, u, w);
        }
        memset(dis, 0, sizeof(dis));
        memset(vis, 0, sizeof(vis));
        ans = 0;
        bfs(1);
        
        memset(vis, 0, sizeof(vis));
        dis[node] = 0;
        ans = 0;
        bfs(node);
        
        printf("%d
    ", ans);
        return 0;
    }
    

    //Misaka_Azusa
    //dsbdsb

  • 相关阅读:
    4、springboot之全局异常捕获
    3、springboot之热部署
    可重入锁
    2、springboot返回json
    1、springboot之HelloWorld
    [转]查询 SQL Server 系统目录常见问题
    设计模式原则详解
    [转]第二章 控制反转和依赖注入
    [转]Spring.Net介绍
    [转]Oracle High Water Level高水位分析
  • 原文地址:https://www.cnblogs.com/MisakaAzusa/p/9778945.html
Copyright © 2011-2022 走看看