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
import java.util.Arrays;
import java.util.Scanner;

public class pak {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt(), m = sc.nextInt();
        int[] items = new int[n];
        int[] bags = new int[m];
        int bagsTakenIdx = m;

        for (int i = 0; i < n; ++i) {
            items[i] = sc.nextInt();
        }
        for (int i = 0; i < m; ++i) {
            bags[i] = sc.nextInt();
        }

        Arrays.sort(items);
        Arrays.sort(bags);
        int[] bagsCapacity = Arrays.copyOfRange(bags, 0, m);

        for (int i = n - 1; i >= 0; --i) {
            int item = items[i];
            boolean canPack = false;
            for (int j = m - 1; j >= 0; --j) {
                if (bagsCapacity[j] - item >= 0) {
                    bagsCapacity[j] -= item;
                    canPack = true;
                    if (j < bagsTakenIdx) bagsTakenIdx = j;
                    break;
                }
            }
            if (!canPack) {
                System.out.println("NIE");
                return;
            }
        }

        int result = m - bagsTakenIdx;

        // Let's try some quick optimization
        boolean optimizing = true;
        int shift = 1, limit = 0;
        while (optimizing && (++limit < 8)) {
            bagsCapacity = Arrays.copyOfRange(bags, 0, m);
            for (int i = n - 1; i >= 0; --i) {
                int item = items[i];
                boolean canPack = false;
                for (int j = bagsTakenIdx + shift; j < m; ++j) {
                    if (bagsCapacity[j] - item >= 0) {
                        bagsCapacity[j] -= item;
                        canPack = true;
                        break;
                    }
                }
                if (!canPack) {
                    optimizing = false;
                    break;
                }
            }
            if (optimizing) {
                shift += 1;
                result -= 1;
            }
        }
        System.out.println(result);
    }
}