sgu 132


状压 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值