poj2152(Fire) 树形DP

题目链接:http://poj.org/problem?id=2152

题意:一棵带边权的树,边权表示节点间距离,在i上建立消防站的代价是w[i],如果在一点i没建消防站,那么它与距离这个点最近的消防站之间的距离不能大于d[i]。问满足建站最小的花费;


解法;看了陈启峰的论文才会的,感觉挺难的,不过论文里分情况讨论了,应该不需要;dp[i][j]表示在i处选择j处作为供应站(但是并不一定要求是最近的,这样即使有更近的也无所谓,和论文里有出入。),best[i]表示i及其子树满足要求的最小花费,那么转移方程:

     best[i]=min(dp[i][j]),1<=j<=n

     dp[i][j]=w[j]+min(dp[k][j]-w[j],best[k]),k是i的儿子


代码:

/******************************************************
* @author:xiefubao
*******************************************************/
#pragma comment(linker, "/STACK:102400000,102400000")
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <stack>
#include <string.h>
//freopen ("in.txt" , "r" , stdin);
using namespace std;

#define eps 1e-8
#define zero(_) (abs(_)<=eps)
const double pi=acos(-1.0);
typedef long long LL;
const int Max=100010;
const int INF=1e9+7;


int n;
int cost[1010];
int d[1010];
int dist[1010];
int dp[1010][1010];
int best[1010];
vector<pair<int,int> > vec[1010];
void add(int a,int b,int c)
{
    vec[a].push_back(pair<int,int>(b,c));
    vec[b].push_back(pair<int,int>(a,c));
}
void getdist(int u,int before,int add)
{
    dist[u]=dist[before]+add;
    for(int i=0; i<vec[u].size(); i++)
        if(vec[u][i].first!=before)
        getdist(vec[u][i].first,u,vec[u][i].second);
}
void dfs(int u,int before)
{
    //cout<<u<<" "<<before<<endl;
    for(int i=0; i<vec[u].size(); i++)
    {
        if(vec[u][i].first==before)
            continue;
        dfs(vec[u][i].first,u);
    }
    dist[u]=0;
    getdist(u,0,0);
    for(int i=1; i<=n; i++)
        if(dist[i]<=d[u])
        {
            dp[u][i]=cost[i];
            for(int k=0; k<vec[u].size(); k++)
                if(vec[u][k].first!=before)
                dp[u][i]+=min(dp[vec[u][k].first][i]-cost[i],best[vec[u][k].first]);
            best[u]=min(best[u],dp[u][i]);
        }
        else
            dp[u][i]=INF;
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        scanf("%d",&n);
        for(int i=0; i<=n; i++)
            vec[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=0; i<n-1; i++)
        {
            int a,b,c;
            scanf("%d%d%d",&a,&b,&c);
            add(a,b,c);
        }
        for(int i=1; i<=n; i++)
            best[i]=INF;
        dfs(1,0);
        cout<<best[1]<<endl;
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值