【每日一题】6.Rinne Loves Edges (树形DP)
题目链接:Here
树形DP 算法讲解:Here
无向联通图其实就是树的形状,其次让我们以 s
为根使得所有的叶子节点不能到达根并且让删去边权的总和最小,那么就是典型的 树形DP 了。
\(dp_i\) 代表以节点 \(i\) 为根节点而其子树内的根节点无法达到根节点的最小代价,\(dp_i = min(dp_i,w_{i\dots_j})\)
using ll = long long;
const int N = 1e5 + 10;
vector<pair<int, int>> v[N];
ll n, m, s, dp[N];
void dfs(ll u, ll fa) {
ll w = 0;
bool flag = false;
for (auto i : v[u]) {
ll v = i.first, s = i.second;
if (v == fa) continue;
flag = true;
dfs(v, u);
w += min(dp[v], s);
}
if (flag) dp[u] = w;
}
void solve() {
cin >> n >> m >> s;
memset(dp, 0x3f, sizeof(dp));
for (int i = 0; i < m; ++i) {
ll a, b, c;
cin >> a >> b >> c;
v[a].push_back({b, c}), v[b].push_back({a, c});
}
dfs(s, 0);
cout << dp[s] << "\n";
}