[hdu 1067]bfs+hash
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1067
queue里面果然不能放vector,还是自己写的struct比较省内存……
#include<bits/stdc++.h> using namespace std; int a[4][8]; const int INF=0x3f3f3f3f; const int p=55566677; const int md=1000000007; struct Node { int a[4][8]; Node(){} Node(const int x[4][8]) { for (int i=0;i<4;i++) for (int j=0;j<8;j++) a[i][j]=x[i][j]; } int gethash() const { int now=0; for (int i=0;i<4;i++) for (int j=0;j<8;j++) now=(1ll*now*p%md+a[i][j])%md; return now; } }; const int End[4][8]= { {11,12,13,14,15,16,17,0}, {21,22,23,24,25,26,27,0}, {31,32,33,34,35,36,37,0}, {41,42,43,44,45,46,47,0} }; const Node endNode(End); const int term=endNode.gethash(); unordered_map<int,int> M; queue<Node> q; int bfs() { M.clear(); while (!q.empty()) q.pop(); for (int i=0;i<4;i++) for (int j=1;j<8;j++) if (a[i][j]%10==1) { int tmp=a[i][j]; a[i][j]=0; a[tmp/10-1][0]=tmp; } Node tmp; for (int i=0;i<4;i++) for (int j=0;j<8;j++) tmp.a[i][j]=a[i][j]; q.push(tmp); int H=tmp.gethash(); if (H==term) return 0; M[H]=0; while (!q.empty()) { Node now=q.front(); int st=M[now.gethash()]; q.pop(); for (int i=0;i<4;i++) for (int j=1;j<8;j++) if (now.a[i][j]==0 && now.a[i][j-1]%10!=7) { int tar=now.a[i][j-1]+1; int K=-1; for (int I=0;I<4;I++) { for (int J=1;J<8;J++) { if (now.a[I][J]==tar) { K=I*8+J; break; } } if (K!=-1) break; } now.a[i][j]=tar; now.a[K/8][K%8]=0; int H=now.gethash(); if (!M.count(H)) { if (H==term) return st+1; q.push(now); M[H]=st+1; } now.a[i][j]=0; now.a[K/8][K%8]=tar; } } return INF; } int main() { int t; scanf("%d",&t); while (t--) { for (int i=0;i<4;i++) for (int j=1;j<8;j++) scanf("%d",&a[i][j]); int ans=bfs(); if (ans!=INF) printf("%d\n",ans); else printf("-1\n"); } return 0; }