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
Help the cows build the tallest space elevator possible by stacking blocks on top of each other according to the rules.
* 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
* 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.
* 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 6Sample Output
48Hint
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.
PS:看题的时候不知道怎么思考,但是,将所有的块数按最大的限制长度重小到大排序后,就会发现这是一个多重背包问题,但是也可以用完全背包做,而且完全背包的时间复杂度还小一些,下面给出两种做法的代码。
多重背包
#include <iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<string>
#include<map>
const int maxn= 5e2+5;
const int mod=1e9;
#define me(a) memset(a,0,sizeof(a))
#define ll long long
using namespace std;
struct node
{
int h,m,c;
bool friend operator<(node a,node b)
{
return a.m<b.m;
}
};
int main()
{
node a[maxn];
int n;
cin>>n;
for(int i=0;i<n;i++)
scanf("%d%d%d",&a[i].h,&a[i].m,&a[i].c);
sort(a,a+n);
int dp[40005],num[40005];me(dp),me(num);
int ma=0;
for(int i=0;i<n;i++)
{
for(int t=0;t<a[i].c;t++)
for(int j=a[i].m;j>=a[i].h;j--)
{
dp[j]=max(dp[j-a[i].h]+a[i].h,dp[j]);
if(dp[j]>ma)
ma=dp[j];
}
}
cout<<ma<<endl;
return 0;
}
完全背包
#include <iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<string>
#include<map>
const int maxn= 5e2+5;
const int mod=1e9;
#define me(a) memset(a,0,sizeof(a))
#define ll long long
using namespace std;
struct node
{
int h,m,c;
bool friend operator<(node a,node b)
{
return a.m<b.m;
}
};
int main()
{
node a[maxn];
int n;
cin>>n;
for(int i=0;i<n;i++)
scanf("%d%d%d",&a[i].h,&a[i].m,&a[i].c);
sort(a,a+n);
int dp[40005],num[40005];me(dp);
int maxn=0;
dp[0]=1;
for(int i=0;i<n;i++)
{
me(num);
for(int j=a[i].h;j<=a[i].m;j++)
{
if(dp[j-a[i].h]&&!dp[j]&&num[j-a[i].h]+1<=a[i].c)
{
dp[j]=1;
num[j]=num[j-a[i].h]+1;
if(j>maxn)
maxn=j;
}
}
}
cout<<maxn<<endl;
return 0;
}