Knapsack Problem

Description: Suppose there is a backpack with a load of up to 8 kg, and you want to load the total price items available within the load range in the backpack. Assuming that the fruit is ready, the serial number, unit price and weight of the fruit are as follows:

0 Plum 4KG NT$4500
1 Apple 5KG NT$5700
2 tangerinr 2KG NT$2250
3 Strawberry 1KG NT$1100
4 melon 6KG NT$6700


Solution: The knapsack problem is about optimization. To solve the optimization problem, you can use "Dynamic programming". Starting from an empty set, each time an element is added, the best solution at this stage is obtained until All elements are added to the set, and the final result is the best solution. Taking the knapsack problem as an example, we use two arrays, value and item, where value represents the total price of the current optimal solution, and item represents the last fruit put into the backpack. Suppose there are 8 backpacks with negative weights 1 to 8, and Find the best solution for each knapsack. Put the fruits into the backpack step by step, and find the best solution at this stage: Putting plums into the backpack can load up to 9,050 yuan of fruit when the backpack is loaded with 8 kg, and the last fruit to be loaded is No. 3, which is strawberries. , loaded with strawberries, the backpack can only put 7 kg (8-1) of fruit, so you must see the best solution when the backpack is loaded with 7 kg, the last one is put in No. 2, which is orange, now the backpack The remaining load is 5kg (7-2), so looking at the best solution for the 5kg load, the last one to put in is No. 1, which is an apple. At this time, the backpack has a load of 0kg (5-5). Then add fruit, so the best solution is to add strawberries, oranges and apples, and the total price is 9050 yuan.

#include <stdio.h>
#include <stdlib.h>
#define LIMIT 8 // 重量限制
#define N 5 // 物品种类
#define MIN 1 // 最小重量
struct body {
    char name[20];
    int size;
    int price;
};
typedef struct body object;
int main(void) {
    int item[LIMIT+1] = {0};
    int value[LIMIT+1] = {0};
    int newvalue, i, s, p;
    object a[] = {
   
   {"李子", 4, 4500},{"苹果", 5, 5700},{"橘子", 2, 2250},{"草莓", 1, 1100},{"甜瓜", 6, 6700}};
    for(i = 0; i < N; i++) {
        for(s = a[i].size; s <= LIMIT; s++) {
            p = s - a[i].size;
            newvalue = value[p] + a[i].price;
            if(newvalue > value[s]) {// 找到阶段最佳解
                value[s] = newvalue;
                item[s] = i;
            }
        }
    }
    printf("物品\t价格\n");
    for(i = LIMIT; i >= MIN; i = i - a[item[i]].size) {
        printf("%s\t%d\n",
               a[item[i]].name, a[item[i]].price);
    }
    printf("合计\t%d\n", value[LIMIT]);
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324505120&siteId=291194637