Define an array , where is set to if it is possible to obtain a total weight of using the available items. Initially, we set mask[0] = 1.
Assume that the array mask has already been correctly filled for some set of items. Consider the next item with weight . Then we need to set mask[i] = 1 for all values i~(w \le i \le m) such that the condition mask[i - w] = 1 holds.
Example
Let us examine how the values of the cells in the array change as the items are processed. The item weights are shown on the left.
The maximum weight of is achieved by the subset \{2, 1, 1\}.
Algorithm implementation
We store the array as a bitmask; otherwise, the solution will not fit within the memory limit.
#define MAX 30000010
bitset<MAX> mask;Read the input data. Set mask[0] = 1.
scanf("%d %d",&m,&n);
mask.set(0);Consider processing the next item with weight . Traverse the array from right to left and set mask[j] = 1 for all values j~(w \le j \le m) such that mask[j - w] = 1.
for (i = 0; i < n; i++)
{
scanf("%d",&w);
for (j = m; j >= w; j--)
if (mask[j - w] == 1) mask.set(j);
}After all items have been processed, find the largest weight not exceeding that can be packed into the luggage and print it.
for (i = m;; i--)
if (mask[i] > 0) break;
printf("%d\n",i);