寻找自由的钥匙 NKOI 树形DP

题目描述
通向自由的钥匙被放n个房间里,这n个房间由n-1条走廊连接。但是每个房间里都有特别的保护魔法,在它的作用下,我无法通过这个房间,也无法取得其中的钥匙。虽然我可以通过消耗能量来破坏房间里的魔法,但是我的能量是有限的。那么,如果我最先站在1号房间(1号房间的保护魔法依然是有效的,也就是,如果不耗费能量,我无法通过1号房间,也无法取得房间中的钥匙),如果我拥有的能量为P,我最多能取得多少钥匙?

经典的树形DP
f[i][j]Ij便()

f[x][i]=max(key[x]+f[l[x]][j]+f[r[x]][ijcost[x]]);


pre

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#define N 100+5
using namespace std;
int n,m,f[N][N],r[N],l[N],key[N],cost[N];
bool vis[N],graph[N][N];
inline int read()
{
    int x = 0, f = 1; char ch = getchar();
    while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); }
    while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar(); }
    return x * f;
}
void Pre(int x)
{
    vis[x]=true;
    for(int i=1;i<=n;++i)
        if(!vis[i]&&graph[x][i])
        {
            r[i]=l[x];
            l[x]=i;
            Pre(i);
        }
    return;
}
void DFS(int x)
{
    if(l[x])DFS(l[x]);
    if(r[x])DFS(r[x]);
    for(int i=0;i<=m;++i)
    {
        f[x][i]=f[r[x]][i];
        for(int j=0;j<=i-cost[x];++j)
             f[x][i]=max(f[x][i],key[x]+f[l[x]][j]+f[r[x]][i-j-cost[x]]);
    }
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;++i)
        cost[i]=read(),key[i]=read();
    for(int i=1;i<n;++i)
    {int tmp1=read(),tmp2=read();graph[tmp1][tmp2]=graph[tmp2][tmp1]=true;}
    Pre(1);
    DFS(1);
    cout<<f[1][m];
}   

这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值