1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
using namespace std;
struct Item {
string Name;
int Quantity;
int Weight;
int Value;
int taken = 0;
};
ifstream& operator>> (ifstream& lhs, Item& rhs) {
lhs >> rhs.Name;
lhs >> rhs.Quantity;
lhs >> rhs.Weight;
lhs >> rhs.Value;
return lhs;
}
int BknpSack(int maxPft, int carryWeight, int val[], int totalItems) {
Item items[10];
int** optTable = new int* [totalItems + 1];
int totalWeight = 0;
int row, col, previousBest, newItemInclude;
//setup item IndexTable
int* itemIndexTable = new int[totalItems + 1];
for (row = 1; row < totalItems; row++) {
optTable[row] = new int[totalWeight + 1];
for (col = 0; col < maxPft; col++) {
optTable[0][col] = 0;
if (col - items[itemIndexTable[row]].Weight >= 0) {
previousBest = optTable[row - 1][col];
newItemInclude = optTable[row - 1][col - items[itemIndexTable[row]].Weight] + items[itemIndexTable[row]].Value;
if (previousBest > newItemInclude) {
optTable[row][col] = previousBest;
}
else {
optTable[row][col] = newItemInclude;
}
}
else {
//cant conclude the cur item
optTable[row][col] = optTable[row - 1][col];//copy val from above
}
}
}
int currentRow = totalItems;
int currentCol = carryWeight;
while (currentRow > 0 && currentCol > 0) {
if (optTable[currentRow][currentCol] == optTable[currentRow - 1][currentCol]) {
currentRow--;
}
else {
currentCol -=
itemIndexTable[currentRow] = items[itemIndexTable[row]].taken++;
currentRow--;
}
}
printf("The optimized Value is: \n");
return items[itemIndexTable[row]].Quantity, items[itemIndexTable[row]].Name, items[itemIndexTable[row]].Value;
}
int main() {
Item items[10];
//read from file
ifstream infile("item.txt");
int carryWeight = 0;
infile >> carryWeight;
Item temp;
int itemCount = 0;
while (infile >> temp) {
//creating arr for data read from file
FILE* inFile;
int* arr;
int size = sizeof(arr) / sizeof(arr[0]);
int readVal;
fread(&size, sizeof(size), 1, inFile);
arr = new int[size];
for (int i = 0; i < size; i++) {
fread(&readVal, sizeof(readVal), 1, inFile);
arr[i] = readVal;
}
infile.close();
}
cout << BknpSack(0, 0, 0, size);
return 0;
}
|