[bzoj1060][zjoi2007]时态同步

一个很有意思的树上dp题。
贪心地注意到,对于更靠近根的边使用「技能」是更优的。
所以对于每一课子树而言,我们先使用技能统一「差值」,使得对于每一个节点,他的每一个子节点时间相同。
这样就出现了重叠子问题,引导我们使用递归(dp)。
具体地,我们定义f[i]为对于i,其子树中的节点到它的最长距离。
那么答案就是sigma(f[x]-sigma(f[y]+v(x,y)))

#include <bits/stdc++.h>
using namespace std;
const int maxn = 500005; ////////////////////
int n, s;
int f[maxn] = {0};
long long ans = 0;
struct edge {
    int to, value;
};
vector<edge> g[maxn];
int vis[maxn];
void dfs(int root, int fa) {
    vector<edge>::iterator it;
    for(it = g[root].begin(); it != g[root].end(); it++) {
        edge v = *it;
        if(v.to!=fa) {
            dfs(v.to, root);
            f[root] = max(f[root], f[v.to]+v.value);
        }
    }
    for(it = g[root].begin(); it!=g[root].end(); it++) {
        edge v= *it;
        if(v.to!=fa)ans+=f[root]-f[v.to]-v.value;
    }
}
int main() {
    scanf("%d\n%d", &n, &s);
    for(int i = 0; i < n-1; i++) {
        int a, b, t;
        scanf("%d %d %d", &a, &b, &t);
        g[a].push_back((edge){b,t});
        g[b].push_back((edge){a, t});
    }
    dfs(s, 0);
    printf("%lld", ans);
} 

posted on   蒟蒻konjac  阅读(190)  评论(0编辑  收藏  举报

编辑推荐:
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
阅读排行:
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单
· C# 13 中的新增功能实操
· Supergateway:MCP服务器的远程调试与集成工具
· Vue3封装支持Base64导出的电子签名组件
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示