Hduoj1030【数学】

Delta-wave

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


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
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
int main()
{
	int i, j, k, n, m;
	while(scanf("%d%d", &n, &m) != EOF)
	{
		int x1, y1 = 1, x2, y2 = 1 ,up1 , up2 ;
		k = sqrt(n);
		if(k * k == n)
		{
			j = (k-1)*(k-1) + 1;
			x1 = k; 
		}
		else
		{
			j = k*k + 1;
			x1 = k+1;
		}
		up1 = x1;
		int flag = 0;
		while(j < n)
		{
			j++; 
			if(flag == 0)
			{
				flag = 1;
				x1--;
			}
			else
			{
				flag = 0;
				y1++;
			}
		}
		k = sqrt(m);
		if(k * k == m)
		{
			j = (k-1)*(k-1) + 1;
			x2 = k;
		}
		else
		{
			j = k*k + 1;
			x2 = k+1;
		}
		up2 = x2;
		flag = 0;
		while(j < m)
		{
			j++;
			if(flag == 0)
			{
				flag = 1;
				x2--;
			}
			else
			{
				flag = 0;
				y2++;
			}
		}
		
		int sum = (abs(x1 - x2) + abs(y1 - y2) )  + abs(up1 - up2);
		printf("%d\n", sum);
	}
	return 0;
}

题意:给出上图,求数字n到m所需要经过的边数。
思路:按照左斜边和右斜边分别设为x坐标和y坐标,计算出每个数字所在的菱形所在的坐标,对于移动的话就是按照菱形移动是一条边,其次就是每个菱形之中还有一条边需要穿越,就相当于ans = abs(x1-x2) + abs(y1-y2) + abs(层数 - 层数);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值