算法---背包问题
算法—背包問題
參考:趣學算法
代碼:
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,右邊大于p1return 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問題如何尋找最優值??
動態規劃!!!
如果存在什么問題,歡迎批評指正!謝謝!
總結
- 上一篇: 减肥能吃碱水面吗
- 下一篇: word List39