螺旋折线

题目描述
如图所示的螺旋折线经过平面上所有整点恰好一次。
对于整点(X, Y),我们定义它到原点的距离dis(X, Y)是从原点到(X, Y)的螺旋折线段的长度。
例如dis(0, 1)=3, dis(-2, -1)=9
给出整点坐标(X, Y),你能计算出dis(X, Y)吗?
在这里插入图片描述
输入
X和Y,数据在int范围以内。
输出
输出dis(X, Y)
样例输入 Copy

0 1

样例输出 Copy

3

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;

typedef long long ll;

int main() {
	ll x, y;
	cin >> x >> y;
	ll tem = max(abs(x), abs(y));
	int ix = -tem, iy = -tem;
	tem--;
	ll ans = tem * (8 + tem * 8) / 2;
	if(x == y && x < 0) {
		ans += 4 * (tem + 1) * 2;
		cout << ans << endl;
		return 0;
	}
	tem++;
	tem *= 2;
	if(x == ix) {
		ans += abs(y - iy);
	}
	else {
		ans += tem;
		iy = -iy;
		if(y == iy) {
			ans += abs(x - ix); 
		}
		else {
			ans += tem;
			ix = -ix;
			if(ix == x) 
				ans += abs(y - iy);
			else {
				ans += tem;
				iy = -iy;
				ans += abs(x - ix);
			}
		}
	}
	cout << ans << endl; 
	return 0;
} 

代码后半部分的if else之类的可以换成

	if(y > x)
		ans += x - ix + y - iy;
	else
		ans += tem * 4 - (x - ix) - (y - iy); 

写的麻烦了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值