Delta-wave

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

题目解析

  • 题目大意:让数字按照如图所示的顺序排列成一个三角形,每个数字被圈在一个小三角形内。
  • 问: 给你两个数M、N;
  • 求:从M位置到N位置,需要跨越的边有多少条。(只能通过边,不能跨顶点)
  • 方法:找规律。
  • 核心:三维坐标映射。
    如图:
    三维坐标映射图
    根据规律找到每个点的三维坐标(一,/\)(顺序自定义)

之后我们就根据规律发现M(x1,y1,z1)到N(x2,y2,z2)跨越的边 = abs(x1-x2)+(y1-y2)+(z1-z2)

总结:抛开固有思想,灵活运用映射!

解题代码

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int fun(int x){
	for(int i = 1; i < sqrt(1000000000)+1; i++){
		if(x>(i-1)*(i-1)&&x<=i*i)
		return i;
	}
}

int main(){
	int m,n;
	while(scanf("%d %d",&m,&n)!=EOF){
		int x1,y1,z1;
		int x2,y2,z2;
		int num;
		x1 = fun(m);
		y1 = (m-((x1-1)*(x1-1)+1))/2+1;
		z1 = x1 - ((m - ((x1-1) * (x1-1) + 1))+1)/2;
	
		x2 = fun(n);
		y2 = (n-((x2-1)*(x2-1)+1))/2+1;
		z2 = x2 - ((n - ((x2-1) * (x2-1) + 1))+1)/2;
		num = abs(x1-x2)+abs(y1-y2)+abs(z1-z2);
		printf("x1=%d y1=%d z1=%d\n", x1,y1,z1);
		printf("x2=%d y2=%d z2=%d\n", x2,y2,z2); 
		printf("%d\n", num);
		
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值