Problem Description
A triangle field is numbered with successive integers in the way shown on the picture below.
The traveller needs to go from the cell with number M to the cell with number N. The traveller is able to enter the cell through cell edges only, he can not travel from cell to cell through vertices. The number of edges the traveller passes makes the length of the traveller’s route.
Write the program to determine the length of the shortest route connecting cells with numbers N and M.
Input
Input contains two integer numbers M and N in the range from 1 to 1000000000 separated with space(s).
Output
Output should contain the length of the shortest route.
Sample Input
6 12
Sample Output
3
java代碼如下
import java.util.Scanner;
public class P1030 {
public static void main(String[] args) {
new P1030().run();
}
private void run() {
Scanner scanner = new Scanner(System.in);
int m;
int n;
while (scanner.hasNextInt()) {
m = scanner.nextInt();
n = scanner.nextInt();
if (m > n) {
int temp = 0;
temp = m;
m = n;
n = temp;
}
int rm = getRow(m);
int lm = getColumn(m, rm);
int rn = getRow(n);
int ln = getColumn(n, rn);
int out = 0;
// 偶數時爲倒三角形位置,將起點定位到上一個
if (lm % 2 == 0) {
rm -= 1;
lm -= 1;
out -= 1;
}
// st到en表示終點所在行,起點的控制範圍
int st = lm;
int en = lm + (rn - rm) * 2;
if (st <= ln && ln <= en) { // 終點在可控制範圍內
if (ln % 2 != 0)
out += 2 * (rn - rm);
else {
out += 2 * (rn - rm) - 1;
}
} else { // 終點在可控制範圍外
if (ln < st) { // 可控範圍的左邊
if (st % 2 != 0)
out += 2 * (rn - rm);
else {
out += 2 * (rn - rm) - 1;
}
out += /* 2 * (rn - rm) + */st - ln;
}
if (ln > en) { // 可控範圍的右邊
if (en % 2 != 0)
out += 2 * (rn - rm);
else {
out += 2 * (rn - rm) - 1;
}
out += /* 2 * (rn - rm) + */ln - en;
}
}
System.out.println(out);
}
scanner.close();
}
private int getRow(int v) {
return (int) Math.ceil(Math.sqrt(v));
}
private int getColumn(int v, int r) {
return v - (r - 1) * (r - 1);
}
}