HDOJ 1030 Delta-wave

7 篇文章 1 订阅
0 篇文章 0 订阅
题目:
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
 

分析:
此题要求从m到n在三角形中移动,找到最短距离。主要通过找规律。
1、规定统一方向,令较小值去找较大值。
2、求行数跳转所需的路径长度。令较小值跳转到较大值所在的行。
a.如果起始值的列为奇数,则可直接跳转到下一行。
b.行跳转的路径 = 2 X (较大值所在行 - 较小值所在行 + 1) + 1
c.较小值所在列为偶数时比奇数多1

3、求同行中,较小值移动到较大值所需的最短路径数。
a.较小值按照一直向斜向左下方移动,得到在行移动固定长度的移动数量的情况下的最左值。
b.同理,如果一直向斜向右下方移动,得到最右值。
c.如果较大值的列,在[列最大值, 列最右值]区间中,就判断是否为奇数列,是长度加1,否则直接返回已有长度。
d.如果不在该区间,就计算较大值所在的列离区间的最近的长度加到ans(已经移动的长度),返回ans
代码:
#include <iostream>
#include <cmath>
using namespace std;
int x, y;
void getLocal(int s, int& rx, int& ry)
{
	rx = (int)(ceil(sqrt(s)));
	int left = rx*rx - 2*rx + 2;
	ry = s - left + 1;
}
int getShortLen()
{
	int ans = 0;
	int rx, cx, ry, cy;
      	getLocal(x, rx, cx);
	getLocal(y, ry, cy);

	if(rx == ry)
	{
		return abs(cx - cy);
	}	
	ans += 2 * (ry - rx -1) + 1;	//求出行跳转的数量
	int left = cx  + 1;
	int right = cx + 2 * (ry-rx) - 1;
	
	if(!(cx%2))	//偶数比奇数列多1
	{
		ans++;
		left--;
		right++;
	}
	if(cy >= left && cy <= right)
	{
		if(cy%2)
		{
			return ans+1;
		}
		else
		{
			return ans;
		}
	}
	else
	{
		ans += min(abs(cy-left), abs(cy-right));
		return ans;
	}
}
int main(void)
{
	int temp;
	while(cin >> x >> y)
	{
		int ans = 0;
		if(x > y)
		{
			temp = x;
			x    = y;
			y    = temp;
		}
		ans = getShortLen();
		cout << ans << endl;
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值