HDU 1030 Delta-wave 数学题解

Delta-wave

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5782    Accepted Submission(s): 2204


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

一条能够利用建立坐标系做的题目。

引用:http://acm.hdu.edu.cn/discuss/problem/post/reply.php?

postid=18719&messageid=1&deep=0

我们把上下两个相连的三角形构成的菱形看做一个格,左斜线看做横坐标,右斜线看做纵坐标,也是四个方向(0,-1),(0,1),(-1,0),(1,0)变化,那么就相当于直角坐标了。

从(x1,y1)到(x2,y2),这是斜角坐标,距离dis=abs(x1-x2)+abs(y1-y2);我们还须要考虑菱形中的移动,这个都是一层移动一次。

所以答案ans=dis+abs(a-b)=abs(x1-x2)+abs(y1-y2)+abs(a-b)。当中a和b表示各自层数,x1,y1,x2,y2表示两个数所在菱形在斜角坐标系的位置。

利用这个思路敲代码就非常easy的了。

只是为什么这样会正确?好像还是非常难解析清楚。我理解这是一个规律,跨过了两个不同的斜边。就会得到最短的路径了,由于本题一定要走边,不能走顶点跨到下一个三角形的,故此上下左右的边的最小相隔边数,就是题目要求的最短距离数了。也就能够想象为跨过三角形的三个边,三个方向的边,刚好是上下的h高度边。左斜线的x边。右斜线的y边,(有人也喜欢用x,y。z)那么就肯定是最短路径了。


也能够直接利用数学的方法,然后加点暴力法算出来的,之前做过,不反复了。

#include <stdio.h>
#include <vector>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <string>
#include <limits.h>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <math.h>
using namespace std;

int main()
{
	int n, m;
	while (scanf("%d %d", &n, &m) != EOF)
	{
		int nh = (int)sqrt(double(n-1));
		int mh = (int)sqrt(double(m-1));

		int nx = (n - nh*nh - 1) >> 1;
		int mx = (m - mh*mh - 1) >> 1;

		int ny = ((nh + 1) * (nh + 1) - n) >> 1;
		int my = ((mh + 1) * (mh + 1) - m) >> 1;

		printf("%d\n", abs(nh-mh) + abs(nx-mx) + abs(ny-my));
	}
	return 0;
}



版权声明:笔者心脏靖,景空间地址:http://blog.csdn.net/kenden23/。可能不会在未经作者同意转载。

转载于:https://www.cnblogs.com/bhlsheji/p/4652403.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值