#include <stdio.h>
#include <stdlib.h>
// length of the weights array
int arraySize = 0;
//maximum value that can be obtained
int maxSumValues = 0;
//maximum weight that can be obtained
int sumWeightLabel = 0;
//The array of values
int *values;
//The array of weights
int *weights;
//Whether to select the flag array of weight
int *locations;
// When the maximum value is a certain value is selected, 1 is selected, 0 is not selected
int *maxSumValuesLocations;
/**
*
* Compare the maximum value and save the position of the maximum value
*/
int getMaxSumValues(){
int weightSum = 0;
int maxSumValues_ = 0;
for(int i = 0; i < arraySize; i++){
if(locations[i]){
weightSum += weights[i];
maxSumValues_ += values[i];
}
}
if(maxSumValues_ > maxSumValues && weightSum <= sumWeightLabel){
maxSumValues = maxSumValues_;
for(int i = 0; i < arraySize; i++){
maxSumValuesLocations[i] = locations[i];
}
}
}
/**
* print array and the maximum sum of values
*/
void printArray(){
printf("The weights: ");
for(int i = 0;i < arraySize; i++){
if(maxSumValuesLocations[i] == 1)
printf("%5d ",weights[i]);
}
printf("\n");
printf("The values: ");
for(int i = 0;i < arraySize; i++){
if(maxSumValuesLocations[i] == 1)
printf("%5d ",values[i]);
}
printf("\n");
printf("The max sum of values: %5d\n", maxSumValues);
}
/*
* permute weights
* Backtracking
*
*/
void permuteWeights(int index){
if(arraySize == index)
return ;
//nth item included
locations[index] = 1;
getMaxSumValues();
permuteWeights(index + 1);
//not included
locations[index] = 0;
getMaxSumValues();
permuteWeights(index + 1);
}
//Initialization data first
void initKnapsack1(){
//printf("Please input length of Array: ");
//scanf("%d",size);
arraySize = 3;
/*
* for(int i = 0; i < arraySize,i++)
* scanf("%d", values[i]);
*/
values = calloc(arraySize, sizeof(int));
weights = calloc(arraySize, sizeof(int));
values[0] = 60,values[1] = 100,values[2] = 120;
weights[0] = 10,weights[1] = 20,weights[2] = 30;
locations = calloc(arraySize, sizeof(int));
maxSumValuesLocations = calloc(arraySize, sizeof(int));
sumWeightLabel = 50;
maxSumValues = 0;
}
//Initialization data second
void initKnapsack2(){
arraySize = 4;
values = calloc(arraySize, sizeof(int));
weights = calloc(arraySize, sizeof(int));
values[0] = 40,values[1] = 100,values[2] = 50,values[3] = 60;
weights[0] = 20,weights[1] = 10,weights[2] = 40,weights[3] = 30;
locations = calloc(arraySize, sizeof(int));
maxSumValuesLocations = calloc(4, sizeof(int));
sumWeightLabel = 60;
maxSumValues = 0;
}
//Free cache
void freeKnapsack(){
free(values);
free(weights);
free(locations);
free(maxSumValuesLocations);
}
int main(){
initKnapsack1();
permuteWeights(0);
printArray();
freeKnapsack();
initKnapsack2();
permuteWeights(0);
printArray();
freeKnapsack();
return 0;
}