算法—背包问题
参考:趣学算法
代码:
typedef struct three {
float w;
float v;
float p;
}three;
#define elemType three
int quickSort1(elemType a[], int l, int h) {//快速排序
int i = l, j = h;
elemType p1 = a[i];
while (i < j) {
while (i<j&&a[j].p>=p1.p) {//从右往左遍历查找比p1更小的元素
j--;
}
if (i < j) {
a[i++] = a[j];
}
while (i < j&&a[i].p < p1.p) {//从左往右遍历查找比p1更大的元素
i++;
}
if (i < j) {
a[j--] = a[i];
}
}
a[i] = p1;//分界的值,左边小于等于p1,右边大于p1
return i;
}
void fenZhi1(elemType a[], int l, int h) {//分治
if (l < h) {
int mid = quickSort1(a, l, h);//以mid为分界线,进行分治,然后递归下去排序
fenZhi1(a, l, mid - 1);
fenZhi1(a, mid + 1, h);
}
}
#include <stdio.h>
#include <stdlib.h>
#include"quickSort1.h"
int main() {
elemType a[100];
int num,i=0;
scanf_s("%d", &num);
while (i<num) {
scanf_s("%f%f", &a[i].w,&a[i].v);
a[i].p = a[i].v / a[i].w;
i++;
}
fenZhi1(a, 0, num-1);//调动分治策略实现所有趟快速排序,而不是调用快速排序一趟进排序
for (i = 0; i < num; i++) {
printf("%f %f %f\n", a[i].w, a[i].v, a[i].p);
}
float sum = 0.0,maxValue=0.0,acceptWeight;
scanf_s("%f", &acceptWeight);
for (i = num-1; i>=0; i--) {
if (sum + a[i].w <= acceptWeight) {
sum += a[i].w;
maxValue += a[i].v;
}
else {
maxValue += (acceptWeight - sum)*a[i].p;
sum += (acceptWeight - sum);//装满
break;
}
}
printf("背包问题获得的最大值:%f\n", maxValue);
system("pause");
return 0;
}
测试截图:
时间复杂度O(nlogn),空间复杂度O(n)
彩蛋:不可分的0-1问题如何寻找最优值??
动态规划!!!