很无语的题!!!由于题目数据水,从而给的类存相当的小,所以如果用数组模拟队列的话,最后必定memory limit !!!!输出格式也傻逼!!!
#include<iostream>
#include<string>
#include<algorithm>
#include<queue>
#define MAXN 800000
using namespace std;
struct node{
string str;
int dist;};
queue<node> st;
node goal;
int vis[MAXN];
int fact[9];
const int dx[4]={-1,1,0,0};
const int dy[4]={0,0,-1,1};
int try_to_insert(node& s){
int code=0;
for(int i=0;i<9;i++)
{int cnt=0;
for(int j=i+1;j<9;j++) if(s.str[j]<s.str[i]) cnt++;
code+=fact[8-i]*cnt;}
if(vis[code]) return 0;
vis[code]=1;
return 1;
}
void bfs(){
fact[0]=1;
for(int i=1;i<9;i++) fact[i]=fact[i-1]*i;
while(!st.empty()){
node s=st.front();
if(s.str==goal.str)return;
int z;//cout<<s.str[0];system("pause");
for(z=0;z<9;z++) if(s.str[z]=='A') break;
int x=z/3,y=z%3;
for(int d=0;d<4;d++)
{
int newx=x+dx[d];
int newy=y+dy[d];
int newz=newx*3+newy;
if(newx>=0&&newx<3&&newy>=0&&newy<3)
{
node t;
t.str=s.str;
t.str[newz]=s.str[z];
t.str[z]=s.str[newz];
t.dist=s.dist+1;
// cout<<t.dist<<endl;
if(try_to_insert(t)) st.push(t);
}
}
st.pop();}return;}
int main(){
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int t;
cin>>t;
int q=1;
while(t--){
memset(vis,0,sizeof(vis));
while(!st.empty()) st.pop();
goal.str.clear();
node first;
string a;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
cin>>a;
first.str+=a;}}
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{cin>>a;goal.str+=a;}
first.dist=0;
st.push(first);
bfs();
node ans=st.front();
if(ans.dist>=0) {printf("Battle array #%d :/n",q);
printf("The minimum move of the battle array is : %d/n",ans.dist);}
// if(q<t)
printf("/n");
q++;
}
return 0;}