bzoj3717 [PA2014]Pakowanie 贪心+状压DP

题目传送门

https://lydsy.com/JudgeOnline/problem.php?id=3717

题解

这道题大概也就只能算常规的状压 DP 吧,但是这个状态和转移的设计还是不是很好想。

首先很显然,要优先把物品往大的包里面装,直到装不了别人再去装下一个。

可以考虑贪心的策略,如果这个背包还能塞下的话,那么一定要去塞,这样至少是不会差的。

所以令 (dp[S]) 表示要装下 (S) 中的东西需要多少背包,(f[S]) 表示如果要达到 (dp[S]) 的结果,那么最后一个背包最多还有多少剩余的空间。

最后 (dp[Fullset]) 就是答案。


时间复杂度 (O(n2^n)),但是时间限制很充足。

#include<bits/stdc++.h>

#define fec(i, x, y) (int i = head[x], y = g[i].to; i; i = g[i].ne, y = g[i].to)
#define dbg(...) fprintf(stderr, __VA_ARGS__)
#define File(x) freopen(#x".in", "r", stdin), freopen(#x".out", "w", stdout)
#define fi first
#define se second
#define pb push_back

template<typename A, typename B> inline char smax(A &a, const B &b) {return a < b ? a = b, 1 : 0;}
template<typename A, typename B> inline char smin(A &a, const B &b) {return b < a ? a = b, 1 : 0;}

typedef long long ll; typedef unsigned long long ull; typedef std::pair<int, int> pii;

template<typename I> inline void read(I &x) {
	int f = 0, c;
	while (!isdigit(c = getchar())) c == '-' ? f = 1 : 0;
	x = c & 15;
	while (isdigit(c = getchar())) x = (x << 1) + (x << 3) + (c & 15);
	f ? x = -x : 0;
}

const int N = 24 + 7;
const int M = 100 + 7;
const int NP = (1 << 24) + 7;
const int INF = 0x3f3f3f3f;

int n, m, S;
int a[N], c[M];
int dp[NP], f[NP];

inline void work() {
	std::sort(c + 1, c + m + 1, std::greater<int>());
	S = (1 << n) - 1;
	memset(dp, 0x3f, sizeof(dp));
	dp[0] = 0;
	for (int s = 0; s <= S; ++s) {
		if (dp[s] == INF) continue;
		for (int i = 1; i <= n; ++i) if (!((s >> (i - 1)) & 1)) {
			int ss = s | (1 << (i - 1));
			if (f[s] < a[i]) {
				if (c[dp[s] + 1] >= a[i])
					if (smin(dp[ss], dp[s] + 1)) f[ss] = c[dp[ss]] - a[i];
					else if (dp[ss] == dp[s] + 1) smax(f[ss], c[dp[ss]] - a[i]);
			}
			else {
				if (smin(dp[ss], dp[s])) f[ss] = f[s] - a[i];
				else if (dp[ss] == dp[s]) smax(f[ss], f[s] - a[i]);
			}
		}
	}
	if (dp[S] != INF) printf("%d
", dp[S]);
	else puts("NIE");
}

inline void init() {
	read(n), read(m);
	for (int i = 1; i <= n; ++i) read(a[i]);
	for (int i = 1; i <= m; ++i) read(c[i]);
}

int main() {
#ifdef hzhkk
	freopen("hkk.in", "r", stdin);
#endif
	init();
	work();
	fclose(stdin), fclose(stdout);
	return 0;
}
原文地址:https://www.cnblogs.com/hankeke/p/bzoj3717.html