【水讨论】#53 A. Square Earth?

本文探讨了在正方形边上确定两点间最短路径的问题,提供了详细的解析思路及代码实现,适用于竞赛编程与算法研究。

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

A. Square Earth?
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Meg the Rabbit decided to do something nice, specifically — to determine the shortest distance between two points on the surface of our planet. But Meg... what can you say, she wants everything simple. So, she already regards our planet as a two-dimensional circle. No, wait, it's even worse — as a square of side n. Thus, the task has been reduced to finding the shortest path between two dots on a square (the path should go through the square sides). To simplify the task let us consider the vertices of the square to lie at points whose coordinates are: (0, 0)(n, 0)(0, n) and (n, n).

Input

The single line contains 5 space-separated integers: n, x1, y1, x2, y2 (1 ≤ n ≤ 1000, 0 ≤ x1, y1, x2, y2 ≤ n) which correspondingly represent a side of the square, the coordinates of the first point and the coordinates of the second point. It is guaranteed that the points lie on the sides of the square.

Output

You must print on a single line the shortest distance between the points.

Sample test(s)
input
2 0 0 1 0
output
1
input
2 0 1 2 1
output
4
input
100 0 0 100 100
output
200


有一个n为边长的正方形边上有两个点,问只能走正方形边界的情况下最短路程是多长(顺时针A到B或者逆时针A到B咯~)。

好吧……分情况讨论好了……

我们把这个正方形从左下到右上分为两半,然后——

1) 两个点在同侧的话,就坐标(x+y)的差即可,记住abs取绝对值

2) 在不同侧的话,就两个方向看看哪个小咯~一侧为x1+y1+x2+y2,另一侧就直接正方形周长4n来减去前面那个就好。

Code:

#include <cstdio>
#include <memory>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
	int n,x1,y1,x2,y2;
	cin>>n>>x1>>y1>>x2>>y2;
	int len1=x1+y1,len2=x2+y2; 
	//if((x1-y1)*(x2-y2)>=0) dist=abs(x1+y1-x2-y2); 	// 两点在 y=x 同侧 
	//else dist=x1+y1+x2+y2;				// 两点在 y=x 异侧 
	int dist=abs( x1+y1-( (x1-y1)*(x2-y2)>=0 ? (x2+y2):(-x2-y2) ) );
	cout<<min(dist,4*n-dist)<<endl;
	return 0;
}





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

糖果天王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值