zoukankan      html  css  js  c++  java
  • 树的直径:小叶的巡查

    题目源https://www.nowcoder.com/acm/contest/181/D

    一看到这题,诶,有树,求最长路,于是,很自然的什么都没想到于是,就想跑两遍spfa来求解,样例过去,没AC;

    然后知道这道题其实就是一道赤果果的树的直径的模板题,去搜了一下资料:树的直径用两遍dfs就搞出来了,至于证明什么的都不难。

    那么就先贴出ac的代码。(除了树的直径,我还见识了vector的强大)

    #include<bits/stdc++.h>
    using namespace std;
    struct node{
        int to;
        long long w;
    };
    bool vis[100000];
    vector<node>a[300000];
    long long maxs=-1;
    int cnt;
    void dfs(int u,long long p)
    {
        vis[u]=1;
        if(p>maxs)
        {
            maxs=p;
            cnt=u;
        }
        int m=a[u].size();
        for(int i=0;i<m;i++)
        {
            int v=a[u][i].to;
            if(!vis[v])
            {
                dfs(v,p+a[u][i].w);
            }
        }
    }
    int main()
    {
        memset(vis,0,sizeof vis);
        int n;cin>>n;
        for(int i=1;i<n;i++)
        {
            int u,v;long long w;
            cin>>u>>v>>w;
            node x={v,w};
            node y={u,w};
            a[u].push_back(x);
            a[v].push_back(y);
        }
        dfs(1,0);
        memset(vis,0,sizeof vis);
        dfs(cnt,0);
        long long ans=maxs*10+(1+maxs)*maxs/2;
        cout<<ans;
    } 
  • 相关阅读:
    kibana ,logstash and filebeat
    The Run-Time Constant Pool The Constant Pool
    hsdb
    The Dataflow Model: A Practical Approach to Balancing
    编译器
    汇编
    状态机
    lsm-tree
    Serviceability
    JIT编译器
  • 原文地址:https://www.cnblogs.com/719666a/p/9568270.html
Copyright © 2011-2022 走看看