实现Fractional knapsack(分数背包)排序异常,求C++代码修复方案
分数背包代码异常的根因与修复步骤
核心问题定位
- 排序代码块完全无法触发
原代码中fractotal是所有物品单位收益的累加值,量纲为收益/重量,和代表背包最大承重的total(量纲为重量)无比较意义。本例中计算得到的fractotal为28,远小于60的背包容量,代码会直接触发第一个if分支的全装逻辑,包含排序操作的else if分支永远不会执行,这是排序逻辑看起来“完全不生效”的核心原因。 - 交换逻辑变量误用,导致物品属性完全错乱
排序的交换块中,代码将存放单位收益的临时变量temp2,错误用于profit数组的交换:
即使排序逻辑被触发,交换后的profit、weight、fraction值也无法对应到同一件物品,排序结果完全无效。temp3=profit[i]; profit[i]=profit[j]; profit[j]=temp2; // 错误:此处应使用profit的临时变量temp3完成交换,导致profit数组被随机值覆盖 - 类成员数组定义非法
原代码中类内定义的float fraction[]是未指定容量的柔性数组,不符合C++类成员的语法要求,直接通过下标访问数组会触发未定义行为,可能出现随机崩溃或值错乱。 - 单位收益计算存在整数截断风险
原代码fraction[i]=profit[i]/weight[i]的两个操作数均为int类型,计算结果会被强制截断为整数,丢失小数精度。 - 循环逻辑嵌套错误
物品装入背包的while循环被错误嵌套在遍历数组的for循环内部,会导致流程重复执行,无法正确跟踪已装入重量。 - 输出逻辑无效
原代码中cout<<temp直接输出数组首地址,无实际计算意义。
对应修复方案
- 修正分支判断逻辑
删除原fractotal与total的无效比较,改为计算所有物品的总重量,判断是否可全部装入背包:int totalItemWeight = 0; for(i=0; i<4; i++) { totalItemWeight += weight[i]; } if(totalItemWeight <= total) { cout << "The maximum possible value is " << profittotal << endl; return profittotal; } - 修正数组定义
将未指定容量的fraction数组改为固定容量数组:float fraction[4]; - 修正单位收益计算逻辑
计算时将操作数转为浮点类型,避免整数截断:fraction[i] = static_cast<float>(profit[i]) / weight[i]; - 修正交换逻辑
为每个数组的交换使用独立临时变量,避免值错乱:if(fraction[i] < fraction[j]) { // 交换单位收益 float tempFrac = fraction[i]; fraction[i] = fraction[j]; fraction[j] = tempFrac; // 交换对应收益 int tempProfit = profit[i]; profit[i] = profit[j]; profit[j] = tempProfit; // 交换对应重量 int tempWeight = weight[i]; weight[i] = weight[j]; weight[j] = tempWeight; } - 修正物品装入的循环逻辑
去掉错误的循环嵌套,按排序后的顺序依次装入物品,动态跟踪已装入重量与总收益:float currentWeight = 0; float maxProfit = 0; for(i=0; i<4; i++) { if(currentWeight + weight[i] <= total) { temp[i] = 1.0f; currentWeight += weight[i]; maxProfit += profit[i]; } else { float remainWeight = total - currentWeight; temp[i] = remainWeight / weight[i]; maxProfit += profit[i] * temp[i]; break; } } cout << "Maximum achievable profit: " << maxProfit << endl;
内容的提问来源于stack exchange,提问作者Rahul Goswami
相关产品推荐
相关产品推荐

