[CSES] Number Spiral
Number Spiral
Task:
A number spiral is an infinite grid whose upper-left square has number 1. Here are the first five layers of the spiral:
Input
The first input line contains an integer $t$: the number of tests.
After this, there are $t$ lines, each containing integers $y$ and $x$.
Output
For each test, print the number in row $y$ and column $x$.
Constraints
- $1 \le t \le 10^5$
- $1 \le y,x \le 10^9$
Input:
3
2 3
1 1
4 2
Output:
8
1
15
Solutions:
Intuition:It's easily realized that the problem follows a specific pattern. Figuring it out can be helped to predict the output.
Implementation: 1n=int(input())
2for i in range(n):
3 y,x=map(int,input().strip().split())
4 res=0
5 if y<=x:
6 if x%2==0:
7 res= (x-1)**2+1+(y -1)
8 else:
9 res=x**2-(y -1)
10 else:
11 if y%2==0:
12 res=y**2-(x-1)
13 else:
14 res=(y-1)**2+1+(x-1)
15 print(res)
16
Analysis:
Time complexity: It's straightforward that the Time complexity is O(N).
Space complexity: O(1).