您的位置:首页 > 其它

HDU 3567 Eight II

2014-10-01 18:13 330 查看

Eight II

Time Limit: 2000ms
Memory Limit: 65536KB
This problem will be judged on HDU. Original ID: 3567
64-bit integer IO format: %I64d Java class name: Main

Eight-puzzle, which is also called "Nine grids", comes from an old game.

In this game, you are given a 3 by 3 board and 8 tiles. The tiles are numbered from 1 to 8 and each covers a grid. As you see, there is a blank grid which can be represented as an 'X'. Tiles in grids having a common edge with the blank grid can be moved into that blank grid. This operation leads to an exchange of 'X' with one tile.

We use the symbol 'r' to represent exchanging 'X' with the tile on its right side, and 'l' for the left side, 'u' for the one above it, 'd' for the one below it.

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <climits>
#include <vector>
#include <queue>
#include <cstdlib>
#include <string>
#include <set>
#include <stack>
#define LL long long
#define pii pair<int,int>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 3;
struct sta{
int x,y;
sta(int a = 0,int b = 0){
x = a;
y = b;
}
};
char mp[maxn][maxn];
sta s[11];
int nowx,nowy;
int h(){
int tmp = 0;
for(int i = 0; i < 9; i++){
int x = i/3,y = i%3;
if(mp[x][y] == 'X') continue;
tmp += abs(x - s[mp[x][y]-'0'].x) + abs(y - s[mp[x][y]-'0'].y);
}
return tmp;
}
int ans[200],limit;
const int dir[4][2] = {1,0,0,-1,0,1,-1,0};
const char d[4] = {'d','l','r','u'};
bool ok;
int IDAstar(int x,int y,int p,int cur){
int bound = INF,tmp;
int hv = h();
if(cur + hv > limit) return cur + hv;
if(hv == 0) {ok = true;return cur;}
for(int i = 0; i < 4; i++){
if(i == p) continue;
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if(tx < 0 || tx >= 3 || ty < 0 || ty >= 3) continue;
swap(mp[x][y],mp[tx][ty]);
ans[cur] = i;
int nbound = IDAstar(tx,ty,3-i,cur+1);
if(ok) return nbound;
bound = min(bound,nbound);
swap(mp[x][y],mp[tx][ty]);
}
return bound;
}
int main() {
int t,cs = 1;
char ch;
scanf("%d",&t);
getchar();
while(t--){
for(int i = 0; i < 9; i++){
ch = getchar();
if(ch == 'X'){
nowx = i/3;
nowy = i%3;
}
mp[i/3][i%3] = ch;
}
getchar();
for(int i = 0; i < 9; i++){
ch = getchar();
if(ch == 'X') continue;
s[ch-'0'] = sta(i/3,i%3);
}
getchar();
limit = h();
ok = false;
while(!ok) limit = IDAstar(nowx,nowy,-10,0);
printf("Case %d: %d\n",cs++,limit);
for(int i = 0; i < limit; i++)
putchar(d[ans[i]]);
putchar('\n');
}
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: