Delta-wave
題目描述
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
思路:
題意:給定一個如圖所示的三角形,裏面用連續的數字進行填充,給定兩個數N,M,求從N到M的最短路線長度(只允許走邊);
這題一開始並沒啥思路,參考大佬的題解,非常受教!【Delta-wave的題解】
代碼
#include <stdio.h>
#include <cmath>
using namespace std;
int main()
{
int N,M;
while(scanf("%d%d",&N,&M)!=EOF){
int N_x=(int)sqrt(N-1)+1;
int N_y=(N-(N_x-1)*(N_x-1)+1)/2;
int N_z=(N_x*N_x-N)/2+1;
int M_x=(int)sqrt(M-1)+1;
int M_y=(M-(M_x-1)*(M_x-1)+1)/2;
int M_z=(M_x*M_x-M)/2+1;
int s=abs(N_x-M_x)+abs(N_y-M_y)+abs(N_z-M_z);
printf("%d\n",s);
}
return 0;
}