您的位置:首页 > 大数据 > 人工智能

CodeForces 690C2 Brain Network (树上最大距离)

2016-07-28 15:27 639 查看
题目链接

题目描述

C2. Brain Network (medium)

time limit per test2 seconds

memory limit per test256 megabytes

inputstandard input

outputstandard output

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 a b 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一遍,找出一条最长路径的最末端节点(从任一结点p开始dfs找出离这个结点距离最长的结点s),再从这个点s开始再dfs一次找到与s距离最长的点t,s和t的距离就是树上最长路径。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
const int maxn=100000+5;
vector<int> G[maxn];
int _max,flag;
void dfs(int u,int fa,int dep)
{
for(int i=0;i<G[u].size();i++)
{
int v=G[u][i];
if(v==fa) continue;
if(dep+1>_max)
{
_max=dep+1;
flag=v;
}
dfs(v,u,dep+1);
}
}
void init()
{
for(int i=0;i<maxn;i++) G[i].clear();
_max=0,flag=-1;
}
int main()
{
//freopen("in.txt","r",stdin);
int n,m;
while(~scanf("%d%d",&n,&m))
{
init();
for(int i=0;i<m;i++)
{
int p,q;
scanf("%d%d",&p,&q);
G[p].push_back(q);
G[q].push_back(p);
}
dfs(1,-1,0);
_max=0;
dfs(flag,-1,0);
printf("%d\n",_max);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐