[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 @ 2021-03-31 14:29  Troverld  阅读(56)  评论(0编辑  收藏  举报