POJ 1657 Distance on Chessboard

时间限制: 
1000m
内存限制: 
65536kB
描述
国际象棋的棋盘是黑白相间的8 * 8的方格,棋子放在格子中间。如下图所示:

王、后、车、象的走子规则如下:
  • 王:横、直、斜都可以走,但每步限走一格。
  • 后:横、直、斜都可以走,每步格数不受限制。
  • 车:横、竖均可以走,不能斜走,格数不限。
  • 象:只能斜走,格数不限。


写一个程序,给定起始位置和目标位置,计算王、后、车、象从起始位置走到目标位置所需的最少步数。
输入
第一行是测试数据的组数t(0 <= t <= 20)。以下每行是一组测试数据,每组包括棋盘上的两个位置,第一个是起始位置,第二个是目标位置。位置用"字母-数字"的形式表示,字母从"a"到"h",数字从"1"到"8"。
输出
对输入的每组测试数据,输出王、后、车、象所需的最少步数。如果无法到达,就输出"Inf".
样例输入
2a1 c3f5 f8
样例输出
2 1 2 13 1 1 Inf
 
 
(1)、源代码:
#include <iostream>
#include <string>
#include <cmath>

using namespace std;

int main()
{
     int group = 0, i;
     cin >> group;
     string add1, add2;
     int x, y;
     for(i = 0; i < group; i++){
          cin >> add1 >> add2;
          x = abs(add1[0] - add2[0]);
          y = abs(add1[1] - add2[1]);
          if(x==0 && y ==0)
               cout << "0 0 0 0" << endl;
          else{
               if(x < y)
                    cout << y;
               else
                    cout << x;
               if((x==y) || (x==0) || (y==0))
                    cout << " 1";
               else
                    cout << " 2";
               if((x==0) || (y==0))
                    cout << " 1";
               else
                    cout << " 2";
               if(((x + y) % 2) != 0)
                    cout << " Inf" << endl;
               else if(x == y)
                    cout << " 1" << endl;
               else
                    cout << " 2" << endl;
          }
     }
     return 0;
}
 
(2)、解题思路:分别分析王、后、象、车的情况即可。略
(3)、出现错误:compile error
995337.122487/Main.cc:32:19: error: invalid operands of types ‘__gnu_cxx::__enable_if<true, double>::__type’ and ‘int’ to binary ‘operator%’
 
出现这个错误是在if((x+y) % 2 != 0)时,如果这里的x+y换成abs(x-y)则会报错,原因是g++把abs()中的int转换成了double类型了。在g++中使用abs()函数总是会出错。解决办法是在头文件中加入“stdlib.h”,这道题也可以将abs(x-y)换成x+y。
 
 
 
 
posted on 2012-05-11 20:20  谷堆旁边  阅读(377)  评论(0编辑  收藏  举报