POJ 1030 Delta-wave

来源:互联网 发布:软件工程技术的应用 编辑:程序博客网 时间:2024/06/06 10:51

Delta-wave

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



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
 


题解:

在看这题之前,我们先看下一个简单的题目

 <1>

图示两个点,如果只能横向或者纵线走,从A到B的步数为(5-2)+(3-1)=5

在此坐标系中,每个方格有两个方向(横向、纵向,即x,y方向)

那么在此题中,不难看出每个三角形有三个方向(x,y,z)

X方向   


Y方向   


Z方向  


有了这些基础之后,我们需要求解的就是在某点在各个方向上面的位置

例如:点n在三个方向的坐标为:

X=(int)sqrt(n-1)+1;

Y= (n - (X-1)*(X-1)+1)/2;

Z= (X*X - n)/2+1;

下面就是我个人对以上得出的公式的推导过程:

首先,X表示点n所在位置从上到下为第X层,Y表示点n所在位置从左上到右下第Y层,Z表示点n所在位置从右上到左下第Z层。

观察每一行的点,不难发现规律:

1.每一行最后一个数都是该行的平方值。

2.对于求某一点左上到右下是第几层,等于该点的值减去所在的上一行最后一个数之后加上1,再除以2(为什么要除以2和加1呢?下面再细说)。

3.对于求某一点右上到左下是第几层,等于该点所在行最后一个数减去该点的值之后除以2,再加上1(为什么要除以2和加1呢?下面再细说)。

解释:

除了第一行外,对其他任意一行上的一点,无论该点左上到右下或从右上到左下,总有一个与它同在一个水平方向上(即同行)并与它相邻的点属于同一层次,即左上到右下或从右上到左下这两个方向上有两个水平方向相邻的数是在同一层上,因此求一点在这两个方向是第几层都要除以2。加1主要是由该点的位置及以上条件所决定的,这样确保所求位置方向坐标准确。读者可参考上图加以理解,我就不赘诉了。。。



#include<stdio.h>       #include<iostream>#include<algorithm>#include<string.h>#include<stdlib.h>#include<time.h>#include<math.h>#include<map>#include<queue>;#include<stack>;using namespace std;int fun1(int n){    return (int)sqrt(n-1)+1;}int fun2(int n){    return (n-(fun1(n)-1)*(fun1(n)-1)+1)/2;}int fun3(int n){    return (fun1(n)*fun1(n)-n)/2+1;}int main(){    int m,n;    while(cin>>n>>m)    {        int x1,x2,y1,y2,z1,z2;        x1=fun1(n);        y1=fun2(n);        z1=fun3(n);        x2=fun1(m);        y2=fun2(m);        z2=fun3(m);//        printf("%d %d %d %d %d %d \n",x1,y1,z1,x2,y2,z2);        int s=abs(x1-x2)+abs(y1-y2)+abs(z1-z2);        cout<<s<<endl;    }}



0 0