2024年1月22日发(作者:江苏对口单招数学试卷一模)

2020五一数学建模a题代码

#include

#include

using namespace std;

//定义一个用来存储每堆物品的重量的向量

vector weight;

//定义结果数组,默认初始化为0

int result[20];

//定义函数

void BagPack(vectorweight,int bag_total,int current){

//如果当前放入的总重量超过背包的最大重量,跳出函数

if (bag_total > weight[current])

return;

//如果当前正好放完,打印出结果

if (bag_total == weight[current]){

cout << \"Result: [\";

for (int i = 0; i < 20; i++)

cout << result[i] << \" \";

cout << \"]\" << endl;

}

else {

//如果放的重量不够,则放入该物品并继续搜索

result[current] = 1;

BagPack(weight, bag_total - weight[current], current

+ 1);

//不放入该物品,继续搜索

result[current] = 0;

BagPack(weight, bag_total, current + 1);

}

}

int main(){

cout << \"将20堆物品放入装有20kg的背包中:\" << endl;

cout << \"物品重量为:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,

12, 13, 14, 15, 16, 17, 18, 19, 20]\" << endl;

//20堆物品重量定义

int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,

15, 16, 17, 18, 19, 20};

//将每堆物品的重量存放到weight向量中 for (int i=0; i<20; i++)

_back(a[i]);

//20kg作为背包总重量

int bag_total = 20;

BagPack(weight,bag_total,0);

return 0;

}


更多推荐

重量,物品,放入,定义