http://acm.hdu.edu.cn/showproblem.php?pid=1561
题意:一棵树,每个结点有个价值,从中取M个结点使得价值最大。(必须先取前置)
Idea:
之前也做过类似的题了。
f[i][k][j] = max{ f[i][k-1][j] , f[i][k-1][j-m] + f[第k个儿子][…][m] }
方程比较简单,treeDP上加个背包就是了。边界比较麻烦:
f[i][0][1] = w[i],else 全赋值为-INF
i:treeDp
k:1àsize
j:1àmcap,mcap是以此结点为根的子树所含的结点总数
m:1àmcap &&(j – m > 0)
然后还要去压缩状态,把第二维给压缩了。
#include <cstdio>
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
using namespace std;
#define MAX(x,y) ((x)>(y)?(x):(y))
const int INF = (1<<31)-1;
struct edge
{
int ev,w;
edge(){}
edge(int a,int b):ev(a),w(b){}
};
vector <edge> elist[209];
int w[209];
int f[209][209];
int mcap[209];
void DFS(int fv)
{
int size = elist[fv].size();
f[fv][1] = w[fv];
int ev;
for (int k = 0;k < size;k++) //for (int k = 1;k <= size;k++) 使用vector注意下标是从0开始的~~~
{
ev = elist[fv][k].ev;
DFS(ev);
mcap[fv] += mcap[ev];
for (int j = mcap[fv];j >= 1;j--)
{
for (int m = 1;m <= mcap[fv];m++) if (j - m > 0)//特别注意j - m > 0 这个边界
{
f[fv][j] = MAX(f[fv][j],f[fv][j - m] + f[ev][m]);
}
}
}
}
int main()
{
freopen("test.txt","r",stdin);
int N,M;
while(scanf("%d%d",&N,&M),N+M)
{
for (int i = 0; i <= N; i++)
elist[i].clear();
memset(w,0,sizeof(w));
int fv;
for (int i = 1; i <= N; i++)
{
scanf("%d%d",&fv,&w[i]);
elist[fv].push_back(edge(i,w[i]));
}
for (int i = 0;i < 209;i++) for (int j = 0;j < 209;j++) f[i][j] = -INF;
for (int i = 0;i < 209;i++) mcap[i] = 1;
DFS(0);
printf("%d\n",f[0][M+1]);//printf("%d\n",f[N][M]);
}
return 0;
}