您的位置:首页 > 其它

BZOJ 1085 SCOI 2005 骑士精神

2016-02-07 10:40 411 查看
之前听说过IDA*,好像很优越啊。

估价函数为不在目标位置的棋子个数。

如果限定的最大搜索深度超过了已经走过的步数+最小可能的步数(即估价函数值),那么就不需要继续走了。

枚举一遍最大搜索深度即可。

还得好好斟酌一下要枚举的搜索深度。。

344ms。。

#include <cstdio>
#include <algorithm>
using namespace std;
#define rep(i,j,k) for(int i=j;i<k;i++)
const int tg[5][5] = {
{1, 1, 1, 1, 1},
{0, 1, 1, 1, 1},
{0, 0, 2, 1, 1},
{0, 0, 0, 0, 1},
{0, 0, 0, 0, 0}
};
const int dx[] = {1, 1, -1, -1, 2, 2, -2, -2};
const int dy[] = {2, -2, 2, -2, 1, -1, 1, -1};
int mp[5][5];
bool ida(int dep, int maxdep, int x, int y, int h) {
if (dep > maxdep) return 0;
if (h == 0) return 1;
if (h - 1 + dep > maxdep) return 0;
rep(i,0,8) {
int nx = x + dx[i], ny = y + dy[i], nh = h;
if (nx < 0 || nx > 4 || ny < 0 || ny > 4) continue;
if (mp[x][y] == tg[x][y]) nh++;
if (mp[nx][ny] == tg[x][y]) nh--;
if (mp[nx][ny] == tg[nx][ny]) nh++;
if (mp[x][y] == tg[nx][ny]) nh--;
swap(mp[x][y], mp[nx][ny]);
if (ida(dep + 1, maxdep, nx, ny, nh)) return 1;
swap(mp[x][y], mp[nx][ny]);
}
return 0;
}
int main() {
static char p[8];
int t, x, y, k, h;
scanf("%d", &t);
while (t--) {
rep(i,0,5) {
scanf("%s", p);
rep(j,0,5) if (p[j] == '*') x = i, y = j, mp[i][j] = 2;
else mp[i][j] = p[j] - '0';
}
h = 0;
rep(i,0,5) rep(j,0,5)
h += mp[i][j] != tg[i][j];
for(k=0;k<16;k++)
if (ida(0, k, x, y, h)) { printf("%d\n", k); break; }
if (k == 16) puts("-1");
}
return 0;
}

1085: [SCOI2005]骑士精神

Time Limit: 10 Sec  Memory Limit: 162 MB
Submit: 1401  Solved: 766

Description

在一个5×5的棋盘上有12个白色的骑士和12个黑色的骑士, 且有一个空位。在任何时候一个骑士都能按照骑士的走法(它可以走到和它横坐标相差为1,纵坐标相差为2或者横坐标相差为2,纵坐标相差为1的格子)移动到空位上。 给定一个初始的棋盘,怎样才能经过移动变成如下目标棋盘: 为了体现出骑士精神,他们必须以最少的步数完成任务。



Input

第一行有一个正整数T(T<=10),表示一共有N组数据。接下来有T个5×5的矩阵,0表示白色骑士,1表示黑色骑士,*表示空位。两组数据之间没有空行。

Output

对于每组数据都输出一行。如果能在15步以内(包括15步)到达目标状态,则输出步数,否则输出-1。

Sample Input

2

10110

01*11

10111

01001

00000

01011

110*1

01110

01010

00100

Sample Output

7

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