The basic description of the backpack problem is: there is a backpack, the total weight of the items that can be stored is s, there are n items, their weight is W1, W2 ,..., wn. if you want to select several items from N items, the total weight of the selected item can be placed in the backpack, that is, the total weight of the selected item is equal to S.
Procedure 1: Recursive Algorithm
# Include <iostream>
# Include <stdlib. h>
Using namespace STD;
Const int n = 7;
Const int S = 20;
Int W [n + 1] = {0, 1, 4, 3, 4, 5, 2, 7 };
Int knap (int s, int N)
{
If (S = 0) return 1;
If (S <0 | (S> 0 & n <1) return 0;
If (knap (S-W [N], n-1 ))
{
Cout <W [N];
Return 1;
}
Return knap (S, n-1 );
}
Int main (INT argc, char * argv [])
{
If (knap (S, N) cout <Endl <"OK" <Endl;
Else cout <"no" <Endl;
System ("pause ");
Return 0;
}
Procedure 2: Non-Recursive Algorithms
# Include <iostream>
# Include <stdlib. h>
Using namespace STD;
Const int n = 7;
Const int S = 20;
Int W [n + 1] = {0, 1, 4, 3, 4, 5, 2, 7 };
Typedef struct {
Int S;
Int N;
Int job;
} Knaptp;
Int knap (int s, int N)
{
Knaptp stack [100], X;
Int top, K, rep;
X. S = s;
X. n = N;
X. Job = 0;
Top = 1;
Stack [Top] = X;
K = 0;
While (k = 0 & top> 0 ){
X = stack [Top];
Rep = 1;
While (! K & REP ){
If (X. S = 0) k = 1;
Else if (X. S <0 | X. n <= 0) rep = 0;
Else {
X. S = x. S-W [X. n --];
X. Job = 1;
Stack [++ top] = X;
}
}
If (! K ){
Rep = 1;
While (top> = 1 & REP ){
X = stack [top --];
If (X. Job = 1 ){
X. S + = W [X. n + 1];
X. Job = 2;
Stack [++ top] = X;
Rep = 0;
}
}
}
}
If (k ){
While (top> = 1 ){
X = stack [top --];
If (X. Job = 1) cout <W [X. n + 1];
}
}
Return K;
}
Int main (INT argc, char * argv [])
{
If (knap (S, N) cout <Endl <"OK" <Endl;
Else cout <"no" <Endl;
System ("pause ");
Return 0;
}