费解的开关题目入口:https://www.acwing.com/problem/content/97/
因为达到终点步数在6步以内的状态有限,不管多少次的询问,这些状态都不会增加或减少,步数也不会变化,那么我们可以先预处理出从终点在6步及以内能走到的所有状态,并记录步数,那么在后面查询时主要在之前记录的数组里取出步数即可。
#include<bits/stdc++.h>
using namespace std;
int step[1<<25];
struct node {
int nowstatus;
int step;
};
queue<node>q;
void pre_bfs(){
memset(step,-1,sizeof(step));
q.push((node){(1<<25)-1,0});
step[(1<<25)-1] = 0;
while(!q.empty()){
node temp = q.front();
q.pop();
if(temp.step == 6) continue;
//枚举每个位上被按的情况。
for(int i = 1;i<= 25; i++){
int tp = 1<< (i-1);
if(i%5 != 1) tp += (1<< (i-2));//如果不是最左边的位置
if(i%5 != 0) tp += (1<< i); //如果不是最右边的位置
if(i > 5) tp += (1 << (i-6));//如果不是最上边的位置
if(i < 21) tp += (1<< (i+4));//如果不是最下边的位置
node news = (node){temp.nowstatus ^ tp,temp.step+1};
if(step[news.nowstatus] == -1){
q.push(news);
step[news.nowstatus] = news.step;
}
}
}
}
int main(){
int n;
scanf("%d",&n);
pre_bfs();
for(int i = 1;i<= n; i++){
int num = 0;
char c;
for(int i = 1;i<= 25;i++){
cin >> c;
num += ((c-'0') << (i-1)) ;
}
printf("%d\n",step[num]);
}
return 0;
}