http://poj.org/problem?id=2392
題意:
有一群牛要上太空。他們計劃建一個太空梯-----用一些石頭壘。他們有K種不同型別的石頭,每一種石頭的高度為h_i,數量為c_i,並且由於會受到太空輻射,每一種石頭不能超過這種石頭的最大建造高度a_i。幫助這群牛建造一個最高的太空梯。
吐槽:
做練習的時候,連需不需要對資料排序都沒分析清楚。。。下次再也不把練習安排在上午了,一般我上午狀態極差(┬_┬)
這題由於資料較水,可以直接把多重揹包轉化為01揹包求解,當然由於設定的狀態不一樣,寫法也會不一樣滴。
Code1(01揹包):
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn= 410;
int dp[40010];
struct node {
int h, a, c;
bool operator <(const node& rhs) const {
return a< rhs.a;
}
};
node f[maxn]; int main()
{
int k, n, i, j, ans, maxa;
while(~scanf("%d",&n)) {
for(i=1; i<=n; i++) {
scanf("%d%d%d",&f[i].h,&f[i].a,&f[i].c);
}
sort(f+1,f+1+n);
memset(dp,0,sizeof(dp));
for(i=1; i<=n; i++) {
for(k=f[i].c; k>=1; k--){
for(j=f[i].a; j>=f[i].h; j--)
dp[j] =max(dp[j], dp[j-f[i].h]+f[i].h);
}
}
maxa = 0;
for(j=f[n].a; j>=0; j--)
if(maxa <dp[j]) maxa = dp[j];
printf("%d\n",maxa);
}
return 0;
}
Code(多重揹包):
#include <cstdio>
#include <cstring>
#include <algorithm>
#define max(a,b) a>b ? a:b
using namespace std;
const int maxn= 410;
int dp[40010];
struct node {
int h, a, c;
bool operator <(const node& rhs) const {
return a< rhs.a;
}
};
node f[maxn];
void CompletePack(int C, int W, int V)
{
for(int i=C; i<=V; i++)
dp[i] = max(dp[i],dp[i-C]+W);
}
void ZeroOnePack(int C, int W, int V)
{
for(int i=V; i>=C; i--)
dp[i] = max(dp[i], dp[i-C]+W);
}
void MultipliePack(int C, int W, int M, int V)
{
if(C*M >=V) {
CompletePack(C,W,V);
return ;
}
int k=1;
while(k<M) {
ZeroOnePack(k*C,k*W,V);
M -=k;
k <<=1;
}
ZeroOnePack(C*M,W*M,V);
}
int main()
{
int k, n, i, j, ans, maxH;
while(~scanf("%d",&n)) {
for(i=0; i<n; i++) {
scanf("%d%d%d",&f[i].h,&f[i].a,&f[i].c);
}
sort(f,f+n);
memset(dp,0,sizeof(dp));
for(i=0; i<n; i++) {
MultipliePack(f[i].h,f[i].h,f[i].c,f[i].a);
}
maxH = 0;
for(i=f[n-1].a; i>=0; i--)
if(maxH < dp[i]) maxH = dp[i];
printf("%d\n",maxH);
}
return 0;
}