题目链接: https://hihocoder.com/contest/hiho12/problem/1
给出一棵树 每个节点的价值
求以1为根的树中,选取m个相联通的节点的最大价值和
#include <bits/stdc++.h> using namespace std; const int N = 110; int n, m, V[N]; int dp[N][N]; // 以i为根 个数为m的最大价值 bool vis[N]; vector<int> G[N]; void dfs(int u) { vis[u] = true; memset(dp[u], 0, sizeof(dp[u])); dp[u][1] = V[u-1]; for(int i=0; i<G[u].size(); i++) { int v = G[u][i]; if(vis[v]) continue; dfs(v); for(int j=m; j>1; j--) { for(int k=1; k<j; k++) { dp[u][j] = max(dp[u][j], dp[u][j-k] + dp[v][k]); } } } } int main() { scanf("%d %d", &n, &m); for(int i=0; i<n; i++) scanf("%d", &V[i]); for(int i=1; i<n; i++) { int u, v; scanf("%d %d", &u, &v); G[v].push_back(u); G[u].push_back(v); } memset(vis, 0, sizeof(vis)); dfs(1); printf("%d ", dp[1][m]); return 0; }