Helvetic Coding Contest 2016 online mirror C2

Description

Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of its nervous system. More precisely, we define the distance between two brains u and v(1 ≤ u, v ≤ n) as the minimum number of brain connectors used when transmitting a thought between these two brains. The brain latency of a zombie is defined to be the maximum distance between any two of its brains. Researchers conjecture that the brain latency is the crucial parameter which determines how smart a given zombie is. Help them test this conjecture by writing a program to compute brain latencies of nervous systems.

In this problem you may assume that any nervous system given in the input is valid, i.e., it satisfies conditions (1) and (2) from the easy version.

Input

The first line of the input contains two space-separated integers n and m (1 ≤ n, m ≤ 100000) denoting the number of brains (which are conveniently numbered from 1 to n) and the number of brain connectors in the nervous system, respectively. In the next m lines, descriptions of brain connectors follow. Every connector is given as a pair of brains ab it connects (1 ≤ a, b ≤ n and a ≠ b).

Output

Print one number – the brain latency.

Examples
input
4 3
1 2
1 3
1 4
output
2
input
5 4
1 2
2 3
3 4
3 5
output
3

 求一棵树两点间的最大距离,我们可以先从第一个点开始dfs,走到据它最远的点,然后再拿这个点dfs,走到离这个点最远的点,最大值一直保持更新就行

#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int inf=(1<<30);
const int maxn=100005;
int pos;
int n,ans,vis[maxn],in[maxn];
vector<int>e[maxn];

void dfs(int v,int cnt)
{
    if(ans<cnt)
    {
        ans=cnt;
        pos=v;
    }
    if(vis[v])return;
    vis[v]=1;
    for(int i=0;i<e[v].size();i++)
        if(!vis[e[v][i]])
            dfs(e[v][i],cnt+1);
}

int main()
{
    int n,m;
    ans=0;
    scanf("%d%d",&n,&m);
    memset(in,0,sizeof(in));
    memset(vis,0,sizeof(vis));
    for(int i=1;i<=m;i++)
    {
        int u,v;
        scanf("%d%d",&u,&v);
        e[u].push_back(v);
        e[v].push_back(u);
    }
    dfs(2,0);
    //printf("%d
",ans);
  //  cout<<pos<<endl;
   memset(vis,0,sizeof(vis));
    dfs(pos,0);

    cout<<ans<<endl;
    return 0;
}

  

原文地址:https://www.cnblogs.com/yinghualuowu/p/5660596.html