题干:
The cows are going to space! They plan to achieve orbit by building a sort of space elevator: a giant tower of blocks. They have K (1 <= K <= 400) different types of blocks with which to build the tower. Each block of type i has height h_i (1 <= h_i <= 100) and is available in quantity c_i (1 <= c_i <= 10). Due to possible damage caused by cosmic rays, no part of a block of type i can exceed a maximum altitude a_i (1 <= a_i <= 40000).
Help the cows build the tallest space elevator possible by stacking blocks on top of each other according to the rules.
Input
* Line 1: A single integer, K
* Lines 2..K+1: Each line contains three space-separated integers: h_i, a_i, and c_i. Line i+1 describes block type i.
Output
* Line 1: A single integer H, the maximum height of a tower that can be built
Sample Input
3
7 40 3
5 23 8
2 52 6
Sample Output
48
Hint
OUTPUT DETAILS:
From the bottom: 3 blocks of type 2, below 3 of type 1, below 6 of type 3. Stacking 4 blocks of type 2 and 3 of type 1 is not legal, since the top of the last type 1 block would exceed height 40.
题目大意:
给出了一些砖块,砖块有高度,最高可以达到的高度(高度限制)和数量,问最高可以摞多高的塔。
解题报告:
首先按照限制高度排序这点没问题吧。反正我早晚都得排序,还不如先排那些可能被高度限制住的。
我们都知道,多重背包可以转化成0-1背包类模板的问题去求解,也可以转化成完全背包类模板去求解,即,一个是正向遍历,一个是反向遍历(内层循环的时候),
AC代码:(多重背包转完全背包模型去求解,即正向遍历的模型,然后把那些限制都变成一个个的if判断就好了。)
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#define ll long long
using namespace std;
struct Node {
int h,a,c;
} node[500];
int dp[40000 + 5];
int sum[40000 + 5];
bool cmp(const Node &a,const Node &b) {
return a.a<b.a;
}
int main()
{
int ans = 0;
int KK;
cin>>KK;//
for(int i =1; i<=KK; i++) {
scanf("%d%d%d",&node[i].h,&node[i].a,&node[i].c);
}
sort(node + 1,node+KK+1,cmp);
dp[0] = 1;
for(int i = 1; i<=KK; i++) {
// for(int k = 1; k<=node[i].c; k++)
// for(int j =40000; j>=node[i].a; j--) {
// dp[j] = max(dp[j])
// }
memset(sum,0,sizeof(sum));//记录当前这个物品在j高度(相当于是体积)
for(int j = node[i].h; j <= node[i].a; j++) {
if(dp[j] == 0 &&dp[j - node[i].h ] == 1&& sum[j -node[i].h ] + 1 <= node[i].c) {//如果dp[j]当前高度更新过了,那就不再更新,因为我们可以留着这一块砖头放到更高的地方。
sum[j ] = sum[j -node[i].h ] + 1;
dp[j] = 1;
ans = max(ans,j);
}
}
}
printf("%d\n",ans);
return 0 ;
}
或者:(多重背包转换成0-1背包去求解,b结构体为node这个多重背包的结构体 经过二进制优化后存入的结构体)
注意的就是最后最大高度的dp[node[KK].a ]不一定是最优解
因为这个dp[node[KK].a ]的最值是从上一步过来的
而由于上一步dp的 node[KK].a 更小,因此dp数组存在断档
所以要最后从头扫一遍才能得出最优解,或者直接在线维护一个maxx就可以了
sort(b+1,b+p,cmp);
int maxx = 0;
for(int i=1;i<p;++i){
for(int j=b[i].a;j>=b[i].h;--j){ //背包容量从cost开始才有效
dp[j] = max(dp[j],dp[j-b[i].h]+b[i].h);
maxx = max(maxx,dp[j]);
}
}
cout<<mmax<<endl;