hihoCoder 1044 : 状态压缩·一 状压dp

思路:状态压缩,dp(i, j)表示考虑前i个数且[i-m+1, i]的选择情况为j。如果要选择当前这个数并且,数位1的个数不超过q,则dp[i+1][nex] = max(dp[i+1][nex], dp[i][j] + w[i+1]),如果不选择dp[i+1][j>>1] = max(dp[i+1][j>>1], dp[i][j]);

AC代码

#include <cstdio>
#include <cmath>
#include <cctype>
#include <algorithm>
#include <cstring>
#include <utility>
#include <string>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
#pragma comment(linker, "/STACK:1024000000,1024000000")
#define eps 1e-10
#define inf 0x3f3f3f3f
#define PI pair<int, int>
typedef long long LL;
const int maxn = 1000 + 5;
int dp[maxn][1<<10], w[maxn];

int main() {
	int n, m, q;
	while(scanf("%d%d%d", &n, &m, &q) == 3){
		for(int i = 1; i <= n; ++i) {
			scanf("%d", &w[i]);
		}
		memset(dp, 0, sizeof(dp));
		int tol = 1<<m;
		for(int i = 0; i < n; ++i) {
			for(int j = 0; j < tol; ++j) {
				int nex = (j>>1)^(1<<(m-1));
				int cnt = 0;
				for(int k = 0; k < m; ++k) {
					if(nex & (1<<k)) ++cnt;
				}
				if(cnt <= q) dp[i+1][nex] = max(dp[i+1][nex], dp[i][j] + w[i+1]);
				dp[i+1][j>>1] = max(dp[i+1][j>>1], dp[i][j]);
			}
		}
		int ans = 0;
		for(int i = 0; i < tol; ++i) {
			ans = max(ans, dp[n][i]);
		}
		printf("%d\n", ans);
	}
	return 0;
} 

如有不当之处欢迎指出!

上一篇:移植mbed到目标板


下一篇:HihoCoder 1044 垃圾清理 (优化:状态压缩)