链接:戳这里
The more, The Better
Time Limit: 6000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Problem Description
ACboy很喜欢玩一种战略游戏,在一个地图上,有N座城堡,每座城堡都有一定的宝物,在每次游戏中ACboy允许攻克M个城堡并获得里面的宝物。但由于地理位置原因,有些城堡不能直接攻克,要攻克这些城堡必须先攻克其他某一个特定的城堡。你能帮ACboy算出要获得尽量多的宝物应该攻克哪M个城堡吗?
Input
每个测试实例首先包括2个整数,N,M.(1 <= M <= N <= 200);在接下来的N行里,每行包括2个整数,a,b. 在第 i 行,a 代表要攻克第 i 个城堡必须先攻克第 a 个城堡,如果 a = 0 则代表可以直接攻克第 i 个城堡。b 代表第 i 个城堡的宝物数量, b >= 0。当N = 0, M = 0输入结束。
Output
对于每个测试实例,输出一个整数,代表ACboy攻克M个城堡所获得的最多宝物的数量。
Sample Input
3 2
0 1
0 2
0 3
7 4
2 2
0 1
0 4
2 1
7 1
7 6
2 2
0 0
Sample Output
5
13
思路:
设置dp[i][j] 表示以i作为根节点,向下取j个节点的最优值
当前根节点为u,其中一个儿子为v
两层for枚举 当前父亲u还能分配j个节点,分配给v儿子k个,那么其他的儿子(包括父亲本身)总共就是(j-k)个
那么儿子v至少分配一个,但是最多分配(num-1)个 ,父亲占去一个
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<vector>
#include <ctime>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<iomanip>
#include<cmath>
#define mst(ss,b) memset((ss),(b),sizeof(ss))
#define maxn 0x3f3f3f3f
#define MAX 1000100
///#pragma comment(linker, "/STACK:102400000,102400000")
typedef long long ll;
typedef unsigned long long ull;
#define INF (1ll<<60)-1
using namespace std;
int n,m;
struct edge{
int v,next;
}e[10010];
int head[220],a[220],tot;
void Add(int u,int v){
e[tot].v=v;
e[tot].next=head[u];
head[u]=tot++;
}
int dp[220][220];
void DFS(int u,int fa,int num){
dp[u][1]=a[u];
for(int i=head[u];i!=-1;i=e[i].next){
int v=e[i].v;
if(v==fa) continue;
if(num>1) DFS(v,u,num-1);
///printf("%d %d %d\n",u,v,num);
for(int j=num;j>=1;j--){
for(int k=1;k<j;k++){
dp[u][j]=max(dp[u][j],dp[v][k]+dp[u][j-k]);
}
}
}
}
int main(){
while(scanf("%d%d",&n,&m)!=EOF){
if(n==0 && m==0) break;
mst(dp,0);
mst(a,0);
mst(head,-1);
tot=0;
for(int u=1;u<=n;u++){
int v;
scanf("%d%d",&v,&a[u]);
Add(v,u);
Add(u,v);
}
DFS(0,-1,m+1);
printf("%d\n",dp[0][m+1]);
}
return 0;
}