poj 1321 状态压缩dp||dfs

状态压缩dp

#include 
#include 
#include 
#include 
#include 
using namespace std;
#define mod 100000000
char ss[9][9];
int dp[9][1<<8];
int cnt[1<<8];
void calcu()
{
    for(int i = 0; i < (1<<8); i++)
    {
        for(int k = 1; k <= 8; k++)
            if((1<<(k - 1)) & i)
                cnt[i]++;
    }
}
int main()
{
    int n, m;
    memset(cnt, 0, sizeof cnt);
    calcu();
    while(cin>>n>>m &&(n != -1))
    {
        for(int i = 0; i < n; i++)
            cin>>(ss[i+1]+1);
        memset(dp, 0, sizeof dp);
        dp[0][0] = 1;
        for(int i = 0; i < n; i++)
            for(int j = 0; j <= (1<

或者dfs

#include 
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "algorithm"
using namespace std;

int n,k,ans;
char ss[9][9];
int vis[9];
void dfs(int row,int num)
{
    if(num==k)  {ans++;return;}
    if(row>n)  return;
    for(int i=1;i<=n;i++)
        if(ss[row][i]=='#'&&!vis[i]) {
            vis[i]=1;
            dfs(row+1,num+1);
            vis[i]=0;
            }
    dfs(row+1,num);
}

int main()
{
    while(scanf("%d%d",&n,&k)!=EOF)
    {
        if(n==-1&&k==-1) return 0;
        ans=0;
        memset(vis,0,sizeof vis);
        for(int i=1;i<=n;i++)
            scanf("%s",ss[i]+1);
        dfs(1,0);
        printf("%d\n",ans);
    }
    return 0;
}


你可能感兴趣的:(动态规划,搜索)