题目描述
如图所示的螺旋折线经过平面上所有整点恰好一次。
对于整点(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);
写的麻烦了。