AcWing 4706 -- 树形DP/DFS

题目描述

4706. 最短路程

思路

dfs代码

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>

using namespace std;

const int N = 100010, M = N << 1;

typedef pair<int, int> PII;

int n;
long long f[N][2];
vector<PII> e[N];

void dfs(int u, int fa)
{
    long long s = 0;
    for(auto [ne, w] : e[u])
    {
        if(ne == fa)    continue;
        dfs(ne, u);
        f[u][0] += f[ne][0] + w * 2;
        s = max(s, f[ne][0] + w - f[ne][1]);
    }
    f[u][1] = f[u][0] - s;
}

int main()
{
    cin >> n;
    for(int i = 0; i < n - 1; i ++ )
    {
        int a, b, c;
        cin >> a >> b >> c;
        e[a].push_back({b, c});
        e[b].push_back({a, c});
    }
    
    dfs(1, -1);
    cout << f[1][1] << endl;
    
    return 0;
}

树形dp代码

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>

using namespace std;

const int N = 100010, M = N << 1;

typedef pair<int, int> PII;

int n;
long long f[N][2];
vector<PII> e[N];

void dfs(int u, int fa)
{
    long long s = 0;
    for(auto [ne, w] : e[u])
    {
        if(ne == fa)    continue;
        dfs(ne, u);
        f[u][0] += f[ne][0] + w * 2;
        s = max(s, f[ne][0] + w - f[ne][1]);
    }
    f[u][1] = f[u][0] - s;
}

int main()
{
    cin >> n;
    for(int i = 0; i < n - 1; i ++ )
    {
        int a, b, c;
        cin >> a >> b >> c;
        e[a].push_back({b, c});
        e[b].push_back({a, c});
    }
    
    dfs(1, -1);
    cout << f[1][1] << endl;
    
    return 0;
}

借鉴

树形dp
dfs

posted @ 2022-10-16 15:44  光風霽月  阅读(16)  评论(0编辑  收藏  举报