bnu 14327 The Water Bowls[bfs,状态压缩]

最近写了好多bfs的题目,有学到很多的新技巧,特此来总结。

题目链接:http://www.bnuoj.com/v3/problem_show.php?pid=14327

题目意思比较好懂,只是英语渣的同学就要受苦了。
Their snouts, though, are so wide that they flip not only one bowl but also the bowls on either side of that bowl (a total of three or -- in the case of either end bowl -- two bowls)。

他们的鼻子,是如此的宽以至于他们翻转不仅仅一个碗而且这个碗的两边的碗也被翻转。(如果这个碗是在最两边的话,当然就只能翻他有碗的那一边)。

一开始用bfs() + string 处理的时候,果断超时了。

然后后来想到直接用数组记录步数+把所有的0,1压缩成一个数,而且状态为2^20个。

状态转移的时候直接用位运算就ok了。bfs()就过了。


现在想来:能够使用效率高的数据结构绝对不要用效率低的数据结构是必须的。

还有盗用了别人的一点想法,就是这种类型(从一个状态到另一个状态)题目,可以在扩展的时候进行判断是否达到目标状态。这样可以省去很多的时间。

code:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std;

const int N = 22;
const int M = (1 << 20) + 100;
int hash[M];

int change(int x, int i)
{
    if(i > 0) x = x ^ (1 << (i - 1));
    if(i < 19) x = x ^ (1 << (i + 1));
    x = x ^ (1 << i);
    return x;
}

int bfs(int num)
{
    queue<int> q;
    q.push(num);
    hash[num] = 1;
    while(!q.empty())
    {
        int tmp, tmp1;
        tmp = q.front(); q.pop();
        for(int i = 0; i < 20; i ++){
            tmp1 = change(tmp, i);
            if(hash[tmp1] == 0){
                hash[tmp1] = hash[tmp] + 1;
                q.push(tmp1);
            }
            if(hash[0]) return hash[0];
        }
    }
    return -1;
}

int main()
{
    int x = 0, num = 0;
    for(int i = 0; i < 20; i ++){
        scanf("%d", &x);
        num = num * 2 + x;
    }
    printf("%d\n", bfs(num) - 1);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值