原题:
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.
题意:
给出入上图的一个三角形,要求出从一个数到另外一个数需要跨过多少道界线,且在小三角形中只能穿过三角形的三条边,不能从顶点穿过。例如从6到12需要穿过三条边。
题解:
按照三角形的水平(1),从左上到右下(2),从右上到左下(3)三个方向进行划分,会发现实际上要穿过的边界就是三个方向上行数的差值之和,例如6和12,在(1)方向差为一行,在(2)方向上差值为1行,在(3)方向上差值为一行,所以总共为3行。难点可能就在于推导(2)(3)方向的通项公式了。
代码:AC
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int n,m;
while(cin>>m>>n)
{
int mlev=sqrt(m-1)+1;
int nlev=sqrt(n-1)+1;
int lev=abs(mlev-nlev);
int mleft=(mlev*mlev-m)/2+1;
int nleft=(nlev*nlev-n)/2+1;
int left=abs(mleft-nleft);
int mright=(m-(mlev-1)*(mlev-1)-1)/2+1;
int nright=(n-(nlev-1)*(nlev-1)-1)/2+1;
int right=abs(mright-nright);
cout<<lev+left+right<<endl;
}
return 0;
}