1237. 螺旋折线

题目链接

1237. 螺旋折线

如下图所示的螺旋折线经过平面上所有整点恰好一次。

image

对于整点 \((X,Y)\),我们定义它到原点的距离 \(dis(X,Y)\) 是从原点到 \((X,Y)\) 的螺旋折线段的长度。

例如 \(dis(0,1)=3,dis(−2,−1)=9\)

给出整点坐标 \((X,Y)\),你能计算出 \(dis(X,Y)\) 吗?

输入格式

包含两个整数 \(X,Y\)

输出格式

输出一个整数,表示 \(dis(X,Y)\)

数据范围

\(−10^9≤X,Y≤10^9\)

输入样例:

0 1

输出样例:

3

解题思路

模拟,找规律

image这种形状作为周期,这种形状的等差长度为 \(8\),找出第几个这样的形状,以及从开始点到终点的距离即可

  • 时间复杂度:\(O(1)\)

代码

// Problem: 螺旋折线
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/1239/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

// %%%Skyqwq
#include <bits/stdc++.h>
 
#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
 
typedef long long LL;
typedef pair<int, int> PII;
 
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
 
template <typename T> void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

int x,y;
signed main()
{
    cin>>x>>y;
    int n=max(abs(x),abs(y));
    if(!(x<=0&&y<0))
    	n--;
    else
    {
    	if(-x>-y)n--;
    }
    LL res=0;
    res+=1ll*n*(4*n+3);
    LL t=0;
    if(x<=0&&y<=0)
    {
    	t+=-x+y+n;
    }
    else if(x<=0&&y>=0)
    {
    	t+=n+n+1;
    	t+=y+x+n+1;
    }
    else if(x>=0&&y>=0)
    {
    	t+=n+n+1+n+1+n+1;
    	t+=x+n+1-y;
    }
    else
    {
    	t+=n+n+1+n+1+n+1+n+1+n+1;
    	t+=-y+n+1-x;
    }
    cout<<res+t;
    return 0;
}
posted @ 2022-02-13 15:42  zyy2001  阅读(74)  评论(0编辑  收藏  举报