zoukankan      html  css  js  c++  java
  • bzoj1509

    树的直径

    我先开始以为是个图,想想并不知道什么求图的直径的方法,结果是棵树

    那么直觉告诉我们是在直径上面,实际上就是直径+min(i->u,i->v),扫一遍就行了

    #include<bits/stdc++.h>
    using namespace std;
    const int N = 200010;
    namespace IO 
    {
        const int Maxlen = N;
        char buf[Maxlen], *C = buf;
        int Len;
        inline void read_in()
        {
            Len = fread(C, 1, Maxlen, stdin);
            buf[Len] = '';
        }
        inline void fread(int &x) 
        {
            x = 0;
            int f = 1;
            while (*C < '0' || '9' < *C) { if(*C == '-') f = -1; ++C; }
            while ('0' <= *C && *C <= '9') x = (x << 1) + (x << 3) + *C - '0', ++C;
            x *= f;
        }
        inline void read(int &x)
        {
            x = 0;
            int f = 1; char c = getchar();
            while(c < '0' || c > '9') { if(c == '-') f = -1; c = getchar(); }
            while(c >= '0' && c <= '9') { x = (x << 1) + (x << 3) + c - '0'; c = getchar(); }
            x *= f;
        }
        inline void read(long long &x)
        {
            x = 0;
            long long f = 1; char c = getchar();
            while(c < '0' || c > '9') { if(c == '-') f = -1; c = getchar(); }
            while(c >= '0' && c <= '9') { x = (x << 1ll) + (x << 3ll) + c - '0'; c = getchar(); }
            x *= f;
        } 
    } using namespace IO;
    struct edge {
        int to;
        long long w;
        edge(int to = 0, long long w = 0) : to(to), w(w) {}
    };
    int n, m, root;
    long long ans;
    vector<edge> G[N];
    long long f[N], g[N], d[N];
    void dfs(int u, int last, long long d[])
    {
        if(d[u] > d[root]) root = u;
        for(int i = 0; i < G[u].size(); ++i)
        {
            edge e = G[u][i];
            if(e.to == last) continue;
            d[e.to] = d[u] + e.w;
            dfs(e.to, u, d);
        }    
    }
    int main()
    {
        read(n);
        read(m);
        for(int i = 1; i <= m; ++i)
        {
            int u, v; 
            long long w;
            read(u);
            read(v);
            read(w);
            G[u].push_back(edge(v, w));
            G[v].push_back(edge(u, w));
        }
        dfs(1, 0, f);
        int u = root;
        root = 0;
        dfs(u, 0, g);
        long long dis = g[root];
        u = root;
        root = 0;
        dfs(u, 0, d);
        for(int i = 1; i <= n; ++i) ans = max(ans, dis + min(d[i], g[i]));
        printf("%lld
    ", ans);
        return 0;
    }
    View Code
  • 相关阅读:
    java笔试之数字颠倒
    java笔试之取近似值
    java笔试之求int型正整数在内存中存储时1的个数
    js日期格式化Date
    【算法导论C++代码】归并排序
    Unity3D 错误nativeVideoFrameCallback的解决方法
    Unity3D脚本(MonoBehaviour)生命周期分析
    Unity3D 移动MM failed to find resource file{mmiap.xml}解
    Unity3D C#打开外部应用程序,并检测应用程序是否关闭退出
    Unity3d脚本执行顺序详解
  • 原文地址:https://www.cnblogs.com/19992147orz/p/7380151.html
Copyright © 2011-2022 走看看