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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include<iostream>
#include<cstdio>
#include<string>
#include<cmath>
#include<vector>
#include<map>
#include<set>
#include<algorithm>
#include<utility>
using namespace std;

#define FOR(I,A,B) for(int I=(A);I<=(B);I++)
#define REP(I,N) for(int I=0;I<(N);I++)
#define ALL(X) (X).begin(),(X).end()
#define PB push_back
#define MP make_pair
#define f first
#define s second

typedef vector<int> VI;
typedef pair<int,int> PII;
typedef long long ll;
typedef vector<string> VS;

const int MAX = 105;
const int MAGIC =  50000;

ll memo[1<<24];
int n,m,res,counter;
int items[MAX],knapsacks[MAX],K[MAX];
bool found;

int first_fit(){
	int cur = knapsacks[0];
	int idx = 0;

	REP(i,n){
		if(cur >= items[i]){
			cur -= items[i];
		}
		else{
			++idx;
			cur = knapsacks[idx];
			if(idx == res || cur < items[i]) return m;
			cur -= items[i];
		}
	}

	found = true;
	return idx + 1;
}

int brut(){
	sort(items,items+n);

	do{
		res = min(res,first_fit());
	}
	while(next_permutation(items,items+n));

	return res;
}

void go(int a, int bin_capacity, ll items_size, ll bins_capacity, int mask){
	if(items_size > bins_capacity) return;
	if(items_size == 0){
		found = true;
		res = min(res,a+1);
		return;
	}

	if(memo[mask]>bins_capacity) return;
	memo[mask] = bins_capacity;

	REP(i,n)
		if(items[i] != -1){
			int w = items[i];
			if(bin_capacity >= w){
				items[i] = -1;
				go(a,bin_capacity-w,items_size-w,bins_capacity-w,mask|(1<<i));
				items[i] = w;
			}
			else{
				go(a+1,knapsacks[a+1],items_size,bins_capacity-bin_capacity,mask);
			}
		}
}

int main(){
	srand(time(0));
	ios_base::sync_with_stdio(0);

	cin >> n >> m;

	ll items_sum = 0;

	REP(i,n) cin >> items[i];
	REP(i,m) cin >> knapsacks[i];

	sort(knapsacks,knapsacks+m,[](int a, int b){ return a>b; });

	m = min(m,n);

	res = m;
	found = false;

	int a = m;

	ll items_size = 0;
	REP(i,n) items_size += items[i];

	ll bins_capacity = 0;

	if(n <= 10){
		res = brut();
		goto output;
	}

	REP(i,MAGIC*n){
		random_shuffle(items,items+n);
		res = min(res,first_fit());
	}

	if(found) a = res;
	REP(i,a) bins_capacity += knapsacks[i];

	go(0,knapsacks[0],items_size,bins_capacity,0);

	output:
	!found ? cout << "NIE\n" : cout << res << endl;

	return 0;
}