http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=3326
//1858391 2009-05-07 14:27:05 Accepted 3201 C++ 0 228 aslys #include<iostream> #include<vector> using namespace std; const int N = 105; int n,k; int f[N][N],w[N]; vector<int>sum[N]; //学习使用vector void dp(int x,int y) { int i,j,temp[N]; memset(temp,0,sizeof(temp)); for(i=1;i<=k;i++) { for(j=1;j<=i;j++) if(f[x][j] + f[y][i-j] > temp[i])//合并出最大的 temp[i] = f[x][j] + f[y][i-j]; } for(i=1;i<=k;i++) if(f[x][i] < temp[i]) f[x][i] = temp[i]; }
void dfs(int now,int pre) { int len = sum[now].size(); int i,cnt = 0; for(i=0;i<len;i++) { if(sum[now][i] != pre) { dfs(sum[now][i],now); f[now][1] = w[now]; dp(now,sum[now][i]); cnt ++; } } if(cnt == 0) f[now][1] = w[now]; }
int main() { while(scanf("%d%d",&n,&k)!=EOF) { int i,a,b,maxs; for(i=0;i<n;i++) { scanf("%d",&w[i]); sum[i].clear(); } for(i=1;i<n;i++) { scanf("%d%d",&a,&b); sum[a].push_back(b); sum[b].push_back(a); } maxs = 0; memset(f,0,sizeof(f)); dfs(0,-1);//从任一点出发都行 for(i=0;i<n;i++) if(maxs < f[i][k]) maxs = f[i][k]; printf("%d\n",maxs); } return 0; }
|