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
//Przemysław Jakub Kozłowski
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <functional>
using namespace std;
const int N = 24, M = 103;

int n,m;
uint prz[N+7], ple[M+7];
uint wyn[(1<<N)+7];

int main()
{
    scanf("%d%d", &n, &m);
    for(int i = 1;i <= n;i++)
        scanf("%u", &prz[i]);
    for(int i = 1;i <= m;i++)
        scanf("%u", &ple[i]);
    sort(prz+1,prz+n+1, greater<uint>());
    sort(ple+1,ple+m+1, greater<uint>());
    if(m > n)
    {
        m = n;
        ple[m+1] = 0;
    }

    wyn[0] = 0;
    for(uint mask = 1;mask < (1<<n);mask++)
    {
        uint twyn = (((uint)m+1U)<<27);
        for(int nr = 1;nr <= n;nr++)
            if(mask&(1U<<(nr-1)))
            {
                uint swyn = wyn[mask&(~(1U<<(nr-1U)))];
                if(swyn+prz[nr] >= twyn) continue;
                uint w;
                if((swyn&((1U<<27)-1U))+prz[nr] <= ple[(swyn>>27)]) w = swyn;
                else if(prz[nr] <= ple[(swyn>>27)+1]) w = (((swyn>>27)+1U)<<27);
                else continue;
                w += prz[nr];
                if(w < twyn) twyn = w;
            }
        wyn[mask] = twyn;
    }

    int konwyn = (int)(wyn[(1U<<n)-1U]>>27);
    if(konwyn <= m) printf("%d\n", konwyn);
    else printf("NIE\n");
    return 0;
}