Luogu3267 [JLOI2016/SHOI2016]侦察守卫 (树形DP)

树形DP,一脸蒙蔽。看了题解才发现它转移状态与方程真不愧神题!
\(f[x][y]\)表示\(x\)\(y\)层以下的所有点都已经覆盖完,还需要覆盖上面的\(y\)层的最小代价。
\(g[x][y]\)表示\(x\)子树中所有点都已经覆盖完,并且\(x\)还能向上覆盖\(y\)层的最小代价。
\(g[u][j]=\min(g[u][j]+f[v][j],g[v][j+1]+f[u][j+1])\)
\(f[u][j] = Σf[v][j-1]f[u][j]\)
\(g[u][j] = \min(g[u][j], g[u][j+1])\)
\(f[u][j] = \min(f[u][j], f[u][j-1])\)
我在口胡些啥

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define R(a,b,c) for(register int  a = (b); a <= (c); ++ a)
#define nR(a,b,c) for(register int  a = (b); a >= (c); -- a)
#define Max(a,b) ((a) > (b) ? (a) : (b))
#define Min(a,b) ((a) < (b) ? (a) : (b))
#define Fill(a,b) memset(a, b, sizeof(a))
#define Abs(a) ((a) < 0 ? -(a) : (a))
#define Swap(a,b) a^=b^=a^=b
#define ll long long

//#define ON_DEBUG

#ifdef ON_DEBUG

#define D_e_Line printf("\n\n----------\n\n")
#define D_e(x)  cout << #x << " = " << x << endl
#define Pause() system("pause")
#define FileOpen() freopen("in.txt","r",stdin);

#else

#define D_e_Line ;
#define D_e(x)  ;
#define Pause() ;
#define FileOpen() ;

#endif

struct ios{
    template<typename ATP>ios& operator >> (ATP &x){
        x = 0; int f = 1; char c;
        for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-')  f = -1;
        while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
        x*= f;
        return *this;
    }
}io;
using namespace std;

const int N = 500007;

int n, m, D;

struct Edge{
	int nxt, pre;
}e[N << 1];
int head[N], cntEdge;
inline void add(int u, int v){
	e[++cntEdge] = (Edge){ head[u], v}, head[u] = cntEdge;
}

int val[N];
long long g[N][29], f[N][29];
int vis[N];

inline void DFS(int u, int fa){
    if(vis[u]){
    	f[u][0] = g[u][0] = val[u];
    }
	R(i,1,D){
		g[u][i] = val[u];
	}
    g[u][D + 1]= 0x3f3f3f3f;
    for(register int i = head[u]; i; i = e[i].nxt){
        int v = e[i].pre;
		if(v == fa) continue;
        DFS(v, u);
        nR(j,D,0){
        	g[u][j] = Min(g[u][j] + f[v][j], g[v][j + 1] + f[u][j + 1]);
        }
        nR(j,D,0){
        	g[u][j] = Min(g[u][j], g[u][j + 1]);
        }
        f[u][0] = g[u][0];
        R(j,1,D + 1){
        	f[u][j] += f[v][j - 1];
        }
        R(j,1,D + 1){
        	f[u][j] = Min(f[u][j], f[u][j - 1]);
        }
    }
}
int main(){
    //FileOpen();
	io >> n >> D;
    R(i,1,n){
    	io >> val[i];
    }
    io >> m;
    R(i,1,m){
    	int x;
    	io >> x;
    	vis[x] = 1;
    }
    R(i,2,n){
    	int u, v;
    	io >> u >> v;
    	add(u, v);
    	add(v, u);
    }
    
    DFS(1, 0);
    
    printf("%lld\n",f[1][0] );
    
    return 0;
}
/*
3 1
1 1 1
3
1 1 1
1 2
1 3

14 2
1 1 1 1 1 1 1 1 1 1 1 1 1 1
14
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 2
1 3
1 4
2 5
2 6
3 7
3 8
3 9
6 10
10 11
11 12
12 13
12 14

*/

posted @ 2019-07-24 10:12  邱涵的秘密基地  阅读(121)  评论(0编辑  收藏  举报