第一个自己写的代码
不是ctrl+c, ctrl+v了
#include "pch.h"
#include <iostream>
int w[5] = { 800, 400, 300, 400, 200 };
int v[5] = { 2, 5, 5, 3, 2 };
int choose[5] = { 0,0,0,0,0 };
int limit = 1000;
int happy = 0;
void search(int m);
int checkmax();
int main()
{
//readdata();
search(0);
std::cout << happy << std::endl;
}
void search(int m) //回溯法,深度优先
{
if (m > 5 || m == 5)
{
int temp_sum = 0;
int i;
for (i = 0; i < 5; i++) {
if (choose[i] == 1)temp_sum += w[i] * v[i];
}
if (temp_sum > happy)happy = temp_sum;
return ;
}
else
{
choose[m] = 1;
if (checkmax()) {
search(m + 1);
}
choose[m] = 0;
search(m + 1);
}
}
int checkmax()//不得超过最大重量限制,左剪枝
{
int i;
int sumweight = 0;
for (i = 0; i < 5; i++)
{
if (choose[i] == 1)
{
sumweight += w[i];
}
}
if (sumweight > 1000)return 0;
else return 1;
}