鱼C论坛

 找回密码
 立即注册
查看: 1592|回复: 1

为什么我写的程序老是崩溃,跪求大神帮忙看一下(回朔法求0/1背包问题)

[复制链接]
发表于 2018-11-5 23:56:52 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. #include<iostream>
  2. using namespace std;
  3. int n;//物品个数
  4. int BackpackVolume;//背包容量
  5. int maxValue;//最大价值
  6. int *weight = new int[n];//物品的重量
  7. int *value = new int[n];//物品的价值
  8. int *bestPath = new int[n];//最佳路径
  9. int *judge = new int[2]; //判断左右分支
  10. int currentWeight=0;//当前重量
  11. int currentValue=0;//当前价值
  12. void dfs(int i) {
  13.        
  14.         if(i>n){
  15.                 if (currentValue > maxValue) {
  16.                         maxValue = currentValue;
  17.                         for(i=1;i<=n;i++){
  18.                                 bestPath[i] = judge[i];
  19.                         }
  20.                 }
  21.         }
  22.         else
  23.         {
  24.                 for (int j = 1; j >= 0; j--) {
  25.                         judge[i] = j;
  26.                         if (currentWeight + weight[i]* judge[i] <= BackpackVolume) {

  27.                                 currentWeight += weight[i] * judge[i];
  28.                                 currentValue += value[i] * judge[i];
  29.                                 dfs(i + 1);
  30.                                 currentWeight-= weight[i] * judge[i];
  31.                                 currentValue -= value[i]* judge[i];
  32.                         }
  33.                
  34.                 }
  35.         }
  36. }

  37. int main()
  38. {
  39.         int i;
  40.         maxValue = 0;
  41.         cout << "请输入背包最大容量:" << endl;;
  42.         cin >> BackpackVolume;
  43.         cout << "请输入物品个数:" << endl;
  44.         cin >> n;
  45.         cout << "请依次输入物品的重量:" << endl;
  46.         for (i = 1; i <= n; i++)
  47.                 cin >> weight[i];
  48.         cout << "请依次输入物品的价值:" << endl;
  49.         for (i = 1; i <= n; i++)
  50.                 cin >> value[i];
  51.         dfs(1);
  52.         cout << "最大价值为:" << endl;
  53.         cout << maxValue << endl;
  54.         cout << "被选中的物品的标号依次是:" << endl;
  55.         for (i = 1; i <= n; i++){
  56.                 if (bestPath[i] == 1)
  57.                         cout << i << " ";
  58.         }       
  59.         cout << endl;
  60.         return 0;
  61. }
复制代码
360截图20181105235507361.jpg
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2018-11-6 00:23:37 | 显示全部楼层
第55行一运行就崩溃???????????????????????
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-23 22:38

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表