博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ZOJ 3201
阅读量:6197 次
发布时间:2019-06-21

本文共 1885 字,大约阅读时间需要 6 分钟。

Time Limit: 1000MS   Memory Limit: 32768KB   64bit IO Format: %lld & %llu

Description

You're given a tree with weights of each node, you need to find the maximum subtree of specified size of this tree.

Tree Definition

A tree is a connected graph which contains no cycles.

Input

There are several test cases in the input.

The first line of each case are two integers N(1 <= N <= 100), K(1 <= K <= N), where N is the number of nodes of this tree, and K is the subtree's size, followed by a line with N nonnegative integers, where the k-th integer indicates the weight of k-th node. The following N - 1 lines describe the tree, each line are two integers which means there is an edge between these two nodes. All indices above are zero-base and it is guaranteed that the description of the tree is correct.

Output

One line with a single integer for each case, which is the total weights of the maximum subtree.

Sample Input

3 110 20 300 10 23 210 20 300 10 2

Sample Output

3040

Source

ZOJ Monthly, May 2009
树状DP~
#include 
#include
#include
#include
#include
using namespace std;#define maxn 105int n,k,dp[maxn][maxn],val[maxn];vector
edge[maxn];void dfs(int u,int y){ dp[u][1] = val[u]; for(int i = 0;i < edge[u].size();i ++) { int v = edge[u][i]; if(v == y) continue; dfs(v, u); for(int j = k;j > 0;j --) //相似01背包 for(int p = 0;p < j;p ++) { dp[u][j] = max(dp[u][j], dp[u][j-p] + dp[v][p]); } }}int main(){ int a, b,ans; while(scanf("%d%d", &n, &k) != EOF) { ans = -1; memset(dp, -1, sizeof(dp)); for(int i = 0;i < n;i ++) edge[i].clear(); for(int i = 0;i < n;i ++) scanf("%d", &val[i]); for(int i = 0;i < n-1;i ++) { scanf("%d%d",&a,&b); edge[a].push_back(b); edge[b].push_back(a); } dfs(0, -1); for(int i = 0;i < n;i ++) ans = max(ans, dp[i][k]); printf("%d\n", ans); } return 0;}

转载地址:http://ovjca.baihongyu.com/

你可能感兴趣的文章
易观发布《中国大件快递白皮书》德邦快递成为标准制定者
查看>>
OPPO Find X兰博基尼版到底有多受欢迎?网友:就是加价也要买
查看>>
都在讨论“无现金城市”标杆,东北三省表示:你看我们有戏么
查看>>
小牛电动递交招股书:拟募资1.5亿美元 李一男持股44%
查看>>
第十六届中博会两馆并举 展览面积16万平方米
查看>>
2019美洲杯分组出炉 巴西抽得上签 日本遭遇强敌
查看>>
四川宜宾:一男一女因悲观厌世 相约自缢死亡
查看>>
三部门整顿彩票高频快开游戏:1月16日起暂停派奖活动
查看>>
2018对啊网CPA优秀学员表彰大会暨颁奖典礼在京举行
查看>>
数据挖掘技能的分类和数据挖掘的常用方法的剖析
查看>>
最新阿里java开发岗四面:分布式+性能调优+锁+数据库等
查看>>
揭秘:阿里巴巴是如何防止信息泄露的?
查看>>
基于Kubernetes和Istio的Serverless框架Knative解析之Autoscaler
查看>>
一夜暴富的最简单方式是什么?
查看>>
经典js面试题:数组去重
查看>>
最近Android真的凉凉了?
查看>>
教你用Python动刷新抢12306火车票,附源码!
查看>>
percona toolkit 安装与使用
查看>>
chrome 插件实现mac地址获取
查看>>
深度学习和自然语言处理:诠释词向量的魅力
查看>>