Multi-fork
There apple tree, if there is bifurcated branches, may be a multi-branch points, bifurcation number k> = 0 (that is the number of nodes greater than or equal son 0) N total tree nodes (leaf branch or bifurcation point point), numbered 1 ~ N, the roots must be a number. He described a number of branch nodes of our position both ends of a branch connection.
Data Scale:
For 20% of the data satisfies 1 <= n <= 15.
For 40% of the data satisfies 1 <= n <= 100.
To 100% of the data satisfies 1 <= n <= 310, c <= 2 ^ 31-1.
DP tree two questions, the same code can be changed through the detail, so that F [x] [y] represented by the subtree rooted x y retention edges maximum number of apples, easily deduced state transition equation
f[x][[t]=max(f[x][t] , f[x][t-j-1] + f[y][j]+edge[i])
Wherein y is a child node of x, edge [i] denotes x-> y apple this edge, with f [x] [tj-1] instead of f [x] [tj] because we have reserved x-> y this edge, the last 01 backpack can reverse enumeration.
Binary Code apple tree
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=110;
int n,q,f[maxn][maxn];
int head[maxn],Next[2*maxn],ver[2*maxn],edge[2*maxn],tot,u,v,z;
void add(int x,int y,int z){
ver[++tot]=y;edge[tot]=z;Next[tot]=head[x];head[x]=tot;
}
void dp(int x,int fa){
for(int i=head[x];i;i=Next[i]){
int y=ver[i];
if(y==fa) continue;
dp(y,x);
for(int t=q;t>=1;--t){
for(int j=t-1;j>=0;--j){
f[x][t]=max(f[x][t],f[x][t-j-1]+f[y][j]+edge[i]);
}
}
}
}
int main(){
scanf("%d %d",&n,&q);
for(int i=1;i<n;++i){
scanf("%d %d %d",&u,&v,&z);
add(u,v,z);
add(v,u,z);
}
dp(1,0);
printf("%d",f[1][q]);
return 0;
}
Multi-branch apple tree Code
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=330;
int n,q;
long long f[maxn][maxn];
int head[maxn],Next[2*maxn],ver[2*maxn],edge[2*maxn],tot,u,v,z;
void add(int x,int y,int z){
ver[++tot]=y;edge[tot]=z;Next[tot]=head[x];head[x]=tot;
}
void dp(int x,int fa){
for(int i=head[x];i;i=Next[i]){
int y=ver[i];
if(y==fa) continue;
dp(y,x);
for(int t=q;t>=1;--t){
for(int j=t-1;j>=0;--j){
f[x][t]=max(f[x][t],f[x][t-j-1]+f[y][j]+(long long)edge[i]);
}
}
}
}
int main(){
scanf("%d %d",&n,&q);
for(int i=1;i<n;++i){
scanf("%d %d %d",&u,&v,&z);
add(u,v,z);
add(v,u,z);
}
dp(1,0);
printf("%lld",f[1][q]);
return 0;
}