想不清楚,看题解:http://blog.csdn.net/u014634338/article/details/50015825
题解很详细,就不扯淡了。
下边的dfs解法扯了扯淡
#include <stdio.h>
#include <string.h>
typedef long long LL;
LL dp[11][1<<11];
int n,m;
template <typename T>
void swap(T &a, T &b)
{
a = a^b;
b = a^b;
a = a^b;
}
bool check(int num)
{
int i = 0;
while(i < m)
{
if(num&(1<<i))
{
if(i == m-1)
return false;
if(num&(1<<i+1))
i += 2;
else
return false;
}
else
++i;
}
return true;
}
bool judge(int cur, int pre)
{
int i = 0;
while(i < m)
{
if(cur&(1<<i))
{
if(pre&(1<<i))
{
if(i == m-1 || !(cur&(1<<(i+1))) || !(pre&(1<<(i+1))))
return false;
else
i += 2;
}
else
++i;
}
else
{
if(pre&(1<<i))
++i;
else
return false;
}
}
return true;
}
int main()
{
while(scanf("%d %d",&n,&m) && n+m)
{
if((n&1) && (m&1))
{
printf("0\n");
continue;
}
if(m > n) swap(n,m);
int x = 1 << m;
memset(dp,0,sizeof(dp));
for(int i = 0; i < x; ++i)
if(check(i))
dp[0][i] = 1;
for(int r = 1; r < n; ++r)
{
for(int i = 0; i < x; ++i)
{
for(int j = 0; j < x; ++j)
{
if(judge(i,j))
dp[r][i] += dp[r-1][j];
}
}
}
printf("%I64d\n",dp[n-1][x-1]);
}
return 0;
}
还是dfs写出来的效率高
参考:http://www.cnblogs.com/keam37/p/3834490.html
摆放当前行的时候,如果上一行为空,则可以竖着放;如果上一行不为空,则当前格子不放;如果上一行俩这俩都是空的,两行都横着放。就这三种情况,dfs的时候构造这三种情况就行。
也可以参考:https://wenku.baidu.com/view/16d299d63186bceb19e8bb12.html里面的例5
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
typedef long long LL;
LL dp[12][1<<12];
int n,m;
void dfs(int row, int col, int s1, int s2)
{
if(col == m)
{
dp[row][s2] += dp[row-1][s1];
return ;
}
if(col > m) return;
dfs(row, col+1, s1<<1, s2<<1|1);
dfs(row, col+1, s1<<1|1, s2<<1);
dfs(row, col+2, s1<<2|3, s2<<2|3);
}
int main()
{
while(scanf("%d %d",&n,&m) && n+m)
{
if(n < m) swap(n,m);
memset(dp,0,sizeof(dp));
dp[0][(1<<m)-1] = 1;
for(int i = 1; i <= n; ++i)
dfs(i,0,0,0);
printf("%I64d\n",dp[n][(1<<m)-1]);
}
return 0;
}