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
#define debug if(0)
// Grzegorz Guspiel
#include <bits/stdc++.h>
using namespace std;
 
#define REP(i,n) for(int i=0;i<int(n);++i)
#define SIZE(c) ((int)((c).size()))
#define FOREACH(i,x) for (__typeof((x).begin()) i=(x).begin(); i!=(x).end(); ++i)
#define ALL(v) (v).begin(), (v).end()
#define pb push_back
#define mp make_pair
#define st first
#define nd second

template<typename T> void maxE(T& a, const T& b) { a = max(a, b); }
template<typename T> void minE(T& a, const T& b) { a = min(a, b); }
typedef pair<int, int> PII;

const int MAXN = 24;
const int INF = 1000 * 1000 * 1000 + 100;

struct Data {
    int used, left;
    Data() {}
    Data(int used_, int left_): used(used_), left(left_) {}
};
bool operator<(const Data& a, const Data& b) {
    if (a.used == b.used) return a.left > b.left;
    else return a.used < b.used;
}
ostream& operator<<(ostream& out, const Data& d) {
    out << "D(u=" << d.used << ", l=" << d.left << ")";
    return out;
}

Data t[1 << MAXN];
int n, m;
vector<int> itemSizes;
vector<int> backpackSizes;

int solve() {
    t[0] = Data(0, 0); // ile backpackow uzywam, ile zousedalo w biezacym
    for (int s = 1; s < (1 << n); s++) {
        t[s] = Data(INF, INF);
        REP (i, n) if ((1 << i) & s) {
            int p = s & ~(1 << i);
            Data cur;
            if (itemSizes[i] > t[p].left) {
                if (t[p].used == m) {
                    continue;
                }
                cur = Data(t[p].used + 1, backpackSizes[t[p].used] - itemSizes[i]);
            } else {
                cur = Data(t[p].used, t[p].left - itemSizes[i]);
            }
            if (cur.left >= 0) {
                minE(t[s], cur);
            }
        }
        debug cout << "t[" << s << " = " << t[s] << endl;
    }
    return t[(1 << n) - 1].used;
}

int main() {
    ios_base::sync_with_stdio(0);
    cin >> n >> m;
    REP (i, n) {
        int a; cin >> a;
        itemSizes.pb(a);
    }
    REP (i, m) {
        int a; cin >> a;
        backpackSizes.pb(a);
    }
    sort(ALL(backpackSizes), greater<int>());

    int result = solve();
    if (result == INF) cout << "NIE" << endl;
    else cout << result << endl;
	return 0;
}