[JLOI2016]侦察守卫 树形DP

Description
给你一棵树,你选择一个点进行覆盖那么他就会覆盖所有距离他为D的节点,覆盖每个点有代价,有一些点必须被覆盖,要求最小代价。


Sample Input
12 2
8 9 12 6 1 1 5 1 4 8 10 6
10
1 2 3 5 6 7 8 9 10 11
1 3
2 3
3 4
4 5
4 6
4 7
7 8
8 9
9 10
10 11
11 12


Sample Output
10


我是来学习的。。。
设f[i][j]为i以下的子树全部覆盖,还往上覆盖j层的最小代价。
设g[i][j]为i一下有j层没有被覆盖的最小代价。
转移为:
f[x][j]=min(f[x][j]+g[x][j],g[x][j+1]+f[y][j+1])
g则直接从j-1转移即可。


#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
typedef long long LL;
int _min(int x, int y) {return x < y ? x : y;}
int _max(int x, int y) {return x > y ? x : y;}
int read() {
	int s = 0, f = 1; char ch = getchar();
	while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
	while(ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
	return s * f;
}

struct edge {
	int x, y, next;
} e[1000010]; int len, last[500010];
int K, a[510000], f[21][500010], g[21][500010];
bool v[500010];
//f表示往上拓展,g往下缺

void ins(int x, int y) {
	e[++len].x = x, e[len].y = y;
	e[len].next = last[x], last[x] = len;
}

void treedp(int x, int fa) {
	if(v[x]) f[0][x] = g[0][x] = a[x];
	for(int i = 1; i <= K; i++) f[i][x] = a[x];
	f[K + 1][x] = 999999999;
	for(int k = last[x]; k; k = e[k].next) {
		int y = e[k].y;
		if(y != fa) {
			treedp(y, x);
			for(int i = K; i >= 0; i--) f[i][x] = _min(f[i][x] + g[i][y], g[i + 1][x] + f[i + 1][y]);
			for(int i = K; i >= 0; i--) f[i][x] = _min(f[i][x], f[i + 1][x]);
			g[0][x] = f[0][x];
			for(int i = 1; i <= K; i++) g[i][x] += g[i - 1][y];
			for(int i = 1; i <= K; i++) g[i][x] = _min(g[i][x], g[i - 1][x]);
		}
	}
}

int main() {
	int n = read(); K = read();
	for(int i = 1; i <= n; i++) a[i] = read();
	int m = read();
	for(int i = 1; i <= m; i++) v[read()] = 1;
	for(int i = 1; i < n; i++) {
		int x = read(), y = read();
		ins(x, y), ins(y, x);
	} treedp(1, 0);
	printf("%d\n", f[0][1]);
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值