首页 > 代码库 > hdu 1030
hdu 1030
Delta-wave
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5611 Accepted Submission(s): 2137
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.
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
找规律题:
题意:给你两个值,n,m让你找到从n到m的最短路径并将最短路径的步骤数输出来:
思路:观察题上的图形:可以看到第一行有一个数,第二行有三个数,第三行有五个数,依次类推往后,成公差为二的等差数列
等差数列和为n^2
要想找到最短路径需要找到两个是否在同一层,是否在同一斜列:观察可以看出每行的最右边的数是平方和的形式,所以确定行数可以用ceil函数来确定。左边的第一斜列的数分别是1,3,2,6,5,11,10……右边的第一斜列是1,3,4,8,9……计算左边的斜列数可以用
(a-I(len1-1)*(len1-1)-1)/2+1来求得,就是那右边的可以用(len1*len1-a)/2+1进行求解
代码如下:
<span style="font-size:14px;">#include<stdio.h>#include<math.h>int main(){ int a,b; while(~scanf("%d%d",&a,&b)) { int lefta,leftb,righta,rightb,len1,len2,sum; len1=ceil(sqrt(a));len2=ceil(sqrt(b)); lefta=(a-(len1-1)*(len1-1)-1)/2+1; leftb=(b-(len2-1)*(len2-1)-1)/2+1; righta=(len1*len1-a)/2+1; rightb=(len2*len2-b)/2+1; sum=fabs(len1-len2)+fabs(lefta-leftb)+fabs(righta-rightb); printf("%d\n",sum); } return 0;}</span>
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。