DP/DFS - 樹形DP - 樹的最長路徑

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

思路:

dfs無向邊建圖,dfs樹中最長路徑和次長路徑即可。

代碼:

#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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章