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
主要找出规律,不说了,都是借鉴的!
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<cmath>
using namespace std;
int main()
{
int n,m;
while(cin>>n>>m)
{
int leven=ceil(sqrt(n));
int levem=ceil(sqrt(m));
int rigtn=(n-(leven-1)*(leven-1)+1)/2;
int rigtm=(m-(levem-1)*(levem-1)+1)/2;
int leftn=(leven*leven-n)/2;
int leftm=(levem*levem-m)/2;
// cout<<leven<<" "<<rigtn<<" "<<leftn<<endl<<levem<<" "<<rigtm<<" "<<leftm<<endl;
int sum=abs(levem-leven)+abs(rigtn-rigtm)+abs(leftn-leftm);
cout<<sum<<endl;
}
return 0;
}
本文介绍了一种用于解决从三角网格中一点到另一点最短路径的问题,通过数学方法找到两个点之间的最短路线长度。输入包含两个整数,分别代表起点和终点的位置编号,输出则是连接这两点的最短路径长度。
556

被折叠的 条评论
为什么被折叠?



