[Uva 10085] The most distant state (BFS)

时间:2024-01-18 18:29:08

题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1026

题目大意:就是说给你一个8数码,问你能够达到的距离最远的状态是什么。

刚开始以为只要顺着一边走就行了,后来发现这样走可能最远到达的状态也能通过其他方式到达。

在这里WA了好多次。

应该把所有可能出现的情况全都枚举出来,然后判重。。

UVA也真是慢。。4s的代码跑了快4分钟。。。

 #include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <map>
#include <set>
#include <queue>
#include <string>
using namespace std;
typedef unsigned long long ull; const int B = ; struct Node{
int status[][];
int h;
int x,y;
string route;
}; int T;
int dir[][] = {{,},{-,},{,},{,-}}; int main(){
scanf("%d",&T);
for(int t=;t<=T;t++){
Node s;
s.h = ;
set<int> se;
for(int i=;i<;i++){
for(int j=;j<;j++){
scanf("%d",&s.status[i][j]);
s.h = s.h*+s.status[i][j];
if( s.status[i][j] == ){
s.x = i; s.y = j;
}
}
}
se.insert(s.h);
// printf("%d\n",s.h);
s.route = "";
queue<Node> q;
q.push(s);
Node ans = s;
bool fl = true;
while(!q.empty()){
Node tn = q.front(); q.pop();
if( fl || ans.route.size()<tn.route.size()) ans = tn;
for(int i=;i<;i++){
Node t = tn;
int dx = t.x+dir[i][], dy = t.y+dir[i][];
if( dx<=&&dx>=&&dy<=&&dy>= ){
swap(t.status[tn.x][tn.y],t.status[dx][dy]);
t.x = dx; t.y = dy;
int tt = ;
for(int i=;i<;i++){
for(int j=;j<;j++){
tt = tt*B+t.status[i][j];
}
}
t.h = tt; if( i== ) t.route = tn.route+"D";
else if( i== ) t.route = tn.route+"U";
else if( i== ) t.route = tn.route+"R";
else if( i== ) t.route = tn.route+"L";
if( se.find(tt)==se.end() ){
se.insert(tt);
q.push(t);
}
}
}
}
printf("Puzzle #%d\n",t);
for(int i=;i<;i++) for(int j=;j<;j++){
printf(j==?"%d\n":"%d ",ans.status[i][j]);
}
puts(ans.route.c_str());
puts("");
}
return ;
}