Brain Network (medium)(DFS)

H - Brain Network (medium)

Time Limit:2000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u

CodeForces 690C2

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.

Sample Input

Input
4 3
1 2
1 3
1 4
Output
2
Input
5 4
1 2
2 3
3 4
3 5

Output

3

 

题意是 n ,m 是 n 点 m 边,然后 m 行边的描述,问这棵树的两节点最远距离是多少,两两相邻的节点距离算 1

//我还以为并查集能做,想了半天,然后发现实在想得太简单了

//从任一点 DFS 这棵树,到最远节点,然后再从最远节点 DFS 到最远节点,就是树的节点最远距离了

 

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <vector>
 4 using namespace std;
 5 
 6 vector<int> p[100005];
 7 int ans,far;
 8 
 9 void Dfs(int cur,int pre,int step)
10 {
11     if (step>ans)
12     {
13         ans=step;
14         far=cur;
15     }
16     int i,j;
17     for (i=0;i<p[cur].size();i++)
18     {
19         int to = p[cur][i];
20         if (to!=pre)//不回头
21         {
22             Dfs(to,cur,step+1);
23         }
24     }
25 }
26 
27 int main()
28 {
29     int n,m;
30     while (scanf("%d%d",&n,&m)!=EOF)
31     {
32         int i;
33         for (i=1;i<=n;i++)
34             p[i].clear();
35         for (i=1;i<=m;i++)
36         {
37             int a,b;
38             scanf("%d%d",&a,&b);
39             p[a].push_back(b);
40             p[b].push_back(a);
41         }
42         ans=0;
43         Dfs(1,0,0);
44         ans=0;
45         Dfs(far,0,0);
46         printf("%d\n",ans);
47     }
48     return 0;
49 }
View Code

 

 

 

posted @ 2016-09-30 21:16  happy_codes  阅读(206)  评论(0编辑  收藏  举报