【秋招笔试题】矿脉开采(树形DP)

在这里插入图片描述
此题直接按树形dp做即可,每次从0枚举到k转移状态

#include <iostream>
#include <cstring>
#include <algorithm>


using namespace std;
#define endl '\n'
#define lson node << 1
#define rson node << 1 | 1
const int maxn = 1e5 + 5;
const int maxk = 100;
int dp[maxn][maxk],n,k,res;
int a[maxn];
int check(int node){
    if (node > n || a[node] == -1) return false;
    return true;
}
void dfs(int node){
    dp[node][1] = a[node];
    int maxx = 0;
    if (check(lson)){
        dfs(lson);
        maxx = max(maxx,dp[lson][0]);
        for (int i = 1; i <= k; ++i) {
            maxx = max(maxx,dp[lson][i]);
            dp[node][i] = max(dp[node][i],dp[lson][i - 1] + a[i]);
        }
    }
    if (check(rson)){
        dfs(rson);
        maxx = max(maxx,dp[rson][1]);
        for (int i = 1; i <= k; ++i) {
            maxx = max(maxx,dp[rson][i]);
            dp[node][i] = max(dp[node][i],dp[rson][i - 1] + a[i]);
        }
    }
    dp[node][0] = maxx;
    for (int i = 0; i <= k; ++i) {
        for (int j = 1; i + j + 1<= k; ++j) {
            dp[node][i + j + 1] = max(dp[node][i + j + 1],dp[lson][i] + dp[rson][j] + a[node]);
        }
    }
}

void solve(){
    cin >> k >> n;
    for (int i = 1; i <= n; ++i) {
        cin >> a[i];
    }
    dfs(1);
    for (int i = 0; i <= k; ++i) {
        res = max(res,dp[1][i]);
    }
    cout << res << endl;
}
signed main(){
    std::ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    solve();

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值