HDU 4127 Flood-it! (迭代加深搜索)

使用迭代加深搜索解决HDU 4127 Flood-it问题,通过DFS结合BFS进行染色,利用剪枝策略优化搜索效率,避免TLE。在8*8矩阵中,将图压缩为long long整型,当剩余未染色格子颜色数大于剩余染色次数时剪枝。搜索过程中的剪枝技巧对于AC至关重要。

解法: 题目中一个8*8的矩阵,只有6种颜色染色,很容易想到最糟糕的情况也不可能会需要64步,反而由于颜色的数量限制,答案很可能很小,而又没有什么规律在,那么第一眼就想到了迭代加深搜索,即,由小到大枚举答案,若可行则为最小解,主体用dfs搜索,用bfs进行染色,8*8的格子使得可以把图压缩到一个long long 整型,但是还需要一个看似不起眼的剪枝,否则TLE到哭: 当剩下未染的格子的颜色种数大于剩下的染色次数时,直接放弃对该子树的搜索。

虽然这个剪枝在颜色数只有6的情况下看似鸡肋,但是不然,因为在深度优先搜索的过程中,前n-1层相对于第n层都可以忽略,那么一次剪掉6层。。。效果可想而知。这里的大意导致比赛时不能AC,真是爽。。

搜索的魅力(kengdie)大概在于,莫名其妙的剪枝,莫名其妙的AC。。

/* Created Time: Wednesday, November 06, 2013 PM02:06:50 CST */
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
typedef long long lld;
const int N = 8;
int n,col[N][N],sa[6];
lld all;
int dir[4][2] = {1,0,0,1,-1,0,0,-1};
bool exist(lld st,int x,int y) {
    return st&(1ll<<(x*n+y));
}
void show(lld st) {
    for (int i = 0; i < n; i ++) {
        for (int j = 0; j < n; j ++)
            printf("%d ",exist(st,i,j));
        puts("");
    }
    puts("");
}
int que[110],qf,qe;
int cover(lld og,lld &st,int c) {
    int cnt[6] = {0};
    qf = 0;
    qe = -1;
    que[++qe] = 0;
    st = 1;
    cnt[col[0][0]] ++;
    while (qf<=qe) {
        int f = que[qf++];
        int x = f/n,y = f%n;
        for (int i = 0; i < 4; i ++) {
            int ex = x+dir[i][0];
            int ey = y+dir[i][1];
            if (ex<0 || ex>=n ||ey<0 || ey>=n) continue;
            if (exist(st,ex,ey)) continue;
            if (exist(og,ex,ey) || col[ex][ey]==c) {
                cnt[col[ex][ey]] ++;
                st |= 1ll<<(ex*n+ey);
                que[++qe] = ex*n+ey;
            }
        }
    }
    int ret = 0;
    for (int i = 0; i < 6; i ++)
        if (sa[i]-cnt[i]) ret ++;
    return ret;
}
bool dfs(lld st,int cur) {
    if (cur==0) {
        return st==all;
    }
    for (int i = 0; i < 6; i ++) {
        lld bst = 0;
        int left = cover(st,bst,i);
        if (st==bst || left>cur-1) continue;
        if (dfs(bst,cur-1)) return true;
    }
    return false;
}
int work() {
    all = 0;
    for (int i = 0; i < n; i ++)
        for (int j = 0; j < n; j ++)
            all |= 1ll<<(i*n+j);
    lld st = 0;
    cover(0,st,col[0][0]);
    for (int i = 0; i <= n*n; i ++) {
        if (dfs(st,i)) return i;
    }
    return -1;
}
int main() {
    while (~scanf("%d",&n),n) {
        memset(sa,0,sizeof(sa));
        for (int i = 0;  i < n; i ++)
            for (int j = 0; j < n; j ++) {
                scanf("%d",&col[i][j]);
                sa[col[i][j]] ++;
            }
        printf("%d\n",work());
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值