只要求出根节点的每棵子树上所有蚂蚁走到根节点所用时间,这些时间的最大值就是答案。那么要求子树上所有蚂蚁到达根节点时间,先求出子树上所有叶子的深度,存在数组p中,在对p从小到大排序,i > 1, p[i] = max(p[i], p[i-1] + 1).若p的长度为len, 那么p[len-1]就是这个子树上的时间
#include <bits/stdc++.h>
#define maxn 500005
#define MOD 1000000007
using namespace std;
typedef long long ll;
vector<int> v[maxn], p;
int n;
void dfs(int j, int f, int h){
if(v[j].size() == 1){
p.push_back(h);
return ;
}
for(int i = 0; i < v[j].size(); i++){
int b = v[j][i];
if(b != f){
dfs(b, j, h+1);
}
}
}
int main(){
// freopen("in.txt", "r", stdin);
int a, b;
scanf("%d", &n);
for(int i = 0; i < n-1; i++){
scanf("%d%d", &a, &b);
v[a].push_back(b);
v[b].push_back(a);
}
int ans = 0;
for(int i = 0; i < v[1].size(); i++){
p.clear();
dfs(v[1][i], 1, 1);
sort(p.begin(), p.end());
for(int j = 1; j < p.size(); j++){
if(p[j] <= p[j-1])
p[j] = p[j-1] + 1;
}
ans = max(ans, p[p.size()-1]);
}
printf("%d\n", ans);
return 0;
}