尝试每只猫的所有放法:放在已有的可以放下的车子里或放在新车子
#include <iostream>
#include <algorithm>
using namespace std;
int N, W, cat[18], res, car[18] = {0};
void judge(int ct, int cr) {
//剪枝
if(cr > res) return;
//所有猫都放下了
if(ct == N) {
res = cr;
return;
}
//找现有的车能不能放下
for(int i = 0; i < cr; i++) {
if(car[i] + cat[ct] <= W) {
car[i] += cat[ct];
judge(ct + 1, cr);
car[i] -= cat[ct];
}
}
//放新的车里
car[cr] = cat[ct];
judge(ct + 1, cr + 1);
car[cr] = 0;
}
int main(){
cin >> N >> W;
res = N;
for(int i = 0; i < N; i++) cin >> cat[i];
sort(cat, cat + N);
judge(0, 1);
cout << res;
return 0;
}