# Dynamic Planning 01 backpack C Algorithm

Source: Internet
Author: User

# Include <stdio. h>
# Include <stdlib. h>

# Define N 5
# Define C 10

Void knapsack (int w [N], int V [N], int M [] [c]);
Void traceback (int m [] [c], int W [N], int X [N]);

Void knapsack (int w [N], int V [N], int M [] [c])
{
Int n = N;
Int C = C;

Int I, J;
For (I = 0; I <C; I ++ ){
If (I <W [0]) {
M [0] [I] = 0;
}
Else {
M [0] [I] = V [0];
}

}

For (I = 1; I <n-1; I ++ ){
For (j = 0; j <C; j ++ ){
If (j> W [I]) {
M [I] [J] = max (M [I-1] [J], V [I] + M [I-1] [J-W [I]);
}
Else {
M [I] [J] = m [I-1] [J];
}
}
}
M [n-1] [C-1] = m [N-2] [C-1];
If (C> W [n-1]) {
M [n-1] [C-1] = max (M [N-2] [C-1], V [n-1] + M [N-2] [C-W [n-1]);
}

}

Void traceback (int m [] [c], int W [N], int X [N])
{
Int J = C;
Int I;
For (I = N-1; I> = 1; I --){
If (M [I] [J-1] = m [I-1] [J-1]) {
X [I] = 0;
}
Else {
J = J-W [I];
X [I] = 1;

}
}
If (j> 0 ){
X [0] = 1;
}
Else {
X [0] = 0;
}

}

Int main ()
{
Int W [N] = {2, 2, 6, 5, 4 };
Int V [N] = {6, 3, 5, 4, 6 };
Int X [N] = {0 };
Int M [N] [c] = {0 }};
Int I;
Knapsack (W, V, M );
Traceback (M, w, x );

For (I = 0; I <n; I ++)
{
Printf ("% d", X [I]);
}
Printf ("/N ");

System ("pause ");
Return 0;
}

Related Keywords:
Related Article

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.