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 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
|
#include <iostream>
#include <string>
#include <sstream>
int parse_input(int &num_items, int &pouch_size);
int calculate(int &num_items, int &pouch_size, int values[], int weights[]);
int main()
{
int num_items;
int pouch_size;
int my_array[2] = { 0 };
*my_array = parse_input(num_items, pouch_size);
calculate(num_items, pouch_size, &my_array[0], &my_array[1]);
return 0;
}
int calculate(int &num_items, int &pouch_size, int values[], int weights[])
{
int **M = new int *[((num_items + 1)*(pouch_size + 1))];
int **B = new int *[((num_items + 1)*(pouch_size + 1))];
for (int i = 1; i < num_items; i++)
{
for (int j = 0; j < pouch_size; j++)
{
if (weights[i] <= j)
{
if (M[i-1][j-weights[i]] + values[i] > M[i-1][j])
{
M[i][j] = M[i-1][j-weights[i]] + values[i];
B[i][j] = i;
}
else
{
M[i][j] = M[i-1][j];
B[i][j] = 0;
}
}
else
{
B[i][j] = M[i-1][j];
B[i][j] = 0;
}
}
}
int r = num_items;
int max_value;
int s = pouch_size;
int *output = new int(num_items + 1);
int out_index = 1;
while (r > 0 && s > 0)
{
if (B[r][s] == 0)
{
r--;
}
else
{
output[out_index] = B[r][s];
out_index++;
s = s - weights[r];
r--;
}
}
max_value = M[num_items][pouch_size];
delete[] M;
delete[] B;
return max_value;
}
int parse_input(int &num_items, int &pouch_size)
{
std::string x;
std::string y;
std::getline(std::cin, x);
std::getline(std::cin, y);
num_items = std::stoi(x);
pouch_size= std::stoi(y);
std::cout << num_items << ' ' << pouch_size << std::endl;
int *values = new int((num_items + 1) * (pouch_size + 1));
int *weights = new int((num_items + 1) * (pouch_size + 1));
int i = 1;
int j = 1;
for (std::string line; std::getline(std::cin, line); )
{
std::stringstream info(line);
std::string A[100] = { NULL };
for (std::string key; std::getline(info, key, ','); )
{
A[i] = key;
i++;
}
weights[j] = std::stoi(A[1]);
values[j] = std::stoi(A[2]);
j++;
}
std::cout << values << std::endl;
int *new_array = new int[2];
new_array[0] = *weights;
new_array[1] = *values;
values = nullptr;
weights = nullptr;
return *new_array;
}
|