HDU1561:The more, The Better——题解

http://acm.hdu.edu.cn/showproblem.php?pid=1561

ACboy很喜欢玩一种战略游戏,在一个地图上,有N座城堡,每座城堡都有一定的宝物,在每次游戏中ACboy允许攻克M个城堡并获得里面的宝物。但由于地理位置原因,有些城堡不能直接攻克,要攻克这些城堡必须先攻克其他某一个特定的城堡。你能帮ACboy算出要获得尽量多的宝物应该攻克哪M个城堡吗?

upd:https://www.cnblogs.com/luyouqi233/p/12403258.html 和它一样,换了种代码和理解写,更加好看了。

O(n*m^2)的复杂度相信大家已经都会了。 

(代码注释区域的dfs)

这里介绍一种O(n*m)的算法,参考https://www.cnblogs.com/Patt/p/5642181.html与徐持衡的论文。

设dp[i][j]为取根节点到i节点路径上的所有点,再从这条路径的左边上和i的子树上取j体积的点的最大价值。最后答案为dp[0][m]。

(看起来这个定义没法想,但是徐的论文给的方法是泛化物品合并……这个方法到现在还没有看懂。)

对于所谓“路径的左边”可理解为dfs序比i小且不在这条路径上的合法路径。

(更饶了*2)

有一个看起来很妙的方程dp[u][j]=max(dp[u][j],dp[v][j-1]);

当然在这之前每个儿子我们都需要更新,dp[v][j]=dp[u][j]+w[v],然后把v递归跑一遍。

(思考为什么不是dp[u][j+1])

(卡了很久思索出了结果,实际很简单,对dp[u][j]状态它根本没选择v及其子树的点,所以初始时dp[v][j]选择的j个点正好是dp[u][j]的j个点)

#include<cstdio>
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;
const int N=250;
inline int read(){
    int X=0,w=0;char ch=0;
    while(!isdigit(ch)){w|=ch=='-';ch=getchar();}
    while(isdigit(ch))X=(X<<3)+(X<<1)+(ch^48),ch=getchar();
    return w?-X:X;
}
struct node{
    int to,nxt;
}e[N];
int cnt,head[N];
int n,m,w[N],dp[N][N];
inline void add(int u,int v){
    e[++cnt].to=v;e[cnt].nxt=head[u];head[u]=cnt;
}
/*void dfs(int u){
    for(int i=head[u];i;i=e[i].nxt){
    int v=e[i].to;
    dfs(v);
    for(int j=m;j>=2;j--){//保证无后效性
        for(int k=1;k<j;k++){
        dp[u][j]=max(dp[u][j],dp[u][k]+dp[v][j-k]);
        }
    }
    }
}*/
void dfs(int u,int c){
    if(c<=0)return;
    for(int i=head[u];i;i=e[i].nxt){
    int v=e[i].to;
    for(int j=0;j<c;j++){
        dp[v][j]=dp[u][j]+w[v];
    }
    dfs(v,c-1);
    for(int j=1;j<=c;j++){
        dp[u][j]=max(dp[u][j],dp[v][j-1]);
    }
    }
}
int main(){
    while(scanf("%d%d",&n,&m)!=EOF&&n+m){
    n++;cnt=0;
    memset(head,0,sizeof(head));
    for(int i=1;i<n;i++){
        int u=read()+1,v=i+1;
        w[v]=read();
        add(u,v);
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
        dp[i][j]=w[i];
        }
    }
    dfs(1,m);
    printf("%d\n",dp[1][m]);
    }
    return 0;
}

+++++++++++++++++++++++++++++++++++++++++++

+本文作者:luyouqi233。               +

+欢迎访问我的博客:http://www.cnblogs.com/luyouqi233/+

+++++++++++++++++++++++++++++++++++++++++++

posted @ 2018-04-14 13:28  luyouqi233  阅读(230)  评论(0编辑  收藏  举报