新编背包问题递归解法和非递归解法.docVIP

  • 3
  • 0
  • 约1.67万字
  • 约 30页
  • 2018-06-27 发布于福建
  • 举报

新编背包问题递归解法和非递归解法.doc

新编背包问题递归解法和非递归解法

背包问题:有不同价值、不同重量的物品n件,求从这n件物品中选取一部分物品的选择方案,使选中物品的总重量不超过指定的限制重量,但选中物品的价值之和为最大。 [算法] try(物品i,当前选择已达到的重量之和tw,本方案可能达到的总价值tv) {//考虑物品i包含在当前方案中的可能性 ?if (包含物品i是可接受的) ?{ ??将物品i包含在当前的方案中: ??if (in-1) ??{ ???try(i+1, tw+物品i的重量,tv); ??} ??else?//又一个完整的方案,因它比前面的方案好,以它为最佳方案 ??{ ???以当前方案作为临时最佳方案保存; ??} ??恢复物品i不包含状态; ?} ?//考虑物品i不包含在当前方案中的可能性 ?if (不包含物品i是可考虑的) ?{ ??if (in-1) ??{ ???try(i+1, tw, tv-物品i的价值); ??} ??else?//又一个完整的方案,因它比前面的方案好,以它为最佳方案 ??{ ???以当前方案作为临时最佳方案保存; ??} ?} } 递归解法:------------------------------------------------------------------------------ #include stdio.h #include stdlib.h #define N 100 double limitW,???//限制得总重量 ??totV(0),??//全部物品的总价值 ??maxv; int option[N],???//解的选择情况 ?cop[N];????//当前解的选择情况 struct? { ?double weight; ?double value; }a[N]; int n;?????//物品总数 void find(int i, double tw, double tv) { ?int k; ?//考虑物品i包含在当前方案中的可能性 ?if (tw + a[i].weight = limitW)??//包含物品i是可接受的 ?{ ??cop[i] = 1;??????//将物品i包含在方案中 ??if (in-1) ??{ ???find(i+1, tw+a[i].weight, tv); ??} ??else ??{ ???for (k=0; kn; k++) ???{ ????option[k] = cop[k]; ???} ???maxv = tv; ??} ??cop[i] = 0;??????//恢复物品i的不包含状态 ?} //考虑物品i不包含在当前方案中的可能性 ?if (tv - a[i].value maxv) ?{ ??if (in-1) ??{ ???find(i+1, tw, tv-a[i].value); ??} ??else ??{ ???for (k=0; kn; k++) ???{ ????option[k] = cop[k]; ???} ???maxv = tv - a[i].value; ??} ?} } void main() { ?int k; ?double w, v; ?printf(输入物品种数\n); ?scanf(%d, n); ?printf(输入各物品的重量和价值\n); for (totV = 0.0, k=0; kn; k++) ?{ ??scanf(%lf%lf, w, v); ??a[k].weight = w; ??a[k].value = v; ??totV += v; ?} printf(输入限制重量:\n); ?scanf(%lf, limitW); ?maxv = 0.0; ? ?for (k=0; kn; k++) ?{ ??cop[k] = 0; ?} find(0, 0.0, totV); for (k=0; kn; k++) ?{ ??if (option[k]) ??{ ???printf(%4d, k+1); ??} ?} ?printf(\n总价值为%.2f\n, maxv); system(pause); } 非递归解法:----------------------------------------------------------------- 用同样的思想,但程序非递归 #include stdio.h #include stdlib.h #define N 100 double limitW; int cop[N];? //临时最佳候选解的物品选择方案,当opts[i]为1,物品i在解中 struct ele{ ?double weight; ?double value; }a[N]; int k,n; st

文档评论(0)

1亿VIP精品文档

相关文档