题意
传送门 AOJ 0121
直接 bfs 复杂度达到搜索深度的指数级,结合 dp 用 bfs 打表,每次保存 0 的位置,通过交换字符位置进行状态转移。
#include <iostream>
#include <algorithm>
#include <queue>
#include <map>
#include <string>
#define min(a,b) (((a) < (b)) ? (a) : (b))
#define max(a,b) (((a) > (b)) ? (a) : (b))
#define abs(x) ((x) < 0 ? -(x) : (x))
#define INF 0x3f3f3f3f
#define delta 0.85
#define eps 1e-3
#define PI 3.14159265358979323846
using namespace std;
struct st{
int p;
string s;
st(int p, string s) : p(p), s(s) {}
};
const int dx[4] = {4, -4, 1, -1};
map<string, int> dp;
bool judge(int x, int d){
if((x == 3 && d == 1) || (x == 4 && d == -1)) return 0;
x += d;
return x >= 0&& x <= 7;
}
void bfs(){
queue<st> que;
string f = "01234567";
dp[f] = 0;
que.push(st(0, f));
while(!que.empty()){
st now = que.front(); que.pop();
int x = now.p;
for(int i = 0; i < 4; i++){
if(judge(x, dx[i])){
int nx = x + dx[i];
string s = now.s;
swap(s[x], s[nx]);
if(dp.find(s) == dp.end()){
dp[s] = dp[now.s] + 1;
que.push(st(nx, s));
}
}
}
}
}
int main(){
bfs();
string s;
while(getline(cin, s)){
s.erase(remove(s.begin(), s.end(), ' '), s.end());
cout << dp[s] << endl;
}
return 0;
}