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
#include<iostream>
#include<vector>
#include<list>
#include<algorithm>


using namespace std;

void read(vector<int>& v) {
	for(int i=0; i< v.size(); i++) {
		cin >> v[i];
	}
}

bool desc(int a, int b) {
	return a > b;
}

void insert(list<int>& cs, int newC) {
	auto place = cs.begin();
	while(place != cs.end() && *place > newC) {
	       	place++;
	}

	cs.insert(place, newC);
}

bool tryPutIntoPack(list<int>& cs, int weight) {
	auto c = cs.begin();
	if(*c < weight) {
		return false;
	}

	while(c != cs.end() && *c >= weight) {
		c++;
	}

	c--;
	int ci = *c;
	if(ci >= weight) {
		cs.erase(c);
		if(ci - weight > 0) insert(cs, ci - weight);
		return true;
	}

	return false;
}


bool packWeights(list<int>& cs, vector<int>& weights) {
	for(int i=0; i < weights.size(); i++) {
		bool packed = tryPutIntoPack(cs, weights[i]);
		if(!packed) {
			return false;
		}
	}
	return true;
}

long accumulate(vector<int>& weights) {
	long sum = 0;
	for(int i=0; i < weights.size(); i++) {
		sum += weights[i];
	}
	return sum;
}


int howManyPacks(vector<int>& weights, vector<int>& packs) {

	if(weights[0] > packs[0]) {
		return -1;
	}

	long sumWs = accumulate(weights);

	int k = 0;
	long kSum = 0;
	for(int i=0; i < packs.size() && kSum < sumWs; i++) {
		kSum += packs[i];
		k = i;
	}
	if(kSum < sumWs) {
		return -1;
	}

	bool allPacked = false;
	while(!allPacked && k < packs.size()) {

		list<int> cs(packs.begin(), packs.begin() + k+1);

		allPacked = packWeights(cs, weights);
		k++;
	}

	if(allPacked)
		return k;
	return -1;
}


int main() {
	int n, m;
	cin >> n >> m;

	vector<int> weights(n);
	vector<int> packs(m);

	read(weights);
	read(packs);

	sort(weights.begin(), weights.end(), desc);
	sort(packs.begin(), packs.end(), desc);

	int packsCount = howManyPacks(weights, packs);
	cout << ((packsCount > -1) ? to_string(packsCount) : "NIE") << endl;

	return 0;
}