HDU 1030 Delta-wave(找规律)

来源:互联网 发布:乐福数据 编辑:程序博客网 时间:2024/06/05 15:11

Delta-wave

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


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
 

Source

Ural Collegiate Programming Contest 1998


因为刚刚做过1026的搜索,所以这一题刚看到时想的便是广搜,大致想了一下思路,就准备开始写;

但是看了输入数据有9次方,下意识觉得搜索会超时,这一题应该不是搜索题;

重新看了一遍题目,因为只要和数塔有关的都肯定有规律,所以觉得这是一道规律题;

刚开始我只从左列和右列两个角度去看,从m到n只需要先从m所在的左列移动到n所在的左列,再从m所在的右列移动到n所在的右列即可;

但是我试了很长时间,发现只有左右列并不能解决问题,于是改变了一下思路,将m、n所在的层数也考虑进来,终于找到规律;

1、找到m、n所在层:ci=ceil(sqrt(i))(向上取整函数)(可参考:c/c++取整函数)

2、找到m、n所在左列:li=(ci*ci-i)/2+1

3、找到m、n所在右列:ri=(i-(ci-1)*(ci-1)-1)/2+1

4、求三者差值和即为结果:result=fabs(cm-cn)+fabs(lm-ln)+fabs(rm-rn)


#include <iostream>#include <cstdio>#include <cstdlib>#include <cmath>using namespace std;int main(){    int m,n;    int cm,cn;    int lm,ln;    int rm,rn;    while(~scanf("%d%d",&m,&n)){        cm=ceil(sqrt(m));        cn=ceil(sqrt(n));        lm=(cm*cm-m)/2+1;        ln=(cn*cn-n)/2+1;        rm=(m-(cm-1)*(cm-1)-1)/2+1;        rn=(n-(cn-1)*(cn-1)-1)/2+1;        int result=fabs(cm-cn)+fabs(lm-ln)+fabs(rm-rn);        printf("%d\n",result);    }    return 0;}