标签:
与hdu 1430 魔板一样采取预处理。用map代替康托展开
不过要注意,我们要反向储存路径和状态,例如我们向上搜索,但我们实际上得到的是从上走到下的结果因此要记录d,最后把得到的路径反向输出
不过用g++居然超内存了.
#include<iostream>
#include<queue>
#include<cstring>
#include<map>
using namespace std;
string ans;
map<string,string>root;
struct stu
{
string ans;
string root;
int mark;
};
void bfs()
{
int sum=0;
queue<stu>mapp;
stu x,y;
x.ans="12345678x";x.root="";x.mark=8;
mapp.push(x);
while(mapp.size())
{
//cout<<mapp.size()<<endl;
x=mapp.front();
mapp.pop();
if(root.find(x.ans)!=root.end()) continue;
root[x.ans]=x.root;
if(x.mark>2)
{
y.ans=x.ans;
swap(y.ans[x.mark],y.ans[x.mark-3]);
y.mark=x.mark-3;
y.root=x.root+'d';
if(root.find(y.ans)==root.end())mapp.push(y);
}
if(x.mark<6)
{
y.ans=x.ans;
swap(y.ans[x.mark],y.ans[x.mark+3]);
y.mark=x.mark+3;
y.root=x.root+'u';
if(root.find(y.ans)==root.end())mapp.push(y);
}
if(x.mark%3!=0)
{
y.ans=x.ans;
swap(y.ans[x.mark],y.ans[x.mark-1]);
y.mark=x.mark-1;
y.root=x.root+'r';
if(root.find(y.ans)==root.end())mapp.push(y);
}
if(x.mark%3!=2)
{
y.ans=x.ans;
swap(y.ans[x.mark],y.ans[x.mark+1]);
y.mark=x.mark+1;
y.root=x.root+'l';
if(root.find(y.ans)==root.end())mapp.push(y);
}
}
}
int main()
{
bfs();
char x;
while(cin>>x)
{
ans+=x;
for(int i=1;i<=8;i++)
{
cin>>x;
ans+=x;
}
if(root.find(ans)!=root.end())
{
for(int i=root[ans].size()-1;i>=0;i--) cout<<root[ans][i];
cout<<endl;
}
else cout<<"unsolvable"<<endl;
ans="";
}
return 0;
}
标签:
原文地址:http://blog.csdn.net/zafkiel_nightmare/article/details/45968549