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.
多重背包:
因为每一块砖都有最大荷载,假设有一块砖A,在A上面的所有砖的重量不能超过A的最大荷载。
那么在最底层的砖一定是荷载最大的。所以按砖块的荷载升序排列。
砖的荷载相当于背包的容量
二进制优化+拆解
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define maxn 40050
#define INF 0x3f3f3f3f
int dp[maxn];
struct block{
int h, a, c;
};
bool cmp(block x, block y){
return x.a < y.a;
}
int main()
{
int k, i, j, l, n, ans = 0;
block b[405];
scanf("%d",&k);
for(i = 1; i <= k; ++i){
scanf("%d %d %d", &b[i].h, &b[i].a, &b[i].c);
}
sort(b+1,b+k+1, cmp);
memset(dp, 0,sizeof(dp));
for(i = 1; i <= k; ++i){
if(b[i].h * b[i].c >= b[i].a){
for(l = b[i].h; l <= b[i].a; ++l){
dp[l] = max(dp[l], dp[l - b[i].h] + b[i].h);
}
}
else{
for(n = 1; n <= b[i].c; n *= 2){
for(j = b[i].a; j >= b[i].h*n; --j){
dp[j] = max(dp[j], dp[j - b[i].h*n]+b[i].h*n);
}
b[i].c -= n;
}
if(b[i].c > 0){
for(j = b[i].a; j >= b[i].h*b[i].c; --j){
dp[j] = max(dp[j], dp[j - b[i].h*b[i].c]+b[i].h*b[i].c);
}
}
}
//printf("%d\n",dp[b[i].a]);
}
for(i = 1; i <= b[k].a; ++i)
ans = max(ans, dp[i]);
printf("%d\n",ans);
}
因为状态转移方程是→_→dp[l] = max(dp[l], dp[l - b[i].h] + b[i].h)(背包的价值与物品的体积是相同的),所以还可以用这种方法( 这题上面那种方法时间是157ms,这种方法是63ms (⊙o⊙))。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
#define maxn 40050
#define INF 0x3f3f3f3f
int dp[maxn], num[maxn];
struct block{
int h, a, c;
};
bool cmp(block x, block y){
return x.a < y.a;
}
int main()
{
int k, i, j, l, n, ans = 0;
block b[405];
scanf("%d",&k);
for(i = 1; i <= k; ++i){
scanf("%d %d %d", &b[i].h, &b[i].a, &b[i].c);
}
sort(b+1,b+k+1, cmp);
dp[0] = 1;
for(i = 1; i <= k; ++i){
memset(num,0,sizeof(num));
for(j = b[i].h; j <= b[i].a ; ++j){
if(!dp[j] && dp[j - b[i].h]&&num[j-b[i].h]< b[i].c){
dp[j] = 1;
num[j] = num[j-b[i].h] +1;
if(ans < j) ans = j;
}
}
}
printf("%d\n",ans);
}