POJ 3585 Accumulation Degree (算竞赛进阶习题)

树形dp二次扫描换根

先dp一次求出每个点为根的流量最大值。

然后用f[i]表示以i为源点整体流量的最大值,可以发现f[root] = dp[root]

然后考虑访问子节点,假设子节点为u,那么dp[u]肯定是f[u]的一部分,还有一部分就是流向父亲节点所在子树的流量。

在访问该节点前我们如果已知f[s],那么从u流向父亲节点的流量显然就是min(f[s] - min(w(s, u), dp[u]), w(s, u))

因此我们也可以一次dfs递推得到答案,如果父亲节点度数为1,需要特判,这时候流量直接就是w(s, u),因为没有别的边有流量流出了

#include <iostream>
#include <cstring>
#include <cstdio>
#define INF 0x3f3f3f3f
#define full(a, b) memset(a, b, sizeof a)
#define FAST_IO ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
using namespace std;
typedef long long ll;
inline int lowbit(int x){ return x & (-x); }
inline int read(){
    int ret = 0, w = 0; char ch = 0;
    while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
    while(isdigit(ch)) ret = (ret << 3) + (ret << 1) + (ch ^ 48), ch = getchar();
    return w ? -ret : ret;
}
inline int gcd(int a, int b){ return b ? gcd(b, a % b) : a; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template <typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template <typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template <typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){
    A ans = 1;
    for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
    return ans;
}
const int N = 200005;
int _, n, cnt, head[N], dp[N], d[N], f[N];
struct Edge { int v, next, cpct; } edge[N<<1];

void addEdge(int a, int b, int c){
    edge[cnt].v = b, edge[cnt].cpct = c, edge[cnt].next = head[a], head[a] = cnt ++;
}

void init(){
    cnt = 0;
    full(head, -1), full(d, 0);
}

void dfs(int s, int fa){
    dp[s] = 0;
    for(int i = head[s]; i != -1; i = edge[i].next){
        int u = edge[i].v;
        if(u == fa) continue;
        dfs(u, s);
        if(d[u] == 1) dp[s] += edge[i].cpct;
        else dp[s] += min(dp[u], edge[i].cpct);
    }
}

void calc(int s, int fa){
    for(int i = head[s]; i != -1; i = edge[i].next){
        int u = edge[i].v;
        if(u == fa) continue;
        if(d[s] == 1) f[u] = dp[u] + edge[i].cpct;
        else f[u] = dp[u] + min(f[s] - min(dp[u], edge[i].cpct), edge[i].cpct);
        calc(u, s);
    }
}

int main(){

    for(_ = read(); _; _ --){
        init();
        n = read();
        for(int i = 1; i <= n - 1; i ++){
            int u = read(), v = read(), c = read();
            d[u] ++, d[v] ++;
            addEdge(u, v, c), addEdge(v, u, c);
        }
        dfs(1, 0), f[1] = dp[1], calc(1, 0);
        int ans = 0;
        for(int i = 1; i <= n; i ++) ans = max(ans, f[i]);
        printf("%d\n", ans);
    }
    return 0;
}

转载于:https://www.cnblogs.com/onionQAQ/p/11203217.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值