杭电1030 Delta-wave (找规律)

题目:

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(其中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;
}
				


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值