最近寫了好多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;
}