http://acm.cs.ecnu.edu.cn/problem.php?problemid=2103
WA
T^T 不知道为什么
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int maxn = 1005;
int n,p;
struct node
{
int to;
int next;
}e[maxn];
int head[maxn];
int tot;
int cost[maxn];
int key[maxn];
int dp[maxn][maxn];
template<class T> inline void checkmax(T &a, T b){if(b > a) a = b;}
void init()
{
tot = 0;
memset(head,-1,sizeof(head));
memset(dp,0,sizeof(dp));
}
void addedge(int u, int v)
{
e[tot].to = v;
e[tot].next = head[u];
head[u] = tot ++;
}
void dfs(int u, int pre)
{
for(int j=p;j>=cost[u];j--){
dp[u][j] = key[u];
}
for(int i=head[u];i!=-1;i=e[i].next){
int v = e[i].to;
if(v == pre)continue;
dfs(v,u);
for(int j=p;j>=cost[u];j--){
dp[u][j] = max(dp[u][j],dp[v][j-cost[u]]+key[u]);
}
}
}
int main()
{
while(scanf("%d%d",&n,&p)!=-1)
{
if(n == 0){
printf("0\n");
continue;
}
init();
for(int i=1;i<=n;i++)
scanf("%d%d",&cost[i], &key[i]);
int m = n - 1;
while(m--){
int x,y;
scanf("%d%d",&x,&y);
addedge(x,y);
addedge(y,x);
}
dfs(1,0);
printf("%d\n",dp[1][p]);
}
return 0;
}
终于找到错误所在了。
上面的写法明显是0-1背包,是在所有的子树中寻找最大的数,然后加上该节点的值。
实际上,这题是分组背包,即看每一组能用多少的power,然后寻求最大的
转移方程:dp[u][p] 第u个结点消耗p单位的power时的最大价值
dp[u][p] = dp[v1][p1] + dp[v2][p1]+ dp[v3][p3] ...
有道类似的题:http://acm.hdu.edu.cn/showproblem.php?pid=1561
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int maxn = 105;
int n,p;
struct node
{
int to;
int next;
}e[maxn<<1];
int head[maxn];
int tot;
int cost[maxn];
int key[maxn];
int dp[maxn][maxn];
template<class T> inline void checkmax(T &a, T b){if(b > a) a = b;}
void init()
{
tot = 0;
memset(head,-1,sizeof(head));
memset(dp,0,sizeof(dp));
}
void addedge(int u, int v)
{
e[tot].to = v;
e[tot].next = head[u];
head[u] = tot ++;
}
void dfs(int u, int pre)
{
for(int j=p;j>=cost[u];j--){
dp[u][j] = key[u];
}
for(int i=head[u];i!=-1;i=e[i].next){
int v = e[i].to;
if(v == pre)continue;
dfs(v,u);
for(int j=p;j>=cost[u];j--){
for(int k=cost[v];k<=j-cost[u];k++)
dp[u][j] = max(dp[u][j],(dp[u][j-k]+dp[v][k]));
}
}
}
int main()
{
//freopen("2103#1.in","r",stdin);
//freopen("out","w",stdout);
while(scanf("%d%d",&n,&p)!=-1)
{
if(n == 0){
printf("0\n");
continue;
}
init();
for(int i=1;i<=n;i++)
scanf("%d%d",&cost[i], &key[i]);
int m = n - 1;
while(m--){
int x,y;
scanf("%d%d",&x,&y);
addedge(x,y);
addedge(y,x);
}
dfs(1,0);
printf("%d\n",dp[1][p]);
}
return 0;
}
for(int j=p;j>=cost[u];j--){
dp[u][j] = max(dp[u][j],dp[v][j-cost[u]]+key[u]);
}
for(int j=p;j>=cost[u];j--){ for(int k=cost[v];k<=j-cost[u];k++) dp[u][j] = max(dp[u][j],(dp[u][j-k]+dp[v][k])); }