【Luogu3931】SAC E#1

problem

solution

codes

//树形DP
//f[u]:割掉u和u子树中所有的叶子节点所需要的最小代价
#include<iostream>
#include<vector>

using namespace std;
typedef long long LL;
const int N = (int)1e5+10, inf = 1e9;

int n, S;

struct node{
    LL to, v;
    node(LL to, LL v):to(to),v(v){};
};
vector<node>G[N];

LL f[N];
void dp(int u, int from){
    if(G[u].size()==1 && u!=S)f[u] = inf;
    for(int i = 0; i < G[u].size(); i++){
        LL v = G[u][i].to, t = G[u][i].v;
        if(v == from)continue; //BUG1因为双连通所以就要改参数,不能跟父节点一样,不然会死循环
        dp(v,u);
        f[u] += min(t, f[v]);
    }
}

int main(){
    cin>>n>>S;
    for(int i = 1; i <= n-1; i++){
        int a, b, c;  cin>>a>>b>>c;
        G[a].push_back(node(b,c));
        //BUG1:因为a与b谁是祖先不知道,所以要双连通
        G[b].push_back(node(a,c));
    }
    dp(S,-1);
    cout<<f[S]<<"
";
    return 0;
}
原文地址:https://www.cnblogs.com/gwj1314/p/9444714.html