题目描述
X星球居民小区的楼房全是一样的,并且按矩阵样式排列。
其楼房的编号为1,2,3… 当排满一行时,从下一行相邻的楼往反方向排号。
比如:当小区排号宽度为6时,开始情形如下:
1 2 3 4 5 6
12 11 10 9 8 7
13 14 15 …
我们的问题是:已知了两个楼号m和n,需要求出它们之间的最短移动距离
(不能斜线方向移动)
输入
输入存在多组测试数据
输入为3个整数w m n,空格分开,都在1到10000范围内
w为排号宽度,m,n为待计算的楼号。
输出
要求输出一个整数,表示m n 两楼间最短移动距离。
样例输入
6 8 2
4 7 20
样例输出
4
5
import java.util.Scanner;
public class Main_1261 {
static Scanner cin = new Scanner(System.in);
public static void main(String[] args) {
// TODO 自动生成的方法存根
while(cin.hasNext()) {
int w = cin.nextInt();
int m = cin.nextInt();
int n = cin.nextInt();
//记录距离
int step;
step = Math.abs(dis(w,m).x-dis(w,n).x)+Math.abs(dis(w,m).y-dis(w,n).y);
System.out.println(step);
}
}
private static node dis(int w,int temp) {
// TODO 自动生成的方法存根
node abc = new node();
abc.x = temp/w;
if (abc.x%2==0) {
if (temp%w==0) {
abc.y = w-1;
}else {
abc.y = temp%w-1;
}
}else {
if (temp%w==0) {
abc.y=0;
}else {
abc.y =Math.abs(w-temp%w) ;
}
}
return abc;
}
}
//类似于C++的结构体
class node{
//x y 分别代表行和列的数值 我以0为开始
int x;
int y;
}