洛谷[P3622] 动物园

状压DP

发现本题中,每个小朋友是否高兴仅取决于其后五个动物的情况,我们可以用状压DP解决本题
首先已处理 num[i][s] 表示对于位置 i ,状态为 s 时有多少在 s 的同学满意
转移方程很好写
dp[i][s] = max(dp[i - 1][(s&15)<<1], dp[i - 1][(s&15)<<1|1]) + num[i][s];
但是本题是环状的所以我们要枚举开始的状态,答案就是 dp[n][枚举的状态]

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <queue>
using namespace std;
const int MAXN = 10055;
int init() {
	int rv = 0, fh = 1;
	char c = getchar();
	while(c < '0' || c > '9') {
		if(c == '-') fh = -1;
		c = getchar();
	}
	while(c >= '0' && c <= '9') {
		rv = (rv<<1) + (rv<<3) + c - '0';
		c = getchar();
	}
	return fh * rv;
}
int n, m, num[MAXN][35], dp[MAXN][35], ans;
int main() {
	n = init(); m = init();
	for(int i = 1; i <= m; i++) {
		int a = init(), b = init(), c = init();
		int l = 0, r = 0;
		for(int j = 1; j <= b; j++) {
			int t = init(); 
			t = (t - a + n) % n;
			l |= (1<<t);
		}
		for(int j = 1; j <= c; j++) {
			int t = init();
			t = (t - a + n) % n;
			r |= (1<<t);
		}
		for(int j = 0; j < 32; j++) {
			if((j & l) ||(~j & r)) num[a][j]++;
		}
	}
	for(int s = 0; s < 32; s++) {
		memset(dp[0], 128, sizeof(dp[0]));
		dp[0][s] = 0;
		for(int i = 1; i <= n; i++) {
			for(int j = 0; j < 32; j++) {
				dp[i][j] = max(dp[i - 1][(j&15)<<1], dp[i - 1][(j&15)<<1|1]) + num[i][j];
			}
		}
		ans = max(ans, dp[n][s]);
	}
	cout << ans << endl;
	return 0;
}
posted @ 2018-04-25 20:53  Mr_Wolfram  阅读(192)  评论(2编辑  收藏  举报