算法----最大承载量下的最大价值问题
代码:
栈代码:(存储哪些是需要的价值物)
#pragma once
#include<stdio.h>
#define maxSize 100
typedef struct stack {int * base;int * top;
}stack;
bool init(stack & Stack) {//栈的初始化Stack.base = new int[maxSize];if (!Stack.base) {return false;}Stack.top = Stack.base;return true;
}
bool push(stack & Stack,int e) {//入栈if (Stack.top - Stack.base == maxSize) {//满栈,不能再插入return false;}*(Stack.top) = e;Stack.top++;return true;
}
bool pop(stack & Stack, int &e) {//出栈if (Stack.base == Stack.top) {//栈空return false;}Stack.top--;e = *(Stack.top);return true;
}
int getTop(stack &Stack) {if (Stack.base == Stack.top) {//栈空return -1;}return *(Stack.top - 1);
}
void printStack(stack Stack) {//遍历栈中的元素while (Stack.base != Stack.top) {printf("%d ", *(Stack.top - 1));Stack.top--;}
}
bool empty(stack Stack) {//栈空的判断if (Stack.base == Stack.top) {return true;}return false;
}
void testStack() {//测试栈是否有问题stack Stack;init(Stack);int value;while (1) {scanf_s("%d", &value);if (value == -1) {break;}push(Stack, value);}printStack(Stack);
}
核心代码:
#include<stdio.h>
#include<stdlib.h>
#include"stack.h"
int MaxValues = 0, tempValues = 0;//最大价值和每次递归从树根到叶子结点的最大价值
int tempWeight = 0, maxWeight;//本次从根节点到其中一个叶子结点的最大临时重量和人能承载的最大重量
int w[100],p[100];//每个宝贝物品的重量和价值
stack Stack24;
void backTrace(int h,int maxH) {//最大承载量下的最大价值if (h == maxH) {if (tempValues > MaxValues) {MaxValues = tempValues;int * v = Stack24.top;printStack(Stack24);Stack24.top = v;printf("\n");}return;}if (tempWeight + w[h] <= maxWeight) {tempWeight += w[h];tempValues += p[h];push(Stack24, h);backTrace(h + 1, maxH);tempWeight -= w[h];tempValues -= p[h];int e;pop(Stack24, e);}backTrace(h + 1, maxH);
}
int main() {init(Stack24);int n;scanf_s("%d%d", &maxWeight,&n);for (int i = 0; i < n; i++) {scanf_s("%d%d", &w[i],&p[i]);}backTrace(0, n);printf("最大承载量下的最大价值为:%d\n",MaxValues);system("pause");return 0;
}