I have received the following exercise from an interviewer, he didn't give the name of the problem. Honestly, I have no idea how to solve this problem even I have tried to read it three times before. Since I used to be a person who always tells myself "I am not the one good at algorithms", but giving up something too soon which I feel that I didn't spend enough effort to overcome is not my way. Then, I have sticked on it for 24 hours.
According to the given image on the problem, I tried to get more clues by searching. Thanks to Google, I found a similar problem on Hackerrank (attached link below). My target here was trying my best to just understand the problem and was trying to solve it accordingly by the Editorial on Hackerrank. Due to this circumstance, it turns me to love solving algorithms from now on (laugh). Check it out!
Problem
You are given a very organized square of size N (1-based index) and a list of S commands
The ith command will follow the format (a[i], b[i], d[i]) and will be executed as:
For every elements inside the inner-square whose top-left corner located at (a[i], b[i]) and bottom-right corner located at (a[i] + d[i], b[i] + d[i]) will rotate 90 degree clockwise. And the ith inner-square always contains (i + 1)th inner-square
After executed S commands, you will then be asked to do L queries to determine the final location given the initial value w[i].
E.g. With the above example, the final position of 25 will be (4, 4) - its initial location was (4, 5)
E.g. With the above example, the final position of 25 will be (4, 4) - its initial location was (4, 5)
Input format and constraints
- Line 1: integer N - size of the square (N <= 10^7)
- Line 2: integer S - number of commands (S <= 10^5)
- S subsequent lines: S commands with format (a[i], b[i], d[i]) with constraints
1 <= a[i], b[i] and 0 <= d[i] < N a[i-1] <= a[i] and a[i] + d[i] <= a[i - 1] + d[i - 1] b[i-1] <= b[i] and b[i] + b[i] <= b[i - 1] + b[i - 1]
The next line will contains integer L - number of queries (L <= 10^5)
Each subsequent line ask for the final position of a number w[i] (0 <= w[i] < N^2)
Here is one input example
7
2
1 2 4
2 3 3
2
11
24
Here is the output
4 4
2 5
Solution
(with my commenting on the code)Reference
[1]. https://www.hackerrank.com/challenges/king-richards-knights
Holy shit, this is exactly the task that LenderRate has offered me back then xD.
ReplyDeleteOh well, God bless you!
Delete