题目链接:
http://hihocoder.com/problemset/problem/1224
题意:
题解:
首先我们先dfs出最长链,然后我们再dfs出每一个点能够最长延展多少
然后最后答案就是最长链的长度+最长延展多少就好了
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MS(a) memset(a,0,sizeof(a))
#define MP make_pair
#define PB push_back
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
//////////////////////////////////////////////////////////////////////////
const int maxn = 1e5+10;
vector<int> G[maxn];
int d[maxn],vis[maxn],fa[maxn];
void dfs(int x,int deep){
d[x] = deep;
for(auto v : G[x]){
if(vis[v]) continue;
fa[v] = x;
dfs(v,deep+1);
}
}
int main(){
int n=read();
for(int i=1; i<n; i++){
int u=read(),v=read();
G[u].push_back(v);
}
dfs(1,0);
int bf=1,ans1 = 0;
for(int i=1; i<=n; i++){
if(d[i] > ans1){
ans1 = d[i];
bf = i;
}
}
while(bf != 1){
vis[bf] = 1;
bf = fa[bf];
}
vis[1] = 1;
for(int i=1; i<=n; i++){
if(vis[i])
dfs(i,0);
}
int ans2 = 0;
for(int i=1; i<=n; i++)
if(!vis[i])
ans2 = max(d[i],ans2);
cout << ans1+ans2 << endl;
return 0;
}