Helvetic Coding Contest 2016 C2. Brain Network (medium)

来源:互联网 发布:淘宝优惠券去哪里领 编辑:程序博客网 时间:2024/05/22 09:04

C2. Brain Network (medium)
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard 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 uand 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 31 21 31 4
output
2
input
5 41 22 33 43 5
output
3

题目大意:

给出一棵树,求最长的路径


题解:

先DFS一遍,找出一条最长路径的最末端节点,再从这个点DFS一次,从而找出最长路径。

例如第一个样例:


1、先找从1出发的最长路径,若有多条,随便一条都可以。

2、找到2,把它作为下一次的起点,再做一次DFS

#include <cstdio>#include <cstring>#include <algorithm>#include <vector>using namespace std;const int maxn = 1e5 + 10;int n, m, ans, leaf, len[maxn];bool mark[maxn];vector<int> v[maxn];void Dfs(int cur, int  pre, int len) {if (len > ans) {ans = len;leaf = cur;}for (auto to: v[cur]) {if (to != pre) {Dfs(to, cur, len + 1);}}}int main() {#ifndef ONLINE_JUDGEfreopen("in.txt", "r", stdin);#endifwhile (scanf("%d%d", &n, &m) != EOF) {for (auto &i: v) {i.clear();}for (int i = 0, a, b; i < m; ++i) {scanf("%d%d", &a, &b);v[a].push_back(b);v[b].push_back(a);}ans = 0;Dfs(1, 0, 0);ans = 0;Dfs(leaf, 0, 0);printf("%d\n", ans);}return 0;}


0 0
原创粉丝点击