POJ 3986 数位dp

#include 
#include 
#include 
using namespace std;
const int mod = 1000000003;
const int maxn = 1 << 6;
int n, k, inp[maxn], dp[maxn][maxn][2], pw[maxn];
long long solve(int i, int pre, int len)
{
	long long cur = 0, res = 0;
	pre &= ~((1 << len) - 1);
	if (n + 1 == i) return !pre;
	int& k = dp[i][len][(pre & (1 << len)) ? 1 : 0];
	if (k != -1) return k;
	for (int j = 31; j >= 0; j--)
		if (inp[i] & (1 << j))
			res += solve(i + 1, pre ^ cur, max(j, len)) * pw[min(j, len)] % mod, res %= mod, cur |= 1 << j;
	return k = res;
}
void init()
{
	pw[0] = 1;
	for (int i = 1; i < maxn; i++)
		pw[i] = (pw[i - 1] * 2) % mod;
}
int main(int argc, char const *argv[])
{
	init();
	while (~scanf("%d%d", &n, &k) && n + k)
	{
		for (int i = 1; i <= n; i++)
			scanf("%d", &inp[i]), inp[i]++;
		memset(dp, -1, sizeof(dp));
		printf("%lld\n", solve(1, k, 0));
	}
	return 0;
}


dp[i][pre][len]表示Xi~Xn[最低位为第len位的前缀]为pre的方案数

dp[i][pre][len]= Sigma(dp[i+1][pre^cur][max(j,len)] * 2^min(j,len))

详细来自:http://blog.csdn.NET/snowdut/article/details/51581438


你可能感兴趣的:(POJ 3986 数位dp)