#include<iostream>
#include<stdlib.h>
using namespace std;
#define MaxNumber 100
int *Weight = new int[MaxNumber];
int *Value = new int[MaxNumber];
int MaxWeight;
void sort(int length) {
int num = 0;
for (int i = 0; i < length; i++)
{
for (int j = i; j < length; j++)
{
if (Weight[i] > Weight[j]) {
num = Weight[i];
Weight[i] = Weight[j];
Weight[j] = num;
num = Value[i];
Value[i] = Value[j];
Value[j] = num;
}
if (Weight[i] == Weight[j]) {
if (Value[i] <Value[j]) {
num = Weight[i];
Weight[i] = Weight[j];
Weight[j] = num;
num = Value[i];
Value[i] = Value[j];
Value[j] = num;
}
}
}
}
}
int main() {
cout << "输入物品数量:";
int length = 0;
cin >> length;
cout << endl;
cout << "输入物品的质量及其价值" << endl;
for (int i = 0; i < length; i++)
{
cin >> Weight[i];
cin >> Value[i];
}
cout << "----------------------------------" << endl;
cout << " 数据输入完毕 " << endl;
cout << "----------------------------------" << endl;
sort(length);
for (int i = 0; i < length; i++)
{
cout << "物品" << i + 1 << "号: ";
cout << "质量:" << Weight[i] << "、价值:" << Value[i] << endl;
}
cout << "----------------------------------" << endl;
cout << " 数据录入完毕 " << endl;
cout << "----------------------------------" << endl;
cout << "输入背包最大承受重量:";
cin >> MaxWeight;
int *Form = new int[MaxNumber];
cout << "最大承受重量:";
for (int j = 0; j < MaxWeight; j++)
{
cout <<"" << j+1 << " ";
}
cout << endl;
for (int i = 0; i < length; i++)
{
int totall = 0;
for (int q = 0; q <= i; q++)
{
totall += Weight[q];
}
for (int j = 1; j <=MaxWeight; j++)
{
Form[j-1] = 0;
}
for (int j = 1; j <=MaxWeight; j++)
{
for (int m = 0; m <=i; m++)
{
if (totall <=j) {
if (totall == j) {
int all = 0;
for (int l = 0; l <= i; l++) {
all += Value[l];
}
Form[j - 1] = all;
}
else {
Form[j - 1] = Form[j - 2];
}
}
else {
if (Weight[m] >j) {
if (m == 0) {
Form[j-1] = Value[m];
}
else {
break;
}
}
else {
if (Weight[m] == j) {
if (m == 0) {
Form[j - 1] = Value[m];
}
else {
if (Value[m] > Form[j - 2]) {
Form[j - 1] = Value[m]>Form[j-1]?Value[m]:Form[j-1];
}
else {
Form[j - 1] = Form[j - 2];
}
}
}
else {
if (m == 0) {
Form[j - 1] = Value[m];
}
else {
if (Form[j-1 - Weight[m]] + Value[m] > Form[j - 2]) {
Form[j-1] = Form[j-1 - Weight[m]] + Value[m];
}
else {
Form[j-1] = Form[j - 2];
}
}
}
}
}
}
}
cout<< " 第" << i + 1 << "个物品:";
for (int j = 0; j < MaxWeight; j++)
{
cout << Form[j] << " ";
}
cout << endl;
}
return 0;
}
背包算法(C++实现)
最新推荐文章于 2024-06-29 19:14:38 发布