DP/DFS - 樹形DP - 樹的最長路徑
給定一棵樹,樹中包含 n 個結點(編號1~n)和 n−1 條無向邊,每條邊都有一個權值。
現在請你找到樹中的一條最長路徑。
換句話說,要找到一條路徑,使得使得路徑兩端的點的距離最遠。
注意:路徑中可以只包含一個點。
輸入格式
第一行包含整數 n。
接下來 n−1 行,每行包含三個整數 ai,bi,ci,表示點 ai 和 bi 之間存在一條權值爲 ci 的邊。
輸出格式
輸出一個整數,表示樹的最長路徑的長度。
數據範圍
1≤n≤10000,
1≤ai,bi≤n,
−105≤ci≤105
輸入樣例:
6
5 1 6
1 4 5
6 3 9
2 6 8
6 1 7
輸出樣例:
22
思路:
代碼:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=10010,M=2*N;
int h[N],e[M],ne[M],w[M],idx;
int ans,n;
void add(int a,int b,int c)
{
e[idx]=b,w[idx]=c,ne[idx]=h[a],h[a]=idx++;
}
int dfs(int u,int f)
{
int d1=0,d2=0;
for(int i=h[u];~i;i=ne[i])
{
int j=e[i];
if(j==f) continue;
int d=dfs(j,u)+w[i];
if(d>=d1) d2=d1,d1=d;
else if(d>d2) d2=d;
}
ans=max(ans,d1+d2);
return d1;
}
int main()
{
memset(h,-1,sizeof h);
scanf("%d",&n);
for(int i=0;i<n-1;i++)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add(a,b,c),add(b,a,c);
}
dfs(1, -1);
printf("%d\n",ans);
return 0;
}