【题解】LuoGu3177:[HAOI2015]树上染色

原题传送门
树形dp
d p u , j dp_{u,j} dpu,j表示节点 u u u为根的子树有 j j j个黑点在整棵树里面的贡献
枚举儿子与儿子为根的子树的黑点数
d p u , j = m a x ( d p u , j − k + d p v , k + ( m − k ) ∗ k ∗ l e n + ( n − m − ( s i z e v − k ) ) ∗ ( s i z e v − k ) ∗ l e n ) dp_{u,j}=max(dp_{u,j-k}+dp_{v,k}+(m-k)*k*len+(n-m-(size_v-k))*(size_v-k)*len) dpu,j=max(dpu,jk+dpv,k+(mk)klen+(nm(sizevk))(sizevk)len)
注意一下枚举顺序,这可以看作是01背包

Code:

#include 
#define maxn 2010
#define int long long
using namespace std;
struct Edge{
	int to, next, len;
}edge[maxn << 1];
int num, head[maxn], size[maxn], dp[maxn][maxn], n, m;

inline int read(){
	int s = 0, w = 1;
	char c = getchar();
	for (; !isdigit(c); c = getchar()) if (c == '-') w = -1;
	for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48);
	return s * w;
}

void addedge(int x, int y, int z){ edge[++num] = (Edge){y, head[x], z}, head[x] = num; }

void dfs(int u, int pre){
	for (int i = 2; i <= m; ++i) dp[u][i] = -1;
	size[u] = 1;
	for (int i = head[u]; i; i = edge[i].next){
		int v = edge[i].to;
		if (v != pre) dfs(v, u), size[u] += size[v];
	}
	for (int i = head[u]; i; i = edge[i].next){
		int v = edge[i].to;
		if (v != pre){
			int l = edge[i].len;
			for (int j = min(m, size[u]); j >= 0; --j)
				for (int k = 0; k <= min(j, size[v]); ++k)
					if (dp[u][j - k] >= 0)
						dp[u][j] = max(dp[u][j], dp[u][j - k] + dp[v][k] + (m - k) * k * l + (size[v] - k) * (n - size[v] - m + k) * l);
		}
	}
}

signed main(){
	n = read(), m = read();
	for (int i = 1; i < n; ++i){
		int x = read(), y = read(), z = read();
		addedge(x, y, z), addedge(y, x, z);
	}
	dfs(1, 0);
	printf("%lld\n", dp[1][m]);
	return 0;
}

你可能感兴趣的:(题解,LuoGu,DP,题解,LuoGu,DP)