BFS爆搜

1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2 5 6 4 3 1 2 3 4 5 6 1 4 2 5 3 6
0 3 -1
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <set>
#include <queue>
using namespace std;
struct DICE
{
int face[6];
}A,B;
bool check(DICE a,DICE b)
{
for(int i=0;i<6;i++)
if(a.face[i]!=b.face[i]) return false;
return true;
}
bool checkIMP(DICE x,DICE y)
{
int a[6],b[6];
for(int i=0;i<6;i++)
{
a[i]=x.face[i];
b[i]=y.face[i];
}
sort(a,a+6);
sort(b,b+6);
for(int i=0;i<6;i++)
{
if(a[i]!=b[i]) return false;
}
return true;
}
void init(DICE& x)
{
int a[6];
for(int i=0;i<6;i++)
a[i]=x.face[i];
sort(a,a+6);
for(int i=0;i<6;i++)
{
x.face[i]=lower_bound(a,a+6,x.face[i])-a+1;
}
}
void showit(DICE x)
{
for(int i=0;i<6;i++)
cout<<x.face[i]<<",";
cout<<endl;
}
int hash(DICE x)
{
int ret=0;
for(int i=0;i<6;i++)
ret=ret*10+x.face[i];
return ret;
}
void rhash(int h,DICE& x)
{
for(int i=5;i>=0;i--)
{
x.face[i]=h%10;
h/=10;
}
}
void LEFT(DICE& X)
{
int a[6];
for(int i=0;i<6;i++)
a[i]=X.face[i];
X.face[0]=a[3];
X.face[1]=a[2];
X.face[2]=a[0];
X.face[3]=a[1];
}
void RIGHT(DICE& X)
{
int a[6];
for(int i=0;i<6;i++)
a[i]=X.face[i];
X.face[0]=a[2];
X.face[1]=a[3];
X.face[3]=a[0];
X.face[2]=a[1];
}
void UP(DICE& X)
{
int a[6];
for(int i=0;i<6;i++)
a[i]=X.face[i];
X.face[0]=a[5];
X.face[1]=a[4];
X.face[4]=a[0];
X.face[5]=a[1];
}
void DOWN(DICE& X)
{
int a[6];
for(int i=0;i<6;i++)
a[i]=X.face[i];
X.face[0]=a[4];
X.face[1]=a[5];
X.face[4]=a[1];
X.face[5]=a[0];
}
bool st[1000001];
void bfs()
{
queue<int> q,qt;
memset(st,0,sizeof(st));
q.push(hash(A));
st[hash(A)]=0;
qt.push(0);
bool flag=false;
while(!q.empty())
{
int time=qt.front(); qt.pop();
int zhi=q.front(); q.pop();
DICE X,Y;int ha;
rhash(zhi,X); Y=X;
if(check(Y,B)==true)
{
flag=true;
printf("%d\n",time);
return ;
}
///LEFT
LEFT(X);
ha=hash(X);
if(st[ha]==false)
{
st[ha]=true;
q.push(ha);
qt.push(time+1);
}
///Right
X=Y;
RIGHT(X);
ha=hash(X);
if(st[ha]==false)
{
st[ha]=true;
q.push(ha);
qt.push(time+1);
}
///UP
X=Y;
UP(X);
ha=hash(X);
if(st[ha]==false)
{
st[ha]=true;
q.push(ha);
qt.push(time+1);
}
///DOWN
X=Y;
DOWN(X);
ha=hash(X);
if(st[ha]==false)
{
st[ha]=true;
q.push(ha);
qt.push(time+1);
}
}
if(flag==false) puts("-1");
}
int main()
{
int x;
while(scanf("%d",&x)!=EOF)
{
A.face[0]=x;
for(int i=1;i<6;i++) scanf("%d",&A.face[i]);
for(int i=0;i<6;i++) scanf("%d",&B.face[i]);
if(checkIMP(A,B)==false)
{
puts("-1"); continue;
}
init(A); init(B);
if(check(A,B)==true)
{
puts("0"); continue;
}
bfs();
}
return 0;
}
原文:http://blog.csdn.net/ck_boss/article/details/39276619