Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 8672 | Accepted: 2884 |
Description
Input
Each test case contains three parts.
The first part is two numbers N K, whose meanings we have talked about just now. We denote the nodes by 1 2 ... N. Since it is a tree, each node can reach any other in only one route. (1<=N<=100, 0<=K<=200)
The second part contains N integers (All integers are nonnegative and not bigger than 1000). The ith number is the amount of apples in Node i.
The third part contains N-1 line. There are two numbers A,B in each line, meaning that Node A and Node B are adjacent.
Input will be ended by the end of file.
Note: Wshxzt starts at Node 1.
Output
Sample Input
2 1 0 11 1 2 3 2 0 1 2 1 2 1 3
Sample Output
11
2
题意:给你一棵树,起点位置是1,树上的每个节点都有自己的价值,问你最多走k步能得到的节点的最大价值。
思路:首先容易想到状态方程dp[i][j]表示从i节点出发走j步所能得到的最大价值,但是这样定义状态会有一个问题,就是走j步后不一定会回到原来的点,这样就不能转移方程了,所以可以增加一维,用dp[i][j][0]表示i节点出发走j步并且最后回到i点的最大价值,用dp[i][j][1]表示i节点出发走j步并且最后不回到i点的最大价值,这样就容易转移了。
dp[i][j][0] = MAX (dp[i][j][0] , dp[i][j-k][0] + dp[son][k-2][0]);//从s出发,要回到s,需要多走两步s-t,t-s,分配给t子树k步,其他子树j-k步,都返回 dp[i][j]][1] = MAX( dp[i][j][1] , dp[i][j-k][0] + dp[son][k-1][1]) ;//先遍历s的其他子树,回到s,遍历t子树,在当前子树t不返回,多走一步 dp[i][j][1] = MAX (dp[i][j][1] , dp[i][j-k][1] + dp[son][k-2][0]);//不回到s(去s的其他子树),在t子树返回,同样有多出两步
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<string>
#include<algorithm>
using namespace std;
typedef long long ll;
#define maxn 105
int value[maxn],first[maxn],dp[maxn][2*maxn][2];
struct node{
int to,next;
}e[2*maxn];
int n,k,vis[maxn];
void dfs(int u)
{
int i,j,v,l;
vis[u]=1;
for(j=0;j<=k;j++){
dp[u][j][0]=value[u];
dp[u][j][1]=value[u]; //这里不管回不回到u点,初始值都是value[u],因为不移动也有value[u]
}
for(i=first[u];i!=-1;i=e[i].next){
v=e[i].to;
if(vis[v])continue;
dfs(v);
for(j=k;j>=1;j--){
for(l=j;l>=1;l--){
if(l>=2){
dp[u][j][0]=max(dp[u][j][0],dp[u][j-l][0]+dp[v][l-2][0] );
dp[u][j][1]=max(dp[u][j][1],dp[u][j-l][1]+dp[v][l-2][0] );
}
dp[u][j][1]=max(dp[u][j][1],dp[u][j-l][0]+dp[v][l-1][1] );
}
}
}
}
int main()
{
int m,i,j,tot,u,v;
while(scanf("%d%d",&n,&k)!=EOF)
{
for(i=1;i<=n;i++){
scanf("%d",&value[i]);
}
tot=0;
memset(first,-1,sizeof(first));
for(i=1;i<=n-1;i++){
scanf("%d%d",&u,&v);
tot++;
e[tot].to=v;e[tot].next=first[u];
first[u]=tot;
tot++;
e[tot].to=u;e[tot].next=first[v];
first[v]=tot;
}
memset(dp,0,sizeof(dp));
memset(vis,0,sizeof(vis));
dfs(1);
printf("%d\n",max(dp[1][k][0],dp[1][k][1]) );
}
return 0;
}