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.

Hduoj1030【数学】_第1张图片

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 
#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(层数 - 层数);

你可能感兴趣的:(Hduoj1030【数学】)