E. Ants in Leaves
被秀智商的水题
#include <bits/stdc++.h>
using namespace std;
#define pii pair<int, int>
#define MP make_pair
#define ls (i<<1)
#define rs (i<<1|1)
#define md (ll+rr>>1)
#define N (1000000 + 10)
#define M (2000000 + 10)
#define inf 0x3f3f3f3f
#define ULL unsigned long long
#define LL long long
#define mod 1000000007
int fst[N], nxt[M], vv[M],e;
void init() {
memset(fst, -1, sizeof fst);
e = 0;
}
void add(int u,int v) {
vv[e] = v, nxt[e] = fst[u], fst[u] = e++;
}
int a[N], cnt, dep[N];
bool cmp(int a, int b) {
return dep[a] < dep[b];
}
void dfs(int u, int fa, int d) {
dep[u] = d;
bool l = 1;
for(int i = fst[u]; ~i; i = nxt[i]) {
int v = vv[i];
if(v == fa) continue;
l = 0;
dfs(v, u, d+1);
}
if(l)
a[cnt++] = u;
}
int res[N];
int main() {
int n;
scanf("%d", &n);
init();
int u, v;
for(int i = 1; i < n; ++i) {
scanf("%d%d", &u, &v);
add(u, v);
add(v, u);
}
int ans = 0;
for(int i = fst[1]; i != -1; i = nxt[i]) {
int v = vv[i];
cnt = 0;
dfs(v, 1, 1);
sort(a, a + cnt, cmp);
res[0] = dep[a[0]];
for(int j = 1; j < cnt; ++j) {
res[j] = max(res[j-1]+1, dep[a[j]]);
}
ans = max(ans, res[cnt-1]);
}
printf("%d\n", ans);
}