queue算法中一般要用到的有
q.empty()若队列为空,返回true,否则返回false
q.size()返回队列中的元素个数
q.pop()删除队首元素
q.front()返回队首元素的值 ,但不删除该元素(仅适用于FIFO队列 )
q.back()返回队尾元素的值,但不删除该元素(仅适用于FIFO队列)
q.top()返回具有最高优先级的元素的值,但不删除该元素
q.push()对queue在队尾压入一个新元素
对priority_queue在基于优先级的适当位置插入新元素
A friend of you is doing research on the Traveling Knight Problem (TKP) where you are to find the shortest closed tour of knight moves that visits each square of a given set of n squares on a chessboard exactly once. He thinks that the most difficult part of the problem is determining the smallest number of knight moves between two given squares and that, once you have accomplished this, finding the tour would be easy.
Of course you know that it is vice versa. So you offer him to write a program that solves the ”difficult” part.
Your job is to write a program that takes two squares a and b as input and then determines the number of knight moves on a shortest route from a to b.
Input
The input file will contain one or more test cases. Each test case consists of one line containing two squaresseparatedbyonespace. Asquareisastringconsistingofaletter(a…h)representingthecolumn and a digit (1…8) representing the row on the chessboard.
Output
For each test case, print one line saying ‘To get from xx to yy takes n knight moves.’.
译文:
你们的一个朋友正在研究旅行骑士问题(TKP),在这里你们要找到最短的封闭的骑士移动旅行,访问一次棋盘上给定的n个方格的每个方格。他认为这个问题最困难的部分是确定两个给定方格之间骑士移动的最小数量,一旦你完成了这项工作,就很容易找到巡演。当然你知道反之亦然。所以你让他写一个解决“困难”部分的程序。你的工作是编写一个程序,以两个正方形a和b作为输入,然后确定骑士在从a到b的最短路线上移动的次数。
Sample Input
e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6
Sample Output
To get from e2 to e4 takes 2 knight moves.
To get from a1 to b2 takes 4 knight moves.
To get from b2 to c3 takes 2 knight moves.
To get from a1 to h8 takes 6 knight moves.
To get from a1 to h7 takes 5 knight moves.
To get from h8 to a1 takes 6 knight moves.
To get from b1 to c3 takes 1 knight moves.
To get from f6 to f6 takes 0 knight moves.
代码
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<queue>
using namespace std;
int bu[8][2]={{2,1},{2,-1},{1,2},{1,-2},{-1,2},{-1,-2},{-2,1},{-2,-1}};
struct l
{
int x;
int y;
int step;
};
int main()
{
char n[3],m[3];
int book[12][12];
while(~scanf("%s %s",n,m))
{
memset(book,0,sizeof book);
int q=m[0]-'a';
int w=m[1]-'1';
struct l lp;
lp.x=n[0]-'a';
lp.y=n[1]-'1';
lp.step=0;
book[lp.x][lp.y]=1;
queue<l>p;
p.push(lp);
while(!p.empty())
{
struct l o;
o=p.front();
p.pop();
if(o.x==q&&o.y==w)
{
printf("To get from %s to %s takes %d knight moves.\n",n,m,o.step);
break;
}
for(int i=0;i<8;i++){
int tx,ty;
tx=o.x+bu[i][0];
ty=o.y+bu[i][1];
if(tx<0||ty<0||tx>=8||ty>=8||book[tx][ty])
continue;
book[tx][ty]=1;
struct l h;
h.x=tx;
h.y=ty;
h.step=o.step+1;
p.push(h);
}
}
}
}