POJ1321：棋盘问题（状压dp & DFS）

 Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 40317 Accepted: 19685

Description

Input

Output

Sample Input

2 1
#.
.#
4 4
...#
..#.
.#..
#...
-1 -1


Sample Output

2
1


Source

# include <stdio.h>
# include <string.h>
char s[9][9];
int n, k, vis[9], ans;
void dfs(int l, int icount)
{
if(icount == 0)
{
++ans;
return;
}
if(l<=0)
return;
for(int j=1; j<=n; ++j)
{
if(s[l][j] == '#' &&!vis[j])
{
vis[j] = 1;
dfs(l-1, icount-1);
vis[j] = 0;
}
}
if(l-icount>0)
dfs(l-1, icount);
}
int main()
{
while(~scanf("%d%d",&n,&k),n != -1 && k!= -1)
{
ans = 0;
memset(vis, 0, sizeof(vis));
for(int i=1; i<=n; ++i)
scanf("%s",s[i]+1);
dfs(n, k);
printf("%d\n",ans);
}
return 0;
}

# include <stdio.h>
# include <string.h>
int dp[9][1<<9], sum[1<<9];
char s[10][10];
int fun(int num)
{
int cnt = 0;
while(num)
{
cnt += num&1;
num >>= 1;
}
return cnt;
}
int main()
{
int n, k, up=1<<9;
for(int i=0; i<up; ++i)
sum[i] = fun(i);
while(~scanf("%d%d",&n,&k),n!=-1 && k!=-1)
{
int r = 1<<n;
for(int i=1; i<=n; ++i)
scanf("%s",s[i]);
memset(dp, 0, sizeof(dp));
dp[0][0] = 1;
for(int i=1; i<=n; ++i)
for(int j=0; j<r; ++j)
if(sum[j] <= k)
{
dp[i][j] += dp[i-1][j];
for(int l=0; l<n; ++l)
if(s[i][l] == '#' && ((j&(1<<l))==0))
dp[i][j|(1<<l)] += dp[i-1][j];
}
int ans = 0;
for(int i=0; i<r; ++i)
if(sum[i] == k)
ans += dp[n][i];
printf("%d\n",ans);
}
return 0;
}