1 条题解

  • 0
    @ 2021-8-8 1:33:34

    C++ :

    
    #include<bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    const int maxn = 2e5 + 10;
    vector<pair<int, ll> > e[maxn];
    ll dp[maxn]; //
    ll ans[maxn];
    int n;
     
    void dfs1(int u, int fa) //
    {
        ll tmp = 0;
        for(auto x : e[u])
        {
            int v = x.first;
            if(v == fa) continue;
            //dp[v] = x.second;
            if(e[v].size() == 1) //
                dp[v] = e[v][0].second;
            dfs1(v, u);
            dp[u] += min(dp[v], x.second);
        }
    }
     
    void dfs(int u, int fa) //
    {
        ll tmp = 0; //
        for(auto x : e[u])
        {
            if(e[u].size() == 1)
                tmp = x.second;
            else
            {
                int v = x.first;
                tmp += min(dp[v], x.second);
            }
        }
        for(auto x : e[u]) //
        {
            int v = x.first; //
            if(v == fa) continue;
            ll rt = dp[u], son = dp[v];
            dp[u] = tmp; //
            if(e[u].size() > 1) //
               dp[u] = dp[u] - min(dp[v], x.second);
            dp[v] = 0;
            for(auto m : e[v]) //
            {
                dp[v] += min(dp[m.first], m.second);
            }
            ans[v] = dp[v]; //
            dfs(v, u);
            //dp[u] = rt, dp[v] = son; //
        }
    }
     
    int main()
    {
    
        int t;
        scanf("%d", &t);
        while(t--)
        {
            scanf("%d", &n);
            for(int i = 0; i <= n; ++i)
                e[i].clear(), dp[i] = 0;
            for(int i = 1; i < n; ++i)
            {
                int u, v, w;
                scanf("%d%d%d", &u, &v, &w);
                e[u].push_back(make_pair(v, w));
                e[v].push_back(make_pair(u, w));
            }
            dfs1(1, 0);
            ans[1] = dp[1];
            dfs(1, 0);
      
            ll res = -1e9;
            for(int i = 1; i <= n; ++i)
                res = max(res, ans[i]);
            printf("%lld\n", res);
        }
        return 0;
    }
     
     
    
    
    • 1

    信息

    ID
    198
    时间
    1000ms
    内存
    128MiB
    难度
    9
    标签
    递交数
    8
    已通过
    6
    上传者