P1131 [ZJOI2007]时态同步 (树上dp水题)

题目链接

思路: 感觉这题是写过树上dp里面最水的一题了233

dp[rt]表示以rt为根的树,修改所需最小值.

具体过程看代码注释

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<stdlib.h>
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<vector>
#include<stack>
#include<queue>
#include<map>
#include<math.h>
#include<set>
using namespace std;
#define LL long long
#define ULL unsigned long long
const int INF=0x3f3f3f3f;
const double eps=1e-5;
const int maxn=5e5+5;
struct
{
    int to,w,next;
}edge[maxn];
int head[maxn],cnt=1;
int max_time[maxn];//以i为根的子树中,i的所有孩子所需的最大时间,通过dfs回溯来维护
LL dp[maxn];
int root,n;
void add(int from,int to,int w)
{
    edge[cnt].to=to;
    edge[cnt].w=w;
    edge[cnt].next=head[from];
    head[from]=cnt++;
}
void dfs(int rt,int par)
{
    vector<int> time;//存所有孩子节点的权值
    int mmax=0;//存孩子节点中的最大权值
    for(int i=head[rt];i;i=edge[i].next)
    {
        int to=edge[i].to;
        if(to==par) continue;
        dfs(to,rt);
        dp[rt]+=dp[to];
        edge[i].w+=max_time[to];//根到i孩子的权值 加上max_time[i],就成了根到最远叶子的权值
        time.push_back(edge[i].w);
        mmax=max(mmax,edge[i].w);
    }
    max_time[rt]=mmax;
    for(int i=0;i<time.size();i++) dp[rt]=dp[rt]+mmax-time[i];//把差值加上即可
}
int main()
{
//    ios::sync_with_stdio(false);
//    cin.tie(0);
//    cout.tie(0);
    scanf("%d%d",&n,&root);
    for(int i=1;i<n;i++)
    {
        int v,u,w;
        scanf("%d%d%d",&v,&u,&w);
        add(v,u,w),add(u,v,w);
    }
    dfs(root,-1);
    printf("%lld\n",dp[root]);
    system("pause");
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值