HDU2191 多重背包
题意:
中文不解释
要点:
多重背包裸题,主要是用了两种做法,一种直接按个数全拆成01背包,复杂度是O(V*Σn[i]);一种用二进制拆成复杂度为O(V*Σlog n[i])。
复杂度是O(V*Σn[i]):
16571118 | 2016-03-16 15:17:11 | Accepted | 2191 | 31MS | 1416K | 512 B | G++ | seasonal |
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define max(a,b) a>b?a:b
int v[150], w[150], c[150],dp[150];
int n, m;
int main()
{
int t,i,j,k;
scanf("%d", &t);
while (t--)
{
memset(dp, 0, sizeof(dp));
scanf("%d%d", &m, &n);
for (int i = 0; i < n; i++)
scanf("%d%d%d", &w[i], &v[i], &c[i]);
for (i = 0; i < n; i++)
for (j = 0; j < c[i]; j++)//拆成c[i]个01背包
for (k = m; k >= w[i]; k--)
dp[k] = max(dp[k], dp[k - w[i]] + v[i]);
printf("%d\n", dp[m]);
}
return 0;
}
16570781 | 2016-03-16 14:37:38 | Accepted | 2191 | 0MS | 1432K | 985 B | G++ | seasonal |
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define max(a,b) a>b?a:b
int v[1500], w[1500], c[1500],dp[1500];
int n, m;
void one_pack(int cost, int weight)//01背包
{
for (int j = m; j >= cost; j--)
dp[j] = max(dp[j], dp[j - cost] + weight);
}
void complete_pack(int cost, int weight)//完全背包
{
for (int j = cost; j <= m; j++)
dp[j] = max(dp[j], dp[j -cost] + weight);
}
void multiple_pack(int cost, int weight, int count)
{
int i;
if (cost*count >= m)//如果一开始就count*cost>=m,可以看成无限种也就是完全背包
{
complete_pack(cost, weight);
}
else
{
int k=1;
while (k < count)
{
one_pack(k*cost, k*weight);//相当于01背包
count -= k;
k *= 2; //利用二进制思想可以表示1-count的所有值
}
one_pack(count*cost, count*weight);//最后处理剩下的个数
}
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
memset(dp, 0, sizeof(dp));
scanf("%d%d", &m, &n);
for (int i = 0; i < n; i++)
scanf("%d%d%d", &w[i], &v[i], &c[i]);
for (int i = 0; i < n; i++)
multiple_pack(w[i], v[i], c[i]);
printf("%d\n", dp[m]);
}
return 0;
}