講義解答(93ms)
#include <bits/stdc++.h>
#define fast_as_a_fuckboy ios_base::sync_with_stdio(0);cin.tie(0);
#define MAX 100001
using namespace std;
deque<int> F[MAX];
int md, rd;
int DFS(int x){
int max1, max2, result;
if(F[x].size() == 0) return 0; //沒有小孩
else if(F[x].size() == 1) return DFS(F[x][0])+1; //只有一個小孩
else{
for(int i = 0;i < F[x].size();i++){
result = DFS(F[x][i])+1;
if(i == 0) max1 = result;
else if(i == 1){
if(max1 >= result){
max2 = result;
}
else{
int tmp = max1;
max1 = result;
max2 = tmp;
}
}
else{
if(max1 <= result){
max2 = max1;
max1 = result;
}
else if(max2 < result){
max2 = result;
}
}
}
}
md = max(md, max1+max2);
return max1;
}
int main(){
fast_as_a_fuckboy;
vector<bool> ischild(MAX,false);
int a, b, root, n;
cin >> n;
for(int i = 1; i < n; i++){
cin >> a >> b;
F[a].push_back(b);
ischild[b] = true;
}
for(int i = 0; i < n; i++){
if(!ischild[i]){
root = i;
break;
}
}
rd = DFS(root);
md = max(md,rd);
cout << md << "\n";
}