Connection Status:
Competition Arena > GridSpiral
TCO20 Round 2A · 2020-04-13 · by misof · Simple Math, Simple Search, Iteration
Class Name: GridSpiral
Return Type: long
Method Name: findCell
Arg Types: (int)
Problem Statement

Problem Statement

There is an infinite square grid. Each cell of the grid contains a non-negative integer, and each non-negative integer appears in exactly one cell.

Two cells of the grid are called adjacent if they share a side.

The integers are arranged into a spiral that starts with the number 0. For each n, the cells that contain numbers n and n+1 are adjacent. If you start at 0 and walk along the spiral, your sequence of steps will be as follows: 1 step up, 1 step right, 2 steps down, 2 steps left, 3 steps up, 3 steps right, 4 steps down, and so on.

Beginning of the spiral:

    9 10 11 12
    8  1  2 13
    7  0  3 14
..  6  5  4 15
.. .. .. .. 16

You are given the int D: a difference we want to find in the grid. Find and return the smallest x such that the cells that contain x and x+D are adjacent. If there is no such x, return -1 instead.

Notes

  • It is guaranteed that whenever an answer exists, it fits into a long.

Constraints

  • D will be between 1 and 10^9, inclusive.
Examples
0)
5
Returns: 0

Cells with values 0 and 5 are adjacent: a step down from cell 0 will take you to cell 5.

1)
11
Returns: 2

The cell with value 13 is to the right of the cell with value 2. Cells 0 and 11 are not adjacent and neither are 1 and 12, so 2 is the smallest cell with the desired property.

2)
47
Returns: 110
3)
100
Returns: -1
4)
1
Returns: 0

Submissions are judged against all 45 archived test cases, of which 5 are shown here. Case numbers match the judge’s.

Coding Area

Language: C++17 · define a public class GridSpiral with a public method long long findCell(int D) · 45 test cases · 2 s / 256 MB per case

Submitting as anonymous