思路:
直接从最大的儿子跳到次大的儿子就完成了转移
c o d e code code
#include<iostream>
#include<cstdio>
using namespace std;
const int MAXN = 1e6 + 10;
int n, m, ru[MAXN], maxx[MAXN], f[MAXN];
int head[MAXN], tot, ans;
struct node {
int to, next;
}b[MAXN * 2];
void add(int x, int y) {
b[++ tot] = (node) { y, head[x] };
head[x] = tot;
}
void dfs(int x, int fa) {
int d = 0;
for(int i = head[x]; i; i = b[i].next) {
int y = b[i].to;
if(y == fa) continue;
d ++;
dfs(y, x);
}
if(d == 0) { f[x] = 1; maxx[x] = 1; }
if(d == 1) {
for(int i = head[x]; i; i = b[i].next) {
int y = b[i].to;
if(y == fa) continue;
maxx[x] = maxx[y] + 1;
f[x] = maxx[x];
}
}
if(d >= 2) {
int M = 0, CM = 0;
for(int i = head[x]; i; i = b[i].next) {
int y = b[i].to;
if(y == fa) continue;
if(maxx[y] > M) CM = M, M = maxx[y];
else if(maxx[y] == M) CM = M;
else if(maxx[y] > CM) CM = maxx[y];
}
maxx[x] = M + d;
f[x] = CM + M + d - 1;
}
if(fa != 0)
ans = max(ans, max(maxx[x], f[x] + 1));
else ans = max(ans, max(maxx[x], f[x]));
}
int main() {
scanf("%d%d", &n, &m);
for(int i = 1; i <= m; i ++) {
int x, y;
scanf("%d%d", &x, &y);
add(x, y), add(y, x), ru[x] ++, ru[y] ++;
}
dfs(1, 0);
printf("%d", ans);
return 0;
}