您的位置:首页 > 其它

HDOJ 1030 Delta-wave

2015-05-04 12:16 393 查看
[align=left]题目:[/align]
[align=left]Problem Description[/align]
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.

 

[align=left]Input[/align]
Input contains two integer numbers M and N in the range from 1 to 1000000000 separated with space(s).
 

[align=left]Output[/align]
Output should contain the length of the shortest route.
 

[align=left]Sample Input[/align]

6 12

 

[align=left]Sample Output[/align]

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: