频道栏目
首页 > 程序开发 > 软件开发 > C++ > 正文
hdu4003 树形dp+分组背包
2014-12-21 10:58:02         来源:生活总是充满希望的  
收藏   我要投稿

 

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

HintIn the first case: 1->2->1->3 the cost is 3;
In the second case: 1->2; 1->3 the cost is 2;
这道题我的解题报告如果看不懂,就结合kuangbin巨巨的一起来看,效果会好一些~

 

 

 

/**
hdu 4003  树形dp+分组背包
题目大意:有n个点构成的一棵树,要求用K个机器人跑最小的距离把每个点都遍历到
解题思路:
        对于其中一个顶点,对于它的所有子结点看做一个种类,每一类中包含价值分别为:dp[son][0],dp[son][1]....dp[son][k]重量分别为0~k的物品。
状态转移方程:dp[u][k]=min(dp[u][k],dp[u][k-j]+(dp[v][j]+j*edge[u].w));(与父节点建立联系必须有j*edge[u].w)
这样借助分组背包就可以搞定,但是这样仅仅能保证在每一类物品中取一种或不取时的最优解,而题目要求的是所有类中必须都选一个,因此我们首先用dp[u][0]
表示用一个机器人走遍全部顶点的解,后面状态转移即可。
值得一提的是:在dp进行顶点u时必须保证所有儿子结点的全部状态必须已经求出,因此要用到dfs
*/
#include 
#include 
#include 
#include 
using namespace std;

int head[10005],ip,dp[10005][11];
int n,s,K;

struct note
{
    int v,w,next;
}edge[10005*2];

void init()
{
    memset(head,-1,sizeof(head));
    ip=0;
}

void addedge(int u,int v,int w)
{
    edge[ip].v=v,edge[ip].w=w,edge[ip].next=head[u],head[u]=ip++;
}

void dfs(int u,int pre)
{
    for(int i=head[u];i!=-1;i=edge[i].next)///相当于枚举所有的种类
    {
        int v=edge[i].v;
        if(v==pre)continue;
        dfs(v,u);
        for(int k=K;k>=0;k--)///背包容量枚举
        {
            dp[u][k]+=dp[v][0]+2*edge[i].w;
            for(int j=1;j<=k;j++)///该种类下所有的物品
            {
                dp[u][k]=min(dp[u][k],dp[u][k-j]+(dp[v][j]+j*edge[i].w));
            }
        }
    }
}
int main()
{
    while(~scanf(%d%d%d,&n,&s,&K))
    {
        init();
        for(int i=0;i

 

点击复制链接 与好友分享!回本站首页
相关TAG标签 树形 背包
上一篇:CF 496D(Tennis Game-O(t*(n/t)复杂度+vector排序)
下一篇:快速排序
相关文章
图文推荐
文章
推荐
点击排行

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站