[USACO12MAR]Cows in a Skyscraper G - 洛谷https://www.luogu.com.cn/problem/P3052继续学习我的状压dp,一道状压入门好题还是继续考虑状态和该状态下的量,我发现状压的很多题都要记录该状态的量。
这道题就是记录目前牛的坐上电梯的状态,然后记录该状态下最后一班电梯的剩余,然后开始考虑其他牛牛能不能进来,或者是去下一班电梯。
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <cstring>
#include <set>
#include <cmath>
#include <map>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
const int MN = 65005;
const int MAXN = 1e6 + 10;
const int INF = 0x3f3f3f3f;
#define IOS ios::sync_with_stdio(false)
#define lowbit(x) ((x)&(-x))
using P = pair<int, int>;
int n, W;
int a[MAXN];
int f[MAXN];
int g[MAXN];
int main() {
int n, W;
scanf("%d %d", &n, &W);
for (int i = 1; i <= n; i++) {
scanf("%d", a + i);
}
memset(f, 0x3f, sizeof(f));
f[0] = 1;
g[0] = W;
for (int i = 0; i < (1 << n); i++) {
for (int j = 1; j <= n; j++) {
if (i & 1 << (j - 1))
continue;
if (g[i] >= a[j] && f[i | (1 << (j - 1))] >= f[i]) {
f[i | (1 << (j - 1))] = f[i];
if (f[i | (1 << (j - 1))] == f[i])
g[i | (1 << (j - 1))] = max(g[i | 1 << (j - 1)], g[i] - a[j]);
else
g[i | (1 << (j - 1))] = g[i] - a[j];
} else if (g[i] < a[j] && f[i | (1 << (j - 1))] >= f[i] + 1) {
f[i | (1 << (j - 1))] = f[i] + 1;
if (f[i | (1 << (j - 1))] == f[i] + 1)
g[i | (1 << (j - 1))] = max(g[i | (1 << (j - 1))], W - a[j]);
else
g[i | (1 << (j - 1))] = W - a[j];
}
}
}
printf("%d\n", f[(1 << n) - 1]);
return 0;
}