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

来源:互联网 发布:linux文件给用户权限 编辑:程序博客网 时间:2024/05/16 18:39

最近写了好多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