Description
原题
如上图所示

螺旋折线经过平面上所有整点恰好一次。
对于整点(X, Y),我们定义它到原点的距离dis(X, Y)是从原点到(X, Y)的螺旋折线段的长度。
例如dis(0, 1)=3, dis(-2, -1)=9
给出整点坐标(X, Y),你能计算出dis(X, Y)吗?

Input

X和Y
对于40%的数据,-1000 <= X, Y <= 1000
对于70%的数据,-100000 <= X, Y <= 100000
对于100%的数据, -1000000000 <= X, Y <= 1000000000

Output

输出dis(X, Y)

Sample Input 1
0 1
Sample Output 1
3
稍微研究了下感觉更像是一个数学题啊。。。先判断这个点是在第几个正方形上,然后就是前面n-1个正方形周长加上现在的不完整的长度。

#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
  long long x, y;
  long long count = 0;
  cin >> x >> y;
  long long n = abs(x) > abs(y) ? abs(x) : abs(y);
  //cout << "这是第" << n << " 个正方形的点"<< endl;
  count = (8 + (n - 1) * 2 * 4)*(n - 1) / 2;   //前面n个正方形的周长和
  long long xtmp = -1 * n;
  long long ytmp = -1 * n + 1;
  if (x == xtmp && y >= ytmp)
  {
    count += y - ytmp;
  }
  else
  {
    count += 2 * n - 1;   //先加个高度,这一段是必须要有的
    if (y == n)
    {
      count += x - xtmp;
    }
    else
    {
      count += 2 * n; //同上,这一段也加上
      if (x == n)
      {
        count += n - y;
      }
      else
      {
        count += 2 * n;
        count += n - x;
      }
    }
  }
  cout << count + 1 << endl;
  system("pause");
  return 0;
}
最后修改:2022 年 04 月 01 日
如果觉得我的文章对你有用,请随意赞赏