[JLOI2016/SHOI2016]侦察守卫

CXIII.[JLOI2016/SHOI2016]侦察守卫

神题。

见代码即可。

#include<bits/stdc++.h>
using namespace std;
int n,m,p,a[500100],f[500100][25],g[500100][25],res=0x3f3f3f3f;
//f[i,j]:minimum cost when there're at most j layers left uncovered
//g[i,j]:minimum cost when there're at least j layers outside the subtree covered
bool sp[500100];
vector<int>v[500100];
void dfs(int x,int fa){
	if(sp[x])f[x][0]=g[x][0]=a[x];//at special points, empty state still need a guard; at normal points, empty state doesn't need a guard.
	for(int i=1;i<=m;i++)g[x][i]=a[x];//at whatever points, a state which can spread outside the subtree need a guard.
	g[x][m+1]=0x3f3f3f3f;//avoiding transferring outside bounds
	for(auto y:v[x]){
		if(y==fa)continue;
		dfs(y,x);
		for(int i=m;i>=0;i--)g[x][i]=min(g[x][i]+f[y][i],f[x][i+1]+g[y][i+1]);
		//in this case transferring order doesn't matter.
		//but g's transferring must take place before f since it needs f in transferring.
		//case 1:guards in x spread into y, where there are i layers downwards y is covered from x.
		//case 2:guards in y spread into x, where there are i+1 layers downward x is covered from y, and y can also cover upper levels.
		for(int i=m;i>=0;i--)g[x][i]=min(g[x][i],g[x][i+1]);
		//in this case it is getting a suffix minimum, where transferring order matters.
		f[x][0]=g[x][0];//in fact f[x][0] and g[x][0] have the same meaning(which is a full subtree covered and nothing more)
		for(int i=1;i<=m;i++)f[x][i]+=f[y][i-1];
		//if there are at most i layers downwards, there should be at most i-1 layers downwards.
		for(int i=1;i<=m;i++)f[x][i]=min(f[x][i],f[x][i-1]);
		//getting a prefix minimum.
	}
}
int main(){
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)scanf("%d",&a[i]);
	scanf("%d",&p);
	for(int i=1,x;i<=p;i++)scanf("%d",&x),sp[x]=true;
	for(int i=1,x,y;i<n;i++)scanf("%d%d",&x,&y),v[x].push_back(y),v[y].push_back(x);
	dfs(1,0);
	printf("%d\n",f[1][0]);
	return 0;
}

posted @   Troverld  阅读(59)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?
点击右上角即可分享
微信分享提示