|
发表于 2023-10-24 23:33:24
|
显示全部楼层
以下是使用栈的基本操作来解决背包问题的C语言代码实现:
- #include <stdio.h>
- #include <stdlib.h>
- #define MAX_ITEMS 100
- typedef struct {
- int weight;
- int value;
- } Item;
- typedef struct {
- Item items[MAX_ITEMS];
- int top;
- } Stack;
- Stack* createStack() {
- Stack* stack = (Stack*)malloc(sizeof(Stack));
- stack->top = -1;
- return stack;
- }
- int isEmpty(Stack* stack) {
- return stack->top == -1;
- }
- void push(Stack* stack, Item item) {
- stack->items[++stack->top] = item;
- }
- Item pop(Stack* stack) {
- return stack->items[stack->top--];
- }
- Item peek(Stack* stack) {
- return stack->items[stack->top];
- }
- int maxValue(int maxWeight, Item* items, int numItems) {
- Stack* stack = createStack();
- int i, totalValue = 0, totalWeight = 0;
- for (i = 0; i < numItems; i++) {
- if (totalWeight + items[ i].weight <= maxWeight) {
- push(stack, items[ i]);
- totalWeight += items[ i].weight;
- totalValue += items[ i].value;
- } else {
- break;
- }
- }
- if (i < numItems) {
- int remainingWeight = maxWeight - totalWeight;
- Item currentItem = items[ i];
- while (!isEmpty(stack) && currentItem.weight > remainingWeight) {
- Item poppedItem = pop(stack);
- totalWeight -= poppedItem.weight;
- totalValue -= poppedItem.value;
- currentItem = peek(stack);
- }
- if (currentItem.weight <= remainingWeight) {
- push(stack, currentItem);
- totalWeight += currentItem.weight;
- totalValue += currentItem.value;
- }
- }
- free(stack);
- return totalValue;
- }
- int main() {
- int numItems, maxWeight, i;
- printf("Enter the number of items: ");
- scanf("%d", &numItems);
- Item* items = (Item*)malloc(numItems * sizeof(Item));
- for (i = 0; i < numItems; i++) {
- printf("Enter weight and value for item %d: ", i + 1);
- scanf("%d %d", &items[ i].weight, &items[ i].value);
- }
- printf("Enter the maximum weight of the knapsack: ");
- scanf("%d", &maxWeight);
- int result = maxValue(maxWeight, items, numItems);
- printf("Maximum value that can be achieved: %d\n", result);
- free(items);
- return 0;
- }
复制代码
请确保在运行代码之前,将背包问题的具体细节与约束条件准确输入,以获取正确的结果。
请注意,本回答来自GPT-4
如果问题已经解决,请设置最佳答案 |
|