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
#include <cstdio>
#include <algorithm>
#include <functional>

class Pak
{
    int m_num_items;
    int m_num_bins;
    int *m_item_weights;
    int *m_bin_sizes;

    int m_minimum;
    int *m_walk_bins;
    bool *m_walk_items;

    void walk(int used_items, int used_bins)
    {
        if (m_minimum != -1 && used_bins >= m_minimum)
            return;

        if (used_items == m_num_items)
        {
            if (m_minimum == -1)
                m_minimum = used_bins;
            else
                m_minimum = std::min(m_minimum, used_bins);

            return;
        }

        for (int i = 0; i < m_num_items; ++i)
        {
            if (m_walk_items[i])
                continue;

            m_walk_items[i] = true;

            for (int j = 0; j < m_num_bins; ++j)
            {
                if (m_walk_bins[j] + m_item_weights[i] <= m_bin_sizes[j])
                {
                    int new_bin = (m_walk_bins[j] == 0);

                    m_walk_bins[j] += m_item_weights[i];
                    walk(used_items + 1, used_bins + new_bin);
                    m_walk_bins[j] -= m_item_weights[i];
                }
            }

            m_walk_items[i] = false;
        }
    }

public:
    int solve(int num_items, int num_bins, int *item_weights, int *bin_sizes)
    {
        m_num_items = num_items;
        m_num_bins = num_bins;
        m_item_weights = item_weights;
        m_bin_sizes = bin_sizes;

        std::sort(item_weights, item_weights + num_items, std::greater<int>());
        std::sort(bin_sizes, bin_sizes + num_bins, std::greater<int>());

        m_walk_bins = new int [num_bins];
        m_walk_items = new bool [num_items];

        for (int i = 0; i < num_bins; ++i)
            m_walk_bins[i] = 0;

        for (int i = 0; i < num_items; ++i)
            m_walk_items[i] = 0;

        m_minimum = -1;

        walk(0, 0);

        return m_minimum;
    }
};

int main()
{
    Pak pak;

    int num_items, num_bins;
    scanf("%i%i", &num_items, &num_bins);

    int *item_sizes = new int[num_items];
    int *bin_sizes = new int[num_bins];

    for (int i = 0; i < num_items; ++i)
        scanf("%i", item_sizes + i);

    for (int i = 0; i < num_bins; ++i)
        scanf("%i", bin_sizes + i);

    int result = pak.solve(num_items, num_bins, item_sizes, bin_sizes);

    if (result != -1)
        printf("%i\n", result);
    else
        printf("NIE\n");

    return 0;
}