码迷,mamicode.com
首页 > 其他好文 > 详细

hdu 1030

时间:2014-08-05 19:24:20      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:杭电   数学   acm   c   math.h   

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.

bubuko.com,布布扣


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>

hdu 1030,布布扣,bubuko.com

hdu 1030

标签:杭电   数学   acm   c   math.h   

原文地址:http://blog.csdn.net/ice_alone/article/details/38388397

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!