(樹形dp)Fire
https://cn.vjudge.net/contest/264707#problem/D
Country Z has N cities, which are numbered from 1 to N. Cities are connected by highways, and there is exact one path between two different cities. Recently country Z often caught fire, so the government decided to build some firehouses in some cities. Build a firehouse in city K cost W(K). W for different cities may be different. If there is not firehouse in city K, the distance between it and the nearest city which has a firehouse, can’t be more than D(K). D for different cities also may be different. To save money, the government wants you to calculate the minimum cost to build firehouses.
題意為一個n個城市的國家,編號為1-n,每個城市都有著火的風險,需要在給出的距離記憶體在一個滅火站,滅火站需要建在城市裡面且不同城市花費不同,求滿足條件的最少花費
剛開始思路是用二位存第i個城市是否修建滅火站,發現寫出來無法將距離之內的城市建站對該城市的狀態表達出來
正解是dp[i][j]表示第i個城市對其管轄的滅火站建在第j個城市,由於需要計算在給出範圍的其他城市的建站情況,所以對每個城市需要計算一次到其他城市的距離,用bst陣列記錄每個點已經算出來的最優解
#include <math.h> #include <stdio.h> #include <string.h> #include <algorithm> #include <iomanip> #include <iostream> #include <list> #include <map> #include <queue> #include <set> #include <stack> #include <vector> #include <string> using namespace std; const int maxn = 1e3 + 4; const int inf = 0x3f3f3f3f; vector< pair<int, int> > e[maxn]; vector<int> w(maxn), d(maxn), bst(maxn), dis(maxn); int dp[maxn][maxn]; int t, n; void Dis(int u) { for(int i = 0; i < e[u].size(); i++) { int v = e[u][i].first, l = e[u][i].second; if(dis[v] != -1) continue; dis[v] = dis[u] + l; Dis(v); } } void dfs(int u, int pre) { for(int i = 0; i < e[u].size(); i++) { int v = e[u][i].first, l = e[u][i].second; if(v == pre) continue; dfs(v, u); } dis.assign(n + 1, -1); dis[u] = 0; bst[u] = inf; Dis(u); for(int i = 1; i <= n; i++) { if(dis[i] > d[u]) dp[u][i] = inf; else { dp[u][i] = w[i]; for(int j = 0; j < e[u].size(); j++) { int v = e[u][j].first, l = e[u][j].second; if(v == pre) continue; dp[u][i] += min(bst[v], dp[v][i] - w[i]); } bst[u] = min(bst[u], dp[u][i]); } } } int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> t; while(t--) { cin >> n; for(int i = 1; i <= n; i++) e[i].clear(); for(int i = 1; i <= n; i++) cin >> w[i]; for(int i = 1; i <= n; i++) cin >> d[i]; for(int i = 1; i < n; i++) { int u, v, l; cin >> u >> v >> l; e[u].push_back(make_pair(v, l)); e[v].push_back(make_pair(u, l)); } dfs(1, 0); cout << bst[1] << endl; } }