两个背包问题都是比较典型的问题,对这两种算法的理解有很好的帮助.
0/1背包问题--
问题描述:
设U = {u1,u2,u3,......ui}(一共有amount数量的物品)是一组准备放入背包中的物品.设背包的容量为size.
定义每个物品都具有两个属性weight和value.
我们要解决的问题就是计算在所选取的物品总重量不超过背包容量size的前提下使所选的物品总价值最大.
程序的设计:
设V[i, j]用来表示从前i项{u1......ui}中取出来的装入体积为j的背包的最大价值.i的范围是从0到amount,j是从0到size.这样的话要计算的值就是V[amount, size].V[0, j]对于所有的j的值都是0,因为这时候的包中没有物品.同时V[i, 0]的值也是0,因为没有物品可以放到size为0的背包里面.
所以有:
V[i, j] = 0 若i = 0 或 j = 0;
V[i, j] = V[i - 1, j] 若j < ui.weight;(当物品的重量大于背包承重时,就不巴物品放在里面)
V[i, j] = max{V[i - 1, j], V[i - 1, j - ui.weight] + ui.value} 若i > 0并且j >= ui.weight;
现在就可用动态规划的方法运用上面的公式来填表求解了.
#include <stdio.h>
#define W 1000
#define N 1000
typedef struct data
...{
int vaule;
int weight;
}goods;
int returnmax(int a, int b)
...{
return (a > b ? a : b);
}
int KNAPSACK(goods *P, int a, int s)
...{
int V[N][W];
int i,j,mv;
for(i = 0; i < a; i++)
V[i][0] = 0;
for(j = 0; j < s; j++)
V[0][j] = 0;
for(i = 1; i <= a; i++)
for(j = 1; j <= s; j++)
...{
V[i][j] = V[i - 1][j];
if(P[i].weight <= j)
V[i][j] = returnmax(V[i][j],V[i - 1][j - P[i].weight] + P[i].vaule);
}
mv = V[a][s];
return mv;
}
int main()
...{
int mostvalue,amount,size,i;
goods A[N];
printf("Input how much the goods have: ");
scanf("%d",&amount);
printf("Input the size of the bag: ");
scanf("%d",&size);
printf("Input the data of the goods: ");
for(i = 0; i < amount; i++)
scanf("%d %d",&A[i].vaule,&A[i].weight);
mostvalue = KNAPSACK(A,amount,size);
printf("%d",mostvalue);
return 0;
}
优化的问题:
1.由于计算当前行的时候只需要上一行的结果,所以修改一下程序就可以减少使用的空间.
2.如果要输出所选的物品也是可以实现的.
PS:0/1背包问题和普通背包的差别就在于(1)物品是否可以重复选择, (2)物品是否可以只选取部分.
普通背包问题--
问题描述:
参看上面的PS;
程序的设计:
因为可以重复的选取物品,而且可以部分的选取物品,所以背包应该是完全填满的(0/1背包问题背包不一定是满的).
因此可以先计算每个物品的性价比,然后排序,最后按顺序选取,直到背包填满.
#include <stdio.h>
#include <stdlib.h>
#define MAX 100000
typedef struct data
...{
long value;
long weight;
double average;
}goods;
compare(const void *a, const void *b)
...{
return -(int)(((goods *)a)->average - ((goods *)b)->average);
}
long KNAPSACK(goods *A, long amount, long size)
...{
double mv = 0;
long i = 0;
long mvresult;
while(size && amount)
...{
if(size >= (A + i)->weight)
...{
mv += (A + i)->value;
size -= (A + i)->weight;
}
else
...{
mv += ((A + i)->average) * size;
size = 0;
}
i++;
amount--;
}
mvresult = (long)mv;
return mvresult;
}
int main()
...{
goods A[MAX];
long amount, size, i, temp, mostvalue;
printf("Input the amount of the goods and the size of the bags: ");
scanf("%ld %ld", &amount, &size);
printf("Input the weight and value of each goods: ");
for(i = 0; i < amount; i++)
...{
scanf("%ld %ld",&A[i].weight, &A[i].value);
A[i].average = A[i].value / A[i].weight;
}
qsort(A, amount, sizeof(A[0]), compare);
mostvalue = KNAPSACK(A, amount, size);
printf("The most value is %ld ", mostvalue);
return 0;
}