Description
给定一棵无根有权树,每个点建消防站都有一定代价 c c c,每个点都有一个限制 l i m lim lim,表示离它最近的消防站的最大距离。求让所有点安全的最小代价。
Solution
设 f i , j f_{i,j} fi,j 为以 i i i 为根的子树全安全,且 j j j 管理 i i i 的最小代价, b e s t i best_i besti 为以 i i i 为根的子树全安全的最小代价,结果显然为 b e s t 1 best_1 best1。首先,用 dfs 预处理出以每个点 i i i 为中心,到其他所有点的距离,用 d i s i , j dis_{i,j} disi,j 表示。
然后从下往上进行树形 dp,先将 f x , j f_{x,j} fx,j 赋初值为 c j c_j cj。对于一个点,在搞完它的儿子 y y y 后,枚举一个依赖点 j j j 来转移 f f f,转移方程为
f x , j = f x , j + m i n { f y , j − c j , b e s t y } ( d i s x , j ≤ l i m x ) f_{x,j} = f_{x,j} + min \{ f_{y,j} - c_j, best_y \} \quad (dis_{x,j} \leq lim_x) fx,j=fx,j+min{fy,j−cj,besty}(disx,j≤limx)
f y , j − c j f_{y,j }- c_j fy,j−cj 为 y y y 也依赖 j j j, b e s t y best_y besty 为 y y y 不依赖 j j j。
求出所有 f x , j f_{x,j} fx,j 后, b e s t x best_x bestx 对 f x , 1 ∼ n f_{x,1 \sim n} fx,1∼n 取 min 即可。
Code
#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 1000 + 10;
int n;
int cost[N], d[N], dis[N][N];
int f[N][N], best[N];
struct node{
int to;
int w;
};
vector <node> G[N];
void DFS(int x, int fa, int sum, int root){
dis[root][x] = sum;
for (int i = 0; i< G[x].size(); i++)
if (G[x][i].to != fa) DFS(G[x][i].to, x, sum + G[x][i].w, root);
}
void dfs(int x, int fa){
for (int i = 1; i <= n; i++)
if (dis[x][i] <= d[x]) f[x][i] = cost[i];
for (int i = 0; i < G[x].size(); i++){
int y = G[x][i].to, w = G[x][i].w;
if (y != fa){
dfs(y, x);
for (int j = 1; j <= n; j++)
if (dis[x][j] <= d[x]) f[x][j] += min(f[y][j] - cost[j], best[y]);
}
}
for(int i = 1; i <= n; i++) best[x] = min(best[x],f[x][i]);
}
int main(){
int T; scanf("%d", &T);
while(T--){
scanf("%d", &n);
memset(f, 0x3f, sizeof(f));
memset(best, 0x3f, sizeof(best));
memset(dis, 0, sizeof(dis));
for (int i = 1; i <= n; i++) G[i].clear();
for (int i = 1; i <= n; i++) scanf("%d", &cost[i]);
for (int i = 1; i <= n; i++) scanf("%d", &d[i]);
for (int i = 1; i < n; i++){
int x, y, w; scanf("%d%d%d", &x, &y, &w);
G[x].push_back((node){y,w});
G[y].push_back((node){x,w});
}
for (int i = 1; i <= n; i++) DFS(i, 0, 0, i);
dfs(1, 0);
printf("%d\n", best[1]);
}
return 0;
}