Apple Tree(传送门)
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 10094 Accepted: 3354
Description
Wshxzt is a lovely girl. She likes apple very much. One day HX takes her to an apple tree. There are
N
nodes in the tree. Each node has an amount of apples. Wshxzt starts her happy trip at one node. She can eat up all the apples in the nodes she reaches. HX is a kind guy. He knows that eating too many can make the lovely girl become fat. So he doesn’t allow Wshxzt to go more than
Input
There are several test cases in the input
Each test case contains three parts.
The first part is two numbers
The second part contains
N
integers (All integers are nonnegative and not bigger than
The third part contains
Input will be ended by the end of file.
Note: Wshxzt starts at Node 1 .
Output
For each test case, output the maximal numbers of apples Wshxzt can eat at a line.
Sample Input
2 1
0 11
1 2
3 2
0 1 2
1 2
1 3
Sample Output
11
2
题意
给定一颗树,
解题思路
树形DP,设
dp[u][k][0]
,表示从
u
出发遍历子树返回
代码
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
#define lson rt << 1, l, mid
#define rson rt << 1|1, mid + 1, r
#define FIN freopen("input.txt", "r", stdin)
typedef pair<int, int> PII;
typedef long long LL;
const int MAXN = 2e2 + 5;
const int MAXM = 1e4;
struct Edge{
int u, v, nxt;
}E[MAXN];
int Head[MAXN], tot;
int N, K;
int dp[MAXN][MAXN << 1][2];
void edge_init(){
tot = 0;
memset(Head, -1, sizeof(Head));
}
void add_edge(int u,int v){
E[tot].u = u;
E[tot].v = v;
E[tot].nxt = Head[u];
Head[u] = tot ++;
}
void dfs(int pre, int u){
for(int i = Head[u]; ~i;i = E[i].nxt){
int v = E[i].v;
if(v == pre) continue;
dfs(u, v);
for(int j = K;j >= 1;j --){
for(int t = 1; t <= j;t ++){
dp[u][j][0] = max(dp[u][j][0], dp[u][j - t][1] + dp[v][t - 1][0]);
dp[u][j][0] = max(dp[u][j][0], dp[u][j - t][0] + dp[v][t - 2][1]);
dp[u][j][1] = max(dp[u][j][1], dp[u][j - t][1] + dp[v][t - 2][1]);
}
}
}
}
int main() {
//FIN;
int x, a, b;
while(~scanf("%d%d", &N, &K)){
memset(dp, 0, sizeof(dp));
edge_init();
for(int i = 1;i <= N;i ++){
scanf("%d", &x);
for(int j = 0;j <= K;j ++){
dp[i][j][0] = dp[i][j][1] = x;
}
}
for(int i = 1;i < N;i ++){
scanf("%d%d", &a, &b);
add_edge(a, b);
add_edge(b, a);
}
dfs(0, 1);
printf("%d\n", max(dp[1][K][0], dp[1][K][1]));
}
return 0;
}