题目描述
思路
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;
}