Based on the previous article, we can optimize the code from the space complexity, that is, to see if it can be done using a one-dimensional array.
According to the Code, we need to know that if we start to push f [V] in every main loop in the second loop, this ensures that f [v] f [v-c [I] saves the value of State f [I-1] [v-c [I.
The Code is as follows:
# Include <cstdio>
# Include <cstring>
Int sum_values [1005];
Int main ()
{
Int T;
Int N, V;
Int I, j;
While (scanf ("% d", & N, & V) & (N + V ))
{
Int weight [1001], value [1001];
For (I = 1; I <= N; I ++)
{
Scanf ("% d", & weight [I]);
Scanf ("% d", & value [I]);
}
Memset (sum_values, 0, sizeof (sum_values ));
For (I = 1; I <= N; I ++) // starts from the first fruit to the nth fruit.
For (j = V; j> = weight [I]; j --) // starting from the full state, and the capacity of the j-state should be larger than the size of the I-state.
If (sum_values [j-weight [I] + value [I]> sum_values [j]) // if, before the j state, that is, the J-1 State is placed into a fruit of class I, and the total value is greater than the value of the j state, select to put in the J-1 state
Sum_values [j] = sum_values [j-weight [I] + value [I];
Printf ("% d \ n", sum_values [V]);
}
Return 0;
}