状压DP:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define R(a,b,c) for(register int a = (b); a <= (c); ++ a)
#define nR(a,b,c) for(register int a = (b); a >= (c); -- a)
#define Max(a,b) ((a) > (b) ? (a) : (b))
#define Min(a,b) ((a) < (b) ? (a) : (b))
#define Fill(a,b) memset(a, b, sizeof(a))
#define Abs(a) ((a) < 0 ? -(a) : (a))
#define Swap(a,b) a^=b^=a^=b
#define ll long long
#define ON_DEBUG
#ifdef ON_DEBUG
#define D_e_Line printf("\n\n----------\n\n")
#define D_e(x) cout << #x << " = " << x << endl
#define Pause() system("pause")
#define FileOpen() freopen("in.txt","r",stdin);
#else
#define D_e_Line ;
#define D_e(x) ;
#define Pause() ;
#define FileOpen() ;
#endif
struct ios{
template<typename ATP>ios& operator >> (ATP &x){
x = 0; int f = 1; char c;
for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-') f = -1;
while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
x*= f;
return *this;
}
}io;
using namespace std;
int a[23], f[(1 << 18) + 7], g[(1 << 18) + 7];
int main(){
int n, V;
io >> n >> V;
R(i,1,n){
io >> a[i];
}
int M = (1 << n) - 1;
R(s,1,M) f[s] = 2147483647;
f[0] = 1;
g[0] = V;
R(s,0,M){
R(i,1,n){
if(s & (1 << (i - 1))) continue;
if(g[s] >= a[i] && f[s | (1 << (i - 1))] >= f[s]){
f[s | (1 << (i - 1))] = f[s];
g[s | (1 << (i - 1))] = Max(g[s | (1 << (i - 1))], g[s] - a[i]);
}
else if(g[s] < a[i] && f[s | (1 << (i - 1))] >= f[s] + 1){
f[s | (1 << (i - 1))] = f[s] + 1;
g[s | (1 << (i - 1))] = Max(g[s | (1 << (i - 1))], V - a[i]);
}
}
}
printf("%d", f[M]);
return 0;
}
IDA*:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define R(a,b,c) for(register int a = (b); a <= (c); ++ a)
#define nR(a,b,c) for(register int a = (b); a >= (c); -- a)
#define Max(a,b) ((a) > (b) ? (a) : (b))
#define Min(a,b) ((a) < (b) ? (a) : (b))
#define Fill(a,b) memset(a, b, sizeof(a))
#define Abs(a) ((a) < 0 ? -(a) : (a))
#define Swap(a,b) a^=b^=a^=b
#define ll long long
#define ON_DEBUG
#ifdef ON_DEBUG
#define D_e_Line printf("\n\n----------\n\n")
#define D_e(x) cout << #x << " = " << x << endl
#define Pause() system("pause")
#define FileOpen() freopen("in.txt","r",stdin);
#else
#define D_e_Line ;
#define D_e(x) ;
#define Pause() ;
#define FileOpen() ;
#endif
struct ios{
template<typename ATP>ios& operator >> (ATP &x){
x = 0; int f = 1; char c;
for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-') f = -1;
while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
x*= f;
return *this;
}
}io;
using namespace std;
int n, V;
int a[19], w[19];
inline bool DFS(int x, int dep){
int minn = Min(x, dep);
R(i,1,minn){
if(w[i] + a[x] <= V){
w[i] += a[x];
if(x == n) return 1;
if(DFS(x + 1, dep)) return 1;
w[i] -= a[x];
}
}
return 0;
}
int main(){
io >> n >> V;
R(i,1,n){
io >> a[i];
}
R(i,1,n){
Fill(w, 0);
if(DFS(1, i)){
printf("%d", i);
return 0;
}
}
return 0;
}