您的位置:首页 > 其它

杭电1030 Delta-wave (找规律)

2013-01-04 21:59 169 查看
题目:

[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(其中m是较小的那个数)是该层的奇数项,那判断n是否在以m为顶点的三角范围内,若在则步数=2*相差层数-1+(或-,根据n是该层的奇偶项判断)1;若m为偶数项,则在前面公式上再加1,而此时三角范围则是m-1和m+1的并;当n不在范围内时,只要在上面判断后的式子基础上再加上n与三角范围边界的差即可。如下图,m=4
n=10,步数=2*2-1+1+|10-12|=6。





用mlay,nlay记录m,n所在的层;lay=nlay-mlay

mnum,nnum记录m,n在其所在层的位置

1、如果mnum为偶数,flag=1

left=m-1+(2*mlay+lay-2)*lay

right=m+1+(2*mlay+lay)*lay

如果mnum为奇数,flag=0

left=m+(2*mlay+lay-2)*lay

right=m+(2*mlay+lay)*lay

2、如果n>=left&&n<=right

2.1、如果nnum为偶数 out=2*lay-1+flag

2.2、如果nnum为奇数 out=2*lay-1+1+flag

3、如果n<left

out=out=2*lay-1+1+flag+left-n

4、如果n>right

out=2*lay-1+1+flag+n-right

代码:

#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;

void swap(long &m,long &n)
{
if(m>n)
{
long temp=m;
m=n;
n=temp;
}
}

void getlaynum(long n,long &lay,long &num)//得到数字所在的层和在该层的位置
{
double f;
f=sqrt((double)n);
lay=(long)ceil(f);
num=n-(lay-1)*(lay-1);
}

int main()
{
long m,n;
long laym,numm,layn,numn,lay;
long left,right,flag,s;
while(cin>>m>>n)
{
s=left=right=0;
swap(m,n);
getlaynum(m,laym,numm);
getlaynum(n,layn,numn);

if(layn==laym)
{
cout<<numn-numm<<endl;
continue;
}
else
{
lay=layn-laym;

//先判断m 在该层中的位置
if(numm%2!=0)
{
flag=0;    //表示m是奇数
left=m+(2*laym+lay-2)*lay;
right=m+(2*laym+lay)*lay;
}
else    //m为偶数时
{
flag=1;
left=m-1+(2*laym+lay-2)*lay;
right=m+1+(2*laym+lay)*lay;
}

//再判断n 是否在m所确定的三角形中
if(n>=left&&n<=right)
{
if(numn%2==0)
{
s=2*lay-1+flag;
}
else
s=2*lay-1+1+flag;
}
else if(n<left)
{
s=2*lay-1+1+flag+left-n;
}
else if(n>right)
s=2*lay-1+1+flag+n-right;
}
cout<<s<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: