(树形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;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值