动态规划(算法竞赛、蓝桥杯)--树形DP积蓄程度

1、B站视频链接:E35 树形DP 积蓄程度_哔哩哔哩_bilibili

cpp 复制代码
#include <bits/stdc++.h> 
using namespace std;
const int N=200010,INF=0x3f3f3f3f;
int h[N],to[N*2],w[N*2],ne[N*2],tot;  //邻接表
int d[N];   //d[i]记录从i点向下流出的最大流量
int f[N];   //f[i]记录从i点向外流出的最大流量
int deg[N]; //deg[i]记录点i的度数

void add(int a, int b, int c){
  to[++tot]=b,w[tot]=c,ne[tot]=h[a],h[a]=tot;
}
int dfs_d(int u, int fa){ //从叶点向上递推,获取u点的下流量 
  for(int i=h[u];i;i=ne[i]){
    int v=to[i];
    if(v==fa) continue;   //避免向上查找 
    int s=dfs_d(v,u);     //返回v点的下流量 
    d[u]+=min(w[i], s);   //累加u点的下流量 
  } 
  if(deg[u]==1) return INF; //特判叶的情况 
  return d[u];              //返回u点的下流量 
}
void dfs_f(int u, int fa){ //从根点向下递推,获取v点的全流量
  for(int i=h[u];i;i=ne[i]){
    int v=to[i];
    if(v==fa) continue;       
    if(deg[u]==1) f[v]=d[v]+w[i]; //特判根的情况 
    else f[v]=d[v]+min(w[i],f[u]-min(w[i],d[v])); 
    dfs_f(v, u);
  }
}
int main(){
  int t, n;
  scanf("%d", &t);
  while(t--){
    scanf("%d", &n);
    tot = 0;
    memset(h, 0, sizeof h);
    memset(d, 0, sizeof d);  
    memset(f, 0, sizeof f);     
    memset(deg, 0, sizeof deg);
    for(int i=1; i<n; i++){
      int a, b, c;
      scanf("%d%d%d", &a, &b, &c);
      add(a, b, c), add(b, a, c);
      deg[a]++, deg[b]++;
    }
    
    dfs_d(1,-1);  //向上递推下流量 
    f[1]=d[1];    //根只有向下的流量 
    dfs_f(1,-1);  //向下递推全流量 
    int ans=0;
    for(int i=1;i<=n;i++) ans=max(ans,f[i]);
    printf("%d\n",ans);
  }
  return 0;
}
相关推荐
KYGALYX几秒前
逻辑回归详解
算法·机器学习·逻辑回归
铉铉这波能秀9 分钟前
LeetCode Hot100数据结构背景知识之集合(Set)Python2026新版
数据结构·python·算法·leetcode·哈希算法
踢足球092912 分钟前
寒假打卡:2026-2-8
数据结构·算法
IT猿手23 分钟前
基于强化学习的多算子差分进化路径规划算法QSMODE的机器人路径规划问题研究,提供MATLAB代码
算法·matlab·机器人
千逐-沐风23 分钟前
SMU-ACM2026冬训周报3rd
算法
铉铉这波能秀1 小时前
LeetCode Hot100数据结构背景知识之元组(Tuple)Python2026新版
数据结构·python·算法·leetcode·元组·tuple
晚霞的不甘1 小时前
Flutter for OpenHarmony 实现计算几何:Graham Scan 凸包算法的可视化演示
人工智能·算法·flutter·架构·开源·音视频
㓗冽1 小时前
60题之内难题分析
开发语言·c++·算法
大江东去浪淘尽千古风流人物1 小时前
【VLN】VLN仿真与训练三要素 Dataset,Simulators,Benchmarks(2)
深度学习·算法·机器人·概率论·slam
铉铉这波能秀2 小时前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary