libreoj#10153. 「一本通 5.2 例 1」二叉苹果树

libreoj10153
题解:dp[u][i]为u节点上保留i根树枝的至多保留的苹果数,那么转态转移方程便是dp[u][i]=max(dp[u][i],dp[u][i-k-1]+g[u][i].w+dp[v][k])

//bool operator <(const node &x)const{}//优先队列运算符重载
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL inf=2e18;
const int maxn=1006;
const LL mod=1e9+7;
int n,q;
struct Edge{
    int to,nxt;
    int w;
}es[205];
int head[maxn],cnt;
int dp[105][105];
void add(int u,int v,int w)
{
    ++cnt;
    es[cnt].to=v;
    es[cnt].w=w;
    es[cnt].nxt=head[u];
    head[u]=cnt;
}
void dfs(int u,int fa)
{
    for(int i=head[u];i;i=es[i].nxt){
        int to=es[i].to;
        //printf("es[i].w:%d\n",es[i].w);
        if(to==fa)continue;
        dfs(to,u);
        for(int j=q;j>=1;j--){//在这里一定从大到小dp否则就会重复利用之前的dp[u][j],从而导致多算
            for(int k=0;k<j;k++){
                dp[u][j]=max(dp[u][j],dp[u][j-k-1]+es[i].w+dp[to][k]);
            }
        }
    }
}
int main()
{
    cin>>n>>q;
    for(int i=1;i<=n-1;i++){
        int s,e,w;
        cin>>s>>e>>w;
        add(s,e,w);add(e,s,w);
    }
    dfs(1,0);
    printf("%d\n",dp[1][q]);
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值