Blue Bridge Cup ALGO-21 training algorithm packing problem

Packing training algorithm problem  

Time limit: 1.0s Memory Limit: 256.0MB

 

Problem Description
  has a box capacity V (a positive integer, 0 <= V <= 20000 ), while there are n items (0 <n <= 30) , each item has a volume (positive integer).
  The remaining space requirements of n items, take any one of a number into the box so that the box is minimized.

 

The input format
  of the first conduct an integer representing the capacity of the box;
  second line an integer, indicates that there are n items;
  next n rows, each row represents a respective integer volume of the n items.

 

Output formats
  an integer representing the remaining space of the box.

 

Sample input
  24
  . 6
  . 8
  . 3
  12 is
  . 7
  . 9
  . 7

 

Sample output
0


Analysis: set f(i, v)as to the capacity of vthe box, first to the processing ispace after the items have been occupied. There recurrence relations:

f(i, v) = \begin{cases} \max \{ f(i-1, v), f(i-1, v-v_i) + v_i \} & \text{ if } v \ge v_i \\ f(i-1, v) & \text{ if } v < v_i \\ 0 & \text{ if } i = 0, v \ge 0 \end{cases}

 

#include <stdio.h>

int max(int a, int b)
{
    return a > b ? a : b;
}

int main()
{
    int V, n;
    int volume[35] = { 0 };
    int f[35][20005] = { 0 };

    scanf("%d", &V);
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i)
        scanf("%d", &volume[i]);

    for (int i = 1; i <= n; ++i)
    {
        for (int v = 0; v < volume[i]; ++v)
            f[i][v] = f[i-1][v];
        for (int v = volume[i]; v <= V; ++v)
            f[i][v] = max(f[i-1][v], f[i-1][v-volume[i]] + volume[i]);
    }
    printf("%d", V - f[n][V]);

    return 0;
}

 

Published 221 original articles · won praise 40 · views 40000 +

Guess you like

Origin blog.csdn.net/liulizhi1996/article/details/104005606