ACdream1032 Component 树形DP

思路:dp[i][j]表示以i为根结点有j个连通节点的最小和, 当进行状态转移时需要利用01背包,节点u下面有多个子节点,每个子节点可以最多可以贡献cnt[v]个节点,cnt[v]表示以v为根结点的树的节点总数。

AC代码

#include <cstdio>
#include <cmath>
#include <cctype>
#include <algorithm>
#include <cstring>
#include <utility>
#include <string>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
#pragma comment(linker, "/STACK:1024000000,1024000000")
#define eps 1e-10
#define inf 0x3f3f3f3f
#define PI pair<int, int>
const int maxn = 2e3 + 5;
int dp[maxn][maxn], w[maxn], cnt[maxn], p[maxn], ans[maxn];
int n;
vector<int>G[maxn];

//dp[i][j]表示以i为根结点有j个连通节点的最小和 

int dfs(int u, int pre) {
	int sum = 0;
	for(int i = 0; i < G[u].size(); ++i) {
		int v = G[u][i];
		if(v == pre) continue;
		cnt[v] += dfs(v, u);
		sum += cnt[v];
	}
	//p[i]表示凑足i个节点的最小和,利用了滚动数组
	p[0] = 0;
	for(int i = 1; i <= sum; ++i) p[i] = inf;
	for(int i = 0; i < G[u].size(); ++i) {
		int v = G[u][i];
		if(v == pre) continue;
		for(int j = sum; j >= 1; --j) {
			for(int k = 1; k <= cnt[v]; ++k) {
				if(j >= k) p[j] = min(p[j], p[j-k] + dp[v][k]);
			}
		}
	}
	for(int i = 0; i <= sum; ++i) {
		dp[u][i+1] = p[i] + w[u];
		ans[i+1] = min(ans[i+1], dp[u][i+1]);
	}
	return sum+1;
}
int main() {
	while(scanf("%d", &n) == 1) {
		for(int i = 1; i <= n; ++i) {
			scanf("%d", &w[i]);
			G[i].clear();
			ans[i] = inf;
		}
		int u, v;
		for(int i = 0; i < n-1; ++i) {
			scanf("%d%d", &u, &v);
			G[u].push_back(v);
			G[v].push_back(u);
		}
		dfs(1, -1);
		for(int i = 1; i <= n; ++i) {
			if(i == n) printf("%d\n", ans[i]);
			else printf("%d ", ans[i]);
		}
	}
	return 0;
}

如有不当之处欢迎指出!

上一篇:git push error: RPC failed; result=56, HTTP code = 0 ,the remote end hung up unexpectedly


下一篇:Hexo博客搭建全解