原题连接:http://acm.hdu.edu.cn/showproblem.php?pid=3449
题意:自己看吧~~~
思路一:先对箱子里的物品进行一次01背包,然后加上箱子价格,在进行分组背包,然后TLE !!白写了一个下午呀!!!
超时代码:
#include<stdio.h> #include<stdlib.h> #include<iostream> #include<cstring> #include<algorithm> using namespace std; const int Max = 1000000 +10; const int base = 2; int dp[Max],N,V; int loop[60]; struct Goos { int cost; int value; }G[60][Max]; void Zero_One(int cost , int value , int vb) { int i; for(i = V-vb;i >= cost;i --) { dp[i] = max(dp[i] , dp[i-cost]+value); } } void display(int m) { int i,j; for(i = 1;i <= m;i ++) { for(j = 0;j < loop[i];j ++) printf(" %d-%d ",G[i][j].cost,G[i][j].value); printf("\n"); } } void Group_Package(int m) { int i,j,k; memset(dp,0,sizeof(dp)); for(i = 1;i <= m;i ++) { for(j = V;j >= 0; j--) { for(k = 0;k < loop[i];k ++) { if(j >= G[i][k].cost) dp[j] = max(dp[j] , dp[j-G[i][k].cost]+G[i][k].value); } } } printf("%d\n",dp[V]); } int main() { int i,j; while(~scanf("%d%d",&N,&V)) { int vb,k; int m = 1; //memset(Gdp,0,sizeof(Gdp)); memset(loop,-1,sizeof(loop)); for(i = 0;i < N;i ++) { scanf("%d%d",&vb,&k); memset(dp,-9,sizeof(dp)); dp[0] = 0; for(j = 0;j < k;j ++) { int cost,value; scanf("%d%d",&cost,&value); Zero_One(cost,value,vb); } int n = 0; for(j = 1; j <= V-vb;j ++) if(dp[j]>0) { G[m][n].cost = j+vb; G[m][n++].value = dp[j]; } loop[m] = n; m++; } //display(m-1); Group_Package(m-1); } }
思路二:自己看代码吧~~~
#include<stdio.h> #include<stdlib.h> #include<iostream> #include<cstring> #include<algorithm> using namespace std; const int Max = 1000000 +10; int dp[Max],N,V; int d[Max]; void Zero_One(int cost , int value , int vb) { int i; for(i = V;i >= vb+cost;i --) { dp[i] = max(dp[i] , dp[i-cost]+value); } } int main() { int i,j; while(~scanf("%d%d",&N,&V)) { int vb,k; memset(d,0,sizeof(d)); for(i = 0;i < N;i ++) { scanf("%d%d",&vb,&k); for(j = 0;j <= V-vb;j ++) dp[j+vb] = d[j]; for(j = 0;j < k;j ++) { int cost,value; scanf("%d%d",&cost,&value); Zero_One(cost,value,vb); } for(j = vb;j <= V;j ++) d[j] = max(d[j],dp[j]); } printf("%d\n",d[V]); } }