一、热身 [Cloned] L - Delta-wave

本文介绍了一种在特定三角形网格中寻找两节点间最短路径的算法。该算法通过计算不同方向上的行数差来确定最短路径长度,允许旅行者仅通过单元格边而非顶点移动。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题:

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. 

题意:

给出入上图的一个三角形,要求出从一个数到另外一个数需要跨过多少道界线,且在小三角形中只能穿过三角形的三条边,不能从顶点穿过。例如从6到12需要穿过三条边。

题解:

按照三角形的水平(1),从左上到右下(2),从右上到左下(3)三个方向进行划分,会发现实际上要穿过的边界就是三个方向上行数的差值之和,例如6和12,在(1)方向差为一行,在(2)方向上差值为1行,在(3)方向上差值为一行,所以总共为3行。难点可能就在于推导(2)(3)方向的通项公式了。

代码:AC

#include<iostream>
#include<cmath>
using namespace std;
		
int main()
{
	int n,m;
	while(cin>>m>>n)
	{
		int mlev=sqrt(m-1)+1;
		int nlev=sqrt(n-1)+1;
		int lev=abs(mlev-nlev);
		int mleft=(mlev*mlev-m)/2+1;
		int nleft=(nlev*nlev-n)/2+1;
		int left=abs(mleft-nleft);
		int mright=(m-(mlev-1)*(mlev-1)-1)/2+1;
		int nright=(n-(nlev-1)*(nlev-1)-1)/2+1;
		int right=abs(mright-nright);
		cout<<lev+left+right<<endl;
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值