【BZOJ4197】[Noi2015]寿司晚宴【状压DP】【背包】

【题目链接】

一开始取了前10个质数状压,然后就TLE了...改成前8个就没事了。

/* Pigonometry */
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

typedef long long LL;

const int maxn = 505, maxk = 505;

int n, p, prime[maxn], cnt, bin[13], S;
LL f[maxk], g[maxk][maxk], A[maxk][maxk], B[maxk][maxk];
bool isnotprime[maxn];

inline void getprime() {
	for(int i = 2; i <= 500; i++) {
		if(!isnotprime[i]) prime[++cnt] = i;
		for(int j = 1; j <= cnt && i * prime[j] <= 500; j++) {
			isnotprime[i * prime[j]] = 1;
			if(i % prime[j] == 0) break;
		}
	}
}

inline int index(int x) {
	int res = 0;
	for(int i = 1; i <= 8 && i <= cnt; i++) if(x % prime[i] == 0)
		res |= bin[i];
	return res;
}

int main() {
	scanf("%d%d", &n, &p);

	getprime();

	bin[1] = 1;
	for(int i = 2; i <= 8; i++) bin[i] = bin[i - 1] << 1;
	S = 1 << 8;

	f[0] = 1;
	for(int i = 2; i <= n; i++) {
		bool flag = 0;
		for(int j = 9; j <= cnt; j++) if(i % prime[j] == 0) {
			flag = 1;
			break;
		}
		if(flag) continue;

		int id = index(i);
		for(int j = S - 1; j >= 0; j--) (f[j | id] += f[j]) %= p;
	}

	for(int i = 0; i < S; i++) for(int j = 0; j < S; j++) if((i & j) == 0)
		g[i][j] = f[i] * f[j] % p;

	for(int i = 9; i <= cnt; i++) {
		memset(A, 0, sizeof(A)); memset(B, 0, sizeof(B));

		for(int j = prime[i]; j <= n; j += prime[i]) {
			int id = index(j);
			for(int k = S - 1; k >= 0; k--) for(int l = S - 1; l >= 0; l--) if((k & l) == 0) {
				A[k | id][l] += g[k][l] + A[k][l];
				B[k][l | id] += g[k][l] + B[k][l];
			}
		}

		for(int j = 0; j < S; j++) for(int k = 0; k < S; k++) if((j & k) == 0)
			(g[j][k] += A[j][k] % p + B[j][k] % p) %= p;
	}

	LL ans = 0;
	for(int i = 0; i < S; i++) for(int j = 0; j < S; j++) if((i & j) == 0)
		(ans += g[i][j]) %= p;
	printf("%lld\n", ans);
	return 0;
}


你可能感兴趣的:(【BZOJ4197】[Noi2015]寿司晚宴【状压DP】【背包】)