POJ 3254 状压dp

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
const int maxn = 1 << 12 + 10;
const int MOD = 1E8;
int dp[15][maxn], mp[15][15], n, m;
std::vector<int> vec[15];
int fun(int x)
{
	int s = 0;
	for (int i = 1; i <= m; i++)
		s += (!mp[x][i]) * (1 << (m - i));
	return s;
}
int main(int argc, char const *argv[])
{
	while (~scanf("%d%d", &n, &m) && n + m)
	{
		memset(dp, 0, sizeof(dp));
		memset(vec, 0, sizeof(vec));
		for (int i = 1; i <= n; i++)
			for (int j = 1; j <= m; j++)
				scanf("%d", &mp[i][j]);
		vec[0].push_back(0);
		for (int i = 0; i < (1 << m); i++)
			dp[0][i] = 1;
		for (int i = 1; i <= n; i++)
		{
			int tmp = fun(i);
			for (int j = 0; j < (1 << m); j++)
				if (!((j & (j >> 1)) || (j & tmp)))
					vec[i].push_back(j);
			for (int j = 0; j < vec[i].size(); j++)
			{
				int u = vec[i][j];
				for (int k = 0; k < vec[i - 1].size(); k++)
				{
					int v = vec[i - 1][k];
					if (v & u) continue;
					dp[i][u] = (dp[i][u] + dp[i - 1][v]) % MOD;
				}
			}
		}
		int ans = 0;
		for (int i = 0; i < (1 << m); i++)
			ans = (ans + dp[n][i]) % MOD;
		printf("%d\n", ans);
	}
	return 0;
}


dp[i][j] 就表示第i行状态为j时的方案数。

判断第i行是不是有两块相邻的土地同时都有牛,假设当前状态为X,那么只需要判断X&(X>>1)的结果,如果是0,说明没有相邻的,否则就说明有相邻的。

你可能感兴趣的:(POJ 3254 状压dp)