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.
![](https://i-blog.csdnimg.cn/blog_migrate/a05e0beea328a712b4c28b451785dc9a.jpeg)
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
找规律,找到了就发现很水。
从三个角度看这个图,level,left,right,如下图,题目的答案就是3个图上2个点之间的层数的高度差之和。
例如 6 12 ,level=1,left=1,right=1,答案就是3。
例如 3 12 ,level=2,left=1,right=2,答案就是6。
from:http://www.cnblogs.com/ACMan/archive/2012/05/30/2526798.html
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
while(in.hasNext()){
int n = in.nextInt();
int m = in.nextInt();
int Ln,Lm,ln,lm,rn,rm;
Ln= (int)Math.ceil(Math.sqrt(n));
Lm=(int)Math.ceil(Math.sqrt(m));
ln=(n-(Ln-1)*(Ln-1)-1)/2+1;
lm=(m-(Lm-1)*(Lm-1)-1)/2+1;
rn=(Ln*Ln-n)/2+1;
rm=(Lm*Lm-m)/2+1;
int step = (int)(Math.abs(Ln-Lm)+Math.abs(ln-lm)+Math.abs(rn-rm));
System.out.println(step);
}
}
}