hdu 4003 Find Metal Mineral(树形dp+分组背包)

本文介绍了一种优化机器人在火星上收集矿物的算法。通过构建树形路径并使用动态规划求解最小能耗方案,实现了多个机器人从指定起点出发,遍历各矿物点并返回地球的能量消耗最小化。

Problem Description

Humans have discovered a kind of new metal mineral on Mars which are distributed in point‐like with paths connecting each of them which formed a tree. Now Humans launches k robots on Mars to collect them, and due to the unknown reasons, the landing site S of all robots is identified in advanced, in other word, all robot should start their job at point S. Each robot can return to Earth anywhere, and of course they cannot go back to Mars. We have research the information of all paths on Mars, including its two endpoints x, y and energy cost w. To reduce the total energy cost, we should make a optimal plan which cost minimal energy cost.

Input

There are multiple cases in the input.
In each case:
The first line specifies three integers N, S, K specifying the numbers of metal mineral, landing site and the number of robots.
The next n‐1 lines will give three integers x, y, w in each line specifying there is a path connected point x and y which should cost w.
1<=N<=10000, 1<=S<=N, 1<=k<=10, 1<=x, y<=N, 1<=w<=10000.

Output

For each cases output one line with the minimal energy cost.

Sample Input

3 1 1
1 2 1
1 3 1
3 1 2
1 2 1
1 3 1

Sample Output

3
2

Hint

In the first case: 1->2->1->3 the cost is 3;
In the second case: 1->2; 1->3 the cost is 2;

这道题目思索了半天,递推式倒是想出来了,但是始终想不到如何进行初始化,最后还是没能做出来……
dp[i][0]的含义为只有一个机器人遍历一遍子树后回到i节点,这也是耗费最大的方法,所以在进行背包时每次现将0的状态放入背包,就可顺利进行dp。

还有……这个数据量用cin会超时……奇怪……

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <algorithm>
#define maxn 10010
#define inf 0x3f3f3f3f
using namespace std;

struct node
{
    int to,len;
    node() {};
    node(int _to,int _len) :to(_to),len(_len) {};
};

vector<node> g[maxn];
int dp[maxn][20];
int n,k,s;

void dfs(int now,int fa)
{
   for(int i=0;i<g[now].size();i++)
   {
       int v=g[now][i].to;
       int len=g[now][i].len;
       if(v==fa) continue;
       dfs(v,now);
       for(int p=k;p>=0;p--)
       {
           dp[now][p]+=dp[v][0]+2*len;
            for(int j=1;j<=p;j++)
            dp[now][p]=min(dp[now][p],dp[now][p-j]+dp[v][j]+j*len);
       }
   }
}

int main()
{
    while(cin>>n>>s>>k)
    {
        memset(dp,0,sizeof(dp));
        for(int i=0;i<=n;i++)
            g[i].clear();
        for(int i=1;i<=n-1;i++)
        {
            int a,b,val;
       //     cin>>a>>b>>val;
            scanf("%d%d%d",&a,&b,&val);
            g[a].push_back(node(b,val));
            g[b].push_back(node(a,val));
        }
        dfs(s,0);
        cout<<dp[s][k]<<endl;

    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值