题目大意
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.
题目链接
分析
两次dfs即可求树的直径(树的直径可能不止一条),不过对这题来讲是没有影响的。对于树的直径的探讨我们以后再详细探讨。
代码
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 1e5 + 10;
int n, m, cnt;
int head[N];
struct edge{
int to, nxt;
}e[N << 1];
inline int read(){
int x = 0, op = 1;
char ch = getchar();
while (!isdigit(ch)){
if (ch == '-') op = -1;
ch = getchar();
}
while (isdigit(ch)){
x = (x << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
return x * op;
}
inline void add(int u, int v){
e[++cnt] = {v, head[u]};
head[u] = cnt;
}
int s1, maxVal;
void dfs(int u, int fa, int dep){
if (maxVal < dep){
maxVal = dep;
s1 = u;
}
for (int i = head[u]; i; i = e[i].nxt) {
int v = e[i].to;
if (v == fa) continue;
dfs(v, u, dep + 1);
}
}
int main() {
n = read(), m = read();
for (int i = 0, x, y; i < m; ++i) {
x = read(), y = read();
add(x, y), add(y, x);
}
dfs(1, -1, 0);
dfs(s1, -1, 0);
printf("%d\n", maxVal);
return 0;
}