懒虫读诗 (树形dp+分组背包)

这篇博客讨论了一种程序设计竞赛中的问题,即在一个森林结构中选择节点以最大化权值,每个节点的选择必须包含其父节点。通过将森林转化为一棵树,并使用动态规划策略,将问题转化为分组背包问题进行解决。代码示例展示了如何实现这一算法,以求解最大开心度之和。

懒虫读诗

[Link](第五届石家庄铁道大学程序设计竞赛_ACM/NOI/CSP/CCPC/ICPC算法编程高难度练习赛_牛客竞赛OJ (nowcoder.com))

题意

给你一个森林,每个点都有权值,选某个点就一定要选它的父节点,问你选m个点的最大权值是多少。

题解

首先加一个权值为0的0号结点,每个树的根向他连一条边就变成了一颗树了。我们设 f ( i , j ) f(i,j) f(i,j)表示以 i i i号结点为根的子树选了 j j j篇文章的最大开心度之和,然后按照 i i i的每个子树选了几篇文章来划分状态进而转移这个过程,变成一个分组背包问题。我们依次枚举子树选多少和转移决策即可,注意至少选一个,因为有依赖性所以这个结点必须选,枚举决策时子树选则的文章和必须小于当前这个树的文章和,因为当前这个树的根一定选。

Code

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <set>
#include <queue>
#include <vector>
#include <map>
#include <bitset>
#include <unordered_map>
#include <cmath> 
#include <stack>
#include <iomanip>
#include <deque> 
#include <sstream>
#define x first
#define y second
#define debug(x) cout<<#x<<":"<<x<<endl;
using namespace std;
typedef long double ld;
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<double, double> PDD;
typedef unsigned long long ULL;
const int N = 330, M = 2 * N, INF = 0x3f3f3f3f, mod = 1e9 + 7;
const double eps = 1e-8, pi = acos(-1), inf = 1e20;
#define tpyeinput int
inline char nc() {static char buf[1000000],*p1=buf,*p2=buf;return p1==p2&&(p2=(p1=buf)+fread(buf,1,1000000,stdin),p1==p2)?EOF:*p1++;}
inline void read(tpyeinput &sum) {char ch=nc();sum=0;while(!(ch>='0'&&ch<='9')) ch=nc();while(ch>='0'&&ch<='9') sum=(sum<<3)+(sum<<1)+(ch-48),ch=nc();}
int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};
int h[N], e[M], ne[M], idx;
void add(int a, int b, int v = 0) {
    e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
int n, m, k;
int a[N], f[N][N];
int w[M];
void dp(int u) {
    for (int i = 1; i <= m + 1; i ++ ) f[u][i] = w[u];
    for (int i = h[u]; ~i; i = ne[i] ) {
        int j = e[i]; dp(j);
        for (int a = m + 1; a; a -- ) 
            for (int b = 0; b < a; b ++)
             f[u][a] = max(f[u][a], f[u][a - b] + f[j][b]);
    }
}
int main() {
    ios::sync_with_stdio(false), cin.tie(0);
    cin >> n >> m;
    memset(h, -1, sizeof h);
    for (int i = 1; i <= n; i ++ ) {
        int u; cin >> u >> w[i];
        add(u, i);
    }
    dp(0);
    cout << f[0][m + 1] << endl;
    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值