Recursive and non-Recursive Algorithms for knapsack problems

Source: Internet
Author: User

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;
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.