【树的最长路径】

题目

错误代码(18过15)

#include <bits/stdc++.h>
using namespace std;
const int N = 1e4+10, M = N << 1;
const int null = -0x3f3f3f3f; 
int h[N], e[M], ne[M], w[M], idx;
int v[N];
int maxx;
int res;
int twice;
void add(int a, int b, int c)
{
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
void dfs(int f, int u, int cnt)
{
    bool has_son = false;
    for(int k = h[u]; ~k; k = ne[k])
    {
        int j = e[k];
        if(j == f) continue;
        else
        {
            dfs(u, j, cnt + w[k]);
            has_son = true;
        }
    }
    if(!has_son && cnt > maxx) maxx = cnt, twice = u;
    return;
}
int main()
{
    int n;
    cin >> n;
    memset(h, -1, sizeof h);
    for(int i = 1; i < n; i++)
    {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
        add(b, a, c);
    }
    
    maxx = null;
    dfs(0, 3, 0);
    maxx = null;
    dfs(0, twice, 0);
    res = maxx;
    cout << res;
    return 0;
}

原因

存在负权边,不能用两次dfs的结论得到树的最长路径

为了求最长路径的叶子节点产生的对于两种dfs的感想

void dfs(int f, int u, int cnt)
{
    bool has_son = false;
    for(int k = h[u]; ~k; k = ne[k])
    {
        int j = e[k];
        if(j == f) continue;
        else
        {
            dfs(u, j, cnt + w[k]);
            has_son = true;
        }
    }
    if(!has_son && cnt > maxx) maxx = cnt, twice = u;
    return;
}

这种dfs要求在递归终点就可以得到结果进行判优,同时进行记录递归终点,这就要求增加参数,要增加对于递归终点的判断。如果要得到路径,那得维护数组。总归容易记录,比较白盒

int dfs(int f, int u)
{
    int maxb = null;
    bool has_son = false;
    for(int k = h[u]; ~k; k = ne[k])
    {
        int j = e[k];
        if(j == f) continue;
        else
        {
            maxb = max(maxb, dfs(u, j) + w[k]);
            has_son = true;
        }
    }
    if(!has_son) return 0;
    else return maxb;
}

这种dfs不需要判断递归终点,且层层返回,这就要求返回的是从当前深度考虑到底部的最优值,需要比较,得到最终返回值。对于递归终点、递归路径,是黑盒的。

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值