1085: [SCOI2005]骑士精神
2016-05-29 12:07
169 查看
1085: [SCOI2005]骑士精神
Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 1557 Solved: 857
[Submit][Status][Discuss]
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
210110
01*11
10111
01001
00000
01011
110*1
01110
01010
00100
Sample Output
7-1
HINT
Source
[Submit][Status][Discuss]
迭代加深搜索+可行性剪枝(如果当前未归位的棋子大于剩余步数果断return)
苟蒻还是太弱。。碰到搜索题一脸懵逼
#include<iostream> #include<cstdio> #include<cstdlib> #include<algorithm> #include<cstring> #include<cmath> #include<vector> #include<queue> using namespace std; const int dx[8] = {1,2,1,2,-1,-2,-1,-2}; const int dy[8] = {2,1,-2,-1,2,1,-2,-1}; const int goal = 549855; const int c[5][5] = {{1,1,1,1,1},{0,1,1,1,1},{0,0,3,1,1},{0,0,0,0,1},{0,0,0,0,0}}; int n,m,cnt,ans,a[5][5],b[5][5]; char ch[10]; int calculate() { int ret = 0; for (int j = 0; j < 5; j++) for (int l = 0; l < 5; l++) if (a[j][l] != 3) ret += a[j][l]*b[j][l]; return ret; } bool dfs(int x,int y,short step,int now,int MAX) { bool flag = 0; int tot = 0; if (step == MAX) return now == goal && x == 2 && y == 2; for (int i = 0; i < 5; i++) for (int j = 0; j < 5; j++) if (c[i][j] != 3 && c[i][j] != a[i][j]) ++tot; if (step + tot > MAX) return 0; for (int i = 0; i < 8; i++) { int xx = x + dx[i]; int yy = y + dy[i]; if (xx < 0 || xx > 4 || yy < 0 || yy > 4) continue; swap(a[x][y],a[xx][yy]); int next = calculate(); if (dfs(xx,yy,step+1,next,MAX)) return 1; swap(a[x][y],a[xx][yy]); } return flag; } void PRE(int &x,int &y,int &now) { for (int i = 0; i < 5; i++) { cin >> ch; for (int j = 0; j < 5; j++) { if (ch[j] == '*') x = i,y = j,a[i][j] = 3; else a[i][j] = ch[j]-'0',now += b[i][j]*a[i][j]; } } } int main() { #ifdef YZY freopen("yzy.txt","r",stdin); #endif cin >> n; int h = 0; for (int i = 0; i < 5; i++) for (int j = 0; j < 5; j++) b[i][j] = 1<<h,++h; for (cnt = 1; cnt <= n; cnt++) { int x,y,now = 0; PRE(x,y,now); for (ans = 1; ans <= 15; ans++) if (dfs(x,y,0,now,ans)) break; if (ans > 15) ans = -1; printf("%d\n",ans); } return 0; }
相关文章推荐
- Java二分查找算法
- JMS概述
- 随笔—邀请赛前训—Codeforces Round #327 (Div. 2) Rebranding
- 重建freescale 4.6.2 multilib toolchain
- 抓包来看ftp状态码
- 数据加密(MD5,DES,RSA)简析
- BZOJ3779: 重组病毒
- 【算法笔记】贪心算法——01背包问题
- TI CC2541 OAD流程
- 用两个栈组成队列
- Shader Forge 颜色乘法+加法+控制饱和度+角色发光+和程序的衔接
- 同程面试经历 android开发工程师
- 计算机中的布尔操作 ^ (即XOR)的学习
- ActiveMQ编程实例
- 牧羊曲
- Digit(湘潭大学比赛)
- spring+mybatis+ehcahce实现注解缓存
- 线性表的顺序存储结构
- Digit(湘潭大学比赛)
- Hibernate 中的session 的flush、reflush 和clear 方法 ,及数据库的隔离级别