[Cpp]
# Include <stdio. h>
# Include <stdlib. h>
# Define Max size 100
Int n; // number of containers
Int c; // container capacity
Int w [MAXSIZE]; // container weight
Int cw; // current weight
Int bestw; // optimal weight
Void input (); // input
Void init (); // Initialization
Void backtrack (int); // backtracking
Int main (void)
{
While (1)
{
Input ();
Init ();
Backtrack (0 );
Printf ("% d \ n", bestw );
}
Return 0;
}
Void input ()
{
Int I = 0;
Printf ("please enter n :");
Scanf ("% d", & n );
Printf ("please enter c :");
Scanf ("% d", & c );
For (I = 0; I <n; ++ I)
{
Scanf ("% d", & w [I]);
}
}
Void init ()
{
Cw = 0;
Bestw = 0;
}
Void backtrack (int t)
{
Int I = 0;
If (t> = n)
{
If (cw> bestw)
{
Bestw = cw;
}
}
Else
{
// Enter the left subtree
Cw + = w [t];
If (cw <= c)
{
Backtrack (t + 1 );
}
// Enter the right subtree
Cw-= w [t];
Backtrack (t + 1 );
}
}
Author: fcwr_zhuxin_fcwr