日历
网志分类
· 所有网志 (41)
· ZOJ ACS (36)
· ZOJ EASY (5)
· ZOJ Medium (0)
· ZOJ HARD (0)
站内搜索
友情链接
· 我的歪酷

订阅 RSS

0023167

歪酷博客

linkmm's ACM world


« 上一篇: ZOJ 1061: Web Navigation
四年缘尽 @ 2006-06-24 01:18

Knight Moves

Time limit: 1 Seconds   Memory limit: 32768K  
Total Submit: 1163   Accepted Submit: 635  

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 Specification

The input file will contain one or more test cases. Each test case consists of one line containing two squares separated by one space. A square is a string consisting of a letter (a-h) representing the column and a digit (1-8) representing the row on the chessboard.

Output Specification

For each test case, print one line saying "To get from xx to yy takes n knight moves.".

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.



问跳马步到定点的最小步数。可以判重BFS,也可以用公式。
#include <iostream>
#include <string>
using namespace std;

int minKightStep(int a, int b){ //a >= 0 && b >= 0
 if(a > b) swap(a, b);
 if(a == 0){
  if(b == 0) return 0;
  if(b == 1) return 3;
  if(b == 2) return 2;
  if(b == 6) return 4;
 }
 if(a == 1 && b == 4) return 3;
 if(a == 2 && b == 2) return 4;

 int u = min(min((a+b) / 3, (2*a+b) / 4) , (a+2*b) / 4);
 return a+b-2*u;

}

int main()
{
 string s1,s2;
 int ax,ay,bx,by;

 while(cin >> s1 >> s2)
 {
  if ( s1 == s2 )
  {
   cout << "To get from " << s1 << " to " << s2 << " takes 0 knight moves.";
   continue;
  }

  ax = s1[0]-'a';
  ay = s1[1]-'1';
  bx = s2[0]-'a';
  by = s2[1]-'1';

  cout << minKightStep(ax*8+ay,bx*8+by) << endl;
 }

}




最新评论


tt

2007-02-04 22:40 匿名 125.90.*.*

怎么结果都不对?


评论 / 个人网页 / 扔小纸条
*昵称

已经注册过? 请登录

Email
网址
*评论