POJ2152 Fire 【树形dp】

题目链接

POJ2152

题解

经典老题,还真暴力

(n le 1000),所以可以(O(n^2))
所以可以枚举每个点依附于哪一个点
(f[u])表示以(u)为根的子树的最小代价
(g[u][v])表示(u)依附于(v)时以(u)为根的子树的最小代价

显然

[f[u] = min{ g[u][v] } ]

[g[u][v] = cost[v] + sumlimits_{(u,to) in edge} min(g[to][v] - cost[v],f[to]) quad [dis(u,v) le D(u)] ]

(dis(u,v))要直接暴力(O(n^2))预处理
上倍增直接(T)掉。。。

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define LL long long int
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define cls(s) memset(s,0,sizeof(s))
using namespace std;
const int maxn = 1005,maxm = 100005,INF = 1000000000;
inline int read(){
	int out = 0,flag = 1; char c = getchar();
	while (c < 48 || c > 57){if (c == '-') flag = -1; c = getchar();}
	while (c >= 48 && c <= 57){out = (out << 3) + (out << 1) + c - 48; c = getchar();}
	return out * flag;
}
int h[maxn],ne;
struct EDGE{int to,nxt,w;}ed[maxn << 1];
inline void build(int u,int v,int w){
	ed[ne] = (EDGE){v,h[u],w}; h[u] = ne++;
	ed[ne] = (EDGE){u,h[v],w}; h[v] = ne++;
}
int fa[maxn],f[maxn],g[maxn][maxn],cost[maxn],d[maxn],dis[maxn][maxn],n,rt;
void DFS(int u,int D,int F){
	dis[rt][u] = D;
	Redge(u) if ((to = ed[k].to) != F)
		DFS(to,D + ed[k].w,u);
}
void dfs(int u){
	f[u] = INF;
	REP(i,n)
		if (dis[u][i] <= d[u]) g[u][i] = cost[i];
		else g[u][i] = INF;
	Redge(u) if ((to = ed[k].to) != fa[u]){
		fa[to] = u; dfs(to);
		REP(i,n) if (g[u][i] != INF)
			g[u][i] += min(g[to][i] - cost[i],f[to]);
	}
	REP(i,n) f[u] = min(f[u],g[u][i]);
}
int main(){
	int T = read();
	while (T--){
		n = read(); ne = 2; cls(h);
		REP(i,n) cost[i] = read();
		REP(i,n) d[i] = read();
		int a,b,w;
		for (int i = 1; i < n; i++){
			a = read(); b = read(); w = read();
			build(a,b,w);
		}
		REP(i,n) rt = i,DFS(i,0,0);
		dfs(1);
		printf("%d
",f[1]);
	}
	return 0;
}

原文地址:https://www.cnblogs.com/Mychael/p/9012295.html