4557: [JLoi2016]偵察守衛
Time Limit: 20 Sec Memory Limit: 256 MBSubmit: 114 Solved: 70
[Submit][Status][Discuss]
Description
Input
Output
僅一行一個整數,表示監視所有B神可能出現的點所需要的最小代價
Sample Input
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
樹形DP
f[i][j]表示i的子樹中,最高覆蓋到i向下第j層的最小花費。
g[i][j]表示i的子樹全部覆蓋,還能向上覆蓋j層的最小花費。
轉移比較麻煩,相關注釋都寫在代碼裏了。
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<algorithm>
#define F(i,j,n) for(int i=j;i<=n;i++)
#define D(i,j,n) for(int i=j;i>=n;i--)
#define ll long long
#define N 500005
#define inf 1000000000
using namespace std;
int n,m,d,cnt;
int w[N],head[N],f[N][25],g[N][25];
bool mark[N];
struct edge{int next,to;}e[N*2];
inline int read()
{
int x=0,f=1;char ch=getchar();
while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
while (ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
inline void add_edge(int x,int y)
{
e[++cnt]=(edge){head[x],y};head[x]=cnt;
e[++cnt]=(edge){head[y],x};head[y]=cnt;
}
void dp(int x,int fa)
{
if (mark[x]) f[x][0]=g[x][0]=w[x];//這個位置一定要放
F(i,1,d) g[x][i]=w[x];//初始狀態是假設x位置放守衛,之後會可能被更新
g[x][d+1]=inf;//只用x子樹中的點不可能向上覆蓋d+1層,所以等於inf
for(int i=head[x];i;i=e[i].next)
{
int y=e[i].to;
if (y==fa) continue;
dp(y,x);
D(j,d,0) g[x][j]=min(g[x][j]+f[y][j],g[y][j+1]+f[x][j+1]);//用y的子樹中的守衛可能花費更少
D(j,d,0) g[x][j]=min(g[x][j],g[x][j+1]);//用g[x][j+1]來更新g[x][j]
f[x][0]=g[x][0];//這裏相當於既不能向上也不能向下擴展
F(j,1,d+1) f[x][j]+=f[y][j-1];//直接加上就可以
F(j,1,d+1) f[x][j]=min(f[x][j-1],f[x][j]);//用f[x][j-1]來更新f[x][j]
}
}
int main()
{
n=read();d=read();
F(i,1,n) w[i]=read();
m=read();
F(i,1,m){int x=read();mark[x]=true;}
F(i,1,n-1){int x=read(),y=read();add_edge(x,y);}
dp(1,0);
printf("%d\n",f[1][0]);
return 0;
}