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
题目解析
- 题目大意:让数字按照如图所示的顺序排列成一个三角形,每个数字被圈在一个小三角形内。
- 问: 给你两个数M、N;
- 求:从M位置到N位置,需要跨越的边有多少条。(只能通过边,不能跨顶点)
- 方法:找规律。
- 核心:三维坐标映射。
如图:
根据规律找到每个点的三维坐标(一,/,\)(顺序自定义)
之后我们就根据规律发现M(x1,y1,z1)到N(x2,y2,z2)跨越的边 = abs(x1-x2)+(y1-y2)+(z1-z2)
总结:抛开固有思想,灵活运用映射!
解题代码
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int fun(int x){
for(int i = 1; i < sqrt(1000000000)+1; i++){
if(x>(i-1)*(i-1)&&x<=i*i)
return i;
}
}
int main(){
int m,n;
while(scanf("%d %d",&m,&n)!=EOF){
int x1,y1,z1;
int x2,y2,z2;
int num;
x1 = fun(m);
y1 = (m-((x1-1)*(x1-1)+1))/2+1;
z1 = x1 - ((m - ((x1-1) * (x1-1) + 1))+1)/2;
x2 = fun(n);
y2 = (n-((x2-1)*(x2-1)+1))/2+1;
z2 = x2 - ((n - ((x2-1) * (x2-1) + 1))+1)/2;
num = abs(x1-x2)+abs(y1-y2)+abs(z1-z2);
printf("x1=%d y1=%d z1=%d\n", x1,y1,z1);
printf("x2=%d y2=%d z2=%d\n", x2,y2,z2);
printf("%d\n", num);
}
}