题目很有趣,正着跑一遍BFS慢的要死,看了题解发现可以逆向搜,因为BFS本身是双向的,逆向的话直接存了所有情况的状态,而且数据量不大, 打个表直接输出也是美滋滋。
#include<iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <stack>
#include <queue>
#include <cmath>
using namespace std;
const int maxn = 1000+5;
typedef long long ll;
string s;
map<string,int > mp;
queue<string> q;
int d[] = {1,-1,4,-4};
void bfs(){
q.push("01234567");
while(!q.empty()){
string s1 = q.front();
q.pop();
int pos = s1.find('0');
for(int i = 0;i < 4;i++){
int x = pos + d[i];
if(x>=0&&x<8&&(!(pos==3&&i==0)&&!(pos==4&&i==1))){
string u = s1;
swap(u[pos],u[x]);
if(mp[u]==0){
mp[u]=mp[s1]+1;
q.push(u);
}
}
}
}
return;
}
int main() {
bfs();
mp["01234567"] = 0;
while(1){
s = "";
int a = 8,b;
while(a--){
if(!(cin>>b)) return 0;
s += b+'0';
}
cout<<mp[s]<<endl;
}
return 0;
}