sgu 132 分类: sgu 2015-05-20 13:06 28人阅读 评论(0) 收藏


状压DP,时间复杂度O(m22n3n)


#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>

const int MAXM = 75, MAXN = 7, INF = 1<<30, Nya = -1;

int n, m;
int map[MAXM];
int f[2][1<<MAXN][1<<MAXN];
int ans = INF, flag;

void Update(int &x,int y)
{// y != Nya
    if(x == Nya || y < x) x = y;
}
void DFS(int row,int col,int now,int las,int cost)
{
    if((map[row]&now)||(map[row-1]&las)) return;

    if(col == n)
    {
        for(int lasp = 0; lasp < (1<<n); lasp++)
        {
            if((lasp&las) || (lasp&map[row-1])) continue;

            int last = lasp^las^map[row-1];

            bool tag = true; 
            for(int i = 1; i < n && tag; i++)
                if(!(last&(1<<i)) && !(last&(1<<(i-1)))) tag = false;
            if(!tag) continue;

            if(row == 1) {Update(f[flag][lasp^las][now], cost); continue;}

            for(int lasq = 0; lasq < (1<<n); lasq++)
                if(f[flag^1][lasq][lasp] != Nya)
                {
                    int qast = lasq^map[row-2];

                    tag = true;
                    for(int i = 0; i < n && tag; i++)
                        if(!(qast&(1<<i)) && !(last&(1<<i))) tag = false;
                    if(!tag) continue;

                    Update(f[flag][lasp^las][now],f[flag^1][lasq][lasp] + cost);
                }
        }
    }
    else
    {
        DFS(row,col+1,now|(1<<col),las|(1<<col),cost+1);

        if(col && (!(now&(1<<(col-1)))))
            DFS(row,col+1,now|(1<<(col-1))|(1<<col),las,cost+1);

        DFS(row,col+1,now,las,cost);
    }
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("sgu132.in","r",stdin); 
    freopen("sgu132.out","w",stdout);
#endif

    std::cin >> m >> n;
    for(int i = 1; i <= m; i++)
    {
        char str[MAXN+3]; std::cin >> str;
        for(int j = 0; j < n; j++)
            if(str[j] == '*') map[i] |= 1<<j;
    }
    map[0] = map[m+1] = map[m+2] = (1<<n)-1;

    for(int i = 1; i <= m+2 ; i++)
        flag ^= 1, memset(f[flag],Nya,sizeof(f[flag])), DFS(i,0,0,0,0);

    for(int i = 0 ; i < (1<<n); i++)
        for(int j = 0 ; j < (1<<n); j++)
            if(f[flag][i][j] != Nya)
                ans = std::min(ans,f[flag][i][j]);

    std::cout << ans;

#ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
#endif
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-05-20 13:06  <Dash>  阅读(206)  评论(0编辑  收藏  举报