L - Delta-wave(HDU 1030)

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的最小步数。只能在大三角形内穿过短边,不能通过定点,穿过短边数目为步数。

思路:

  • 实例模拟:假设N点为3,M点为7,可以让N点斜向左下一格,使N,M在斜右下方向上处于同一列,再让N向下一格,使处于同一行,N再斜向右下一格,到达M点。
  • 发现:要使N,M重合,必须使之处于同一行,在斜右下方向处于同一列,在斜左下方向处于同一列。所以定义三个坐标(行,斜左下列,斜右下列),各个坐标之差的绝对值之和就是最小移动步数。斜左下列从右上往左下数,斜右下列从左上往右下数。
Code
#include <iostream>
#include <math.h>

using namespace std;

int main()
{
	int m, n;
	while (cin >> m >> n)
	{
		int a1 = sqrt(m - 1) + 1;//行坐标
		int a2 = sqrt(n - 1) + 1;
		int b1 = (m - (a1 - 1) * (a1 - 1) + 1) / 2;//斜左坐标
		int b2 = (n - (a2 - 1) * (a2 - 1) + 1) / 2;
		int c1 = (a1 * a1 - m + 2) / 2;//右斜坐标
		int c2 = (a2 * a2 - n + 2) / 2;

		cout << abs(a1 - a2) + abs(b1 - b2) + abs(c1 - c2) << endl;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值