hdu4003(树形背包)

地址:http://acm.hdu.edu.cn/showproblem.php?pid=4003

Find Metal Mineral

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65768/65768 K (Java/Others)
Total Submission(s): 2333    Accepted Submission(s): 1065


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;
 

题意:求K个机器人从S点出发,遍历所有点的最小花费。

思路:最初看见这题时没一点思路,看了下别人的代码,开二位数组dp[i][j]表示对i节点的子树用j个机器人遍历的最小花费。知道怎么开数组剩下的就好做了,只需要注意下保存以前的状态以及赋初值,还有就是状态转移方程。

代码:

#include 
#include 
#include 
using namespace std;
#define Ma 10005
#define INF 0xfffffff
#define LL __int64
struct node{
    int to,next,vi;
} tree[Ma*2];
int n,k,len,head[Ma],dp[Ma][11];
void add(int no,int to,int vi){
    tree[len].to=to;
    tree[len].vi=vi;
    tree[len].next=head[no];
    head[no]=len++;
}
void dfs(int no,int pa)
{
    for(int i=head[no]; i!=-1; i=tree[i].next){
        int to=tree[i].to;
        if(to==pa) continue;
        dfs(to,no);
        int ss[11];
        for(int s=0;s<=k;s++){
            ss[s]=dp[no][s];  //另开个ss数组保存以前状态,因为我这里是多一条支边就会使dp数组的值整体上涨,而使用了min函数会转回以前的值,因此对要每一个dp[no][]赋初值,即加上不消耗机器人遍历i节点的子树的最小花费
            dp[no][s]+=(dp[to][0]+tree[i].vi*2);
        }
        for(int s=1;s<=k;s++){
            for(int j=k;j>=s;j--){
                dp[no][j]=min(dp[no][j],ss[j-s]+dp[to][s]+tree[i].vi*s);  //状态转移方程
            }
        }
    }
}
int main(){
    int st;
    while(scanf("%d%d%d",&n,&st,&k)>0){
        memset(head,-1,sizeof(head));
        memset(dp,0,sizeof(dp));
        len=0;
        for(int i=1; i


你可能感兴趣的:(树形DP)