0/1背包问题(递归与非递归)
递归算法:
// 背包问题-递归.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
int w[5] = {1, 4, 4, 5, 7};
int knap(int s, int n)
{
if(s == 0)
{
return(1);
}
else
{
if( s < 0 || (s > 0 && n < 1))
{
return(0);
}
else
if(knap(s - w[n - 1],n - 1) == 1)
{
printf("result: n = %d, w[%d] = %d \n", n , n - 1, w[n-1]);
return (1);
}
else
{
return(knap(s, n - 1));
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
knap(10, 5);
return 0;
}
非递归算法:
1 //
2 //背包问题:从n个物件(每个物件的体积为Wi, i=1, 2, …, n)中选取若干个恰好能够填满体积为T的背包。
3 //用栈实现,非递归解。要求解答出所有的方法!
4 //能写出算法就行,如果外加代码的话,定不胜感激!
5 #include <iostream>
6 using namespace std;
7
8 #define N 5
9 const int W[N] = {1,2,5,6,8}; // 若原W无序,则先对其排序
10 const int T = 13;
11
12 int stack[N];
13 int stackIdx;
14
15 void output()
16 {
17 int i;
18 for(i=0; i<stackIdx; i++)
19 {
20 cout<<W[stack[i]]<<" ";
21 }
22 cout<<endl;
23 }
24
25 void outstack()
26 {
27 int i;
28 cout<<"stack: ";
29 for(i=0; i<stackIdx; i++)
30 {
31 cout<<stack[i]<<" ";
32 }
33 cout<<endl;
34 }
35
36 void main()
37 {
38 int idx;
39 int sum;
40
41 idx = 0;
42 sum = 0;
43 stackIdx = 0;
44 while(stackIdx >= 0)
45 {
46 //outstack();
47
48 if(idx >= N)
49 {
50 -- stackIdx;
51 sum -= W[stack[stackIdx]];
52 -- stackIdx;
53 sum -= W[stack[stackIdx]];
54 idx = stack[stackIdx] + 1;
55 }
56 else
57 {
58 sum += W[idx];
59
60 if(sum == T)
61 {
62 stack[stackIdx++] = idx;
63 output();
64
65 -- stackIdx;
66 -- stackIdx;
67 sum -= W[idx];
68 sum -= W[stack[stackIdx]];
69 idx = stack[stackIdx] + 1;
70 }
71 else if(sum > T)
72 {
73 -- stackIdx;
74 sum -= W[idx];
75 sum -= W[stack[stackIdx]];
76 idx = stack[stackIdx] + 1;
77 }
78 else
79 {
80 stack[stackIdx++] = idx;
81 ++ idx;
82 }
83 }
84 }
85 system("pause");
86 }