P10483 题解
感觉想到状压不难,为什么 TJ 里面没有呢。
思路
数据范围不允许暴力搜索,考虑状压 DP。
设
然后处理一个数组
枚举每个状态
转移时还需要判断这个状态
代码
#include<bits/stdc++.h>
using namespace std;
const int N = 18 + 2;
int c[N],s[(1 << N) - 1],dp[(1 << N) - 1];
char ch;
inline void read(int &x)
{
while((ch=getchar())<48||ch>57);
x=ch^48;
while((ch=getchar())<58&&ch>47)
x=(x<<1)+(x<<3)+(ch^48);
}
inline void write(const int &x)
{
if(x>9) write(x/10);
putchar(x%10+48);
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
int n,w;read(n),read(w);
for (int i = 1;i <= n;i++) read(c[i]);
int U = (1 << n) - 1;
memset(dp,0x3f,sizeof(dp));
dp[0] = 0;
for (int i = 1;i <= U;i++){
for (int j = 1;j <= n;j++){
if (i & (1 << j - 1) ) s[i] += c[j];
}
}
for (int i = 1;i <= U;i++){
for (int j = i;j;j = i &(j - 1) ){//枚举子集
if (s[j] > w) continue;
dp[i] = min(dp[i],dp[i - j] + 1);
}
}
cout << dp[U];
return 0;
}