【Gym - 100947G】Square Spiral Search

BUPT 2017 summer training (for 16) #1C

题意

A new computer scientist is trying to develop a new memory management system called "spiral memory management".

The basic idea of this system is that it represents the memory as a 2D grid with a predefined origin point, and the address of each memory location is represented as its (x,y) coordinates, and it tries to store frequently used data as close to the origin point as possible.

This system needs a search algorithm. Our computer scientist is currently developing an algorithm called "square spiral search".

The algorithm searches the memory locations in the following order (also shown in the figure):

(0,0), (1,0), (1,1), (0,1), (-1,1), (-1,0), (-1,-1), (0,-1), (1,-1), (2,-1), (2,0), (2,1), (2,2), (1,2), (0,2), (-1,2), (-2,2), (-2,1), (-2,0), (-2,-1), (-2,-2,) ,(-1,-2) ... and so on.

a030df840f82cea67c87b6c9233a4386?v=1500206291
Now he is wondering: how many steps would it take to reach a memory location with the address (x, y) using the square spiral search. Can you help him find the answer?

题解

代码

#include <cstdio>
#include <cmath>
#include <algorithm>
#define ll long long
using namespace std;
int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        int x,y;
        scanf("%d%d",&x,&y);
        if(!x&&!y){
            puts("0");continue;     
        }
        ll s=max(abs(x),abs(y)),ans=(s*2+1)*(s*2+1)-1;
        if(y==-s)
            ans-=(s-x);
        else if(x==-s)
            ans-=s*2+(s+y);
        else if(y==s)
            ans-=s*4+(s+x);
        else
            ans-=s*6+(s-y);
        printf("%lld\n",ans);
    }
    return 0;
}

转载于:https://www.cnblogs.com/flipped/p/7202341.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值