#define INF 0xf0f0f0f0//-∞
int sumValue = 0;
void operationInKnapsack( int value, int m )
{
int itemsInKnapsack[ m ]; // Record the value of M items with high value at present
int count = 0; // Used for counting the first m itmes of array
int flag= 0; // Used for counting the items after m times
for( int i = 0; i < m; i++ )//Initialization
itemsInKnapsack[ i ] = INF;
//The first m items,directly put into the array
if((count < m) && itemsInKnapsack[ count ] == INF)
{
itemsInKnapsack[ count++ ] = value;
sumValue += value;
}
//Full Knapsack, if there are higher valuable items coming in, remove the smaller ones
else
{
int min = itemsInKnapsack[ 0 ];
for( int i = 1; i < m; i++ ) //Find the minimum valuable items
{
if( min > itemsInKnapsack[ i ])
{
min = itemsInKnapsack[ i ]; //Record value
flag = i; //Record array subscript
}
}
sumValue -= min; //delete
itemsInKnapsack[ flag ] = value; // put into more valuable items
sumValue += itemsInKnapsack[ flag ]; //modify the sum value
}
}
3. Knapsack Problem With m Items At Most
最新推荐文章于 2024-04-15 16:01:18 发布