[Cpp]/*
Upper Bound Function
*/
# Include <stdio. h>
# Include <stdlib. h>
# Define Max size 100
// Global variable
Int n; // number of containers
Int c; // capacity
Int r; // remaining capacity
Int w [MAXSIZE]; // container weight
Int cw; // current weight
Int bestw; // optimal weight
// Input Function
Void input ();
// Initialize the Function
Void init ();
// Backtracking
Void backtrack (int );
Int main (void)
{
While (1)
{
Input ();
Init ();
Backtrack (0 );
Printf ("% d \ n", bestw );
}
Return 0;
}
// Input Function
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]);
}
}
// Initialize the Function
Void init ()
{
Int I = 0;
Cw = 0;
Bestw = 0;
For (I = 0; I <n; ++ I)
{
R + = w [I];
}
}
// Backtracking
Void backtrack (int t)
{
If (t> = n)
{
If (cw> bestw)
{
Bestw = cw;
}
}
Else
{
// Left subtree
R-= w [t];
Cw + = w [t];
If (cw <= c)
{
Backtrack (t + 1 );
}
// Right subtree
Cw-= w [t];
If (cw + r> bestw)
{
Backtrack (t + 1 );
}
R + = w [t];
}
}
Author: fcwr_zhuxin_fcwr