PROBLEM LINK:
Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4
Author: iceknight1093
Tester: nskybytskyi
Editorialist: iceknight1093
DIFFICULTY:
Cakewalk
PREREQUISITES:
None
PROBLEM:
You’re given a string S containing the characters \texttt{U,D,L,R}, representing the movement of Alice’s robot on the 2-D plane. It starts at (0, 0).
If Bob’s robot starts at (X, Y), does there exist a sequence of moves that will allow him to occupy the same position as Alice’s robot at some instant of time?
EXPLANATION:
Let’s try to solve a single instance of the problem: can Bob occupy the same position as Alice after exactly i moves have been made?
To answer that, first let’s compute where Alice’s robot will be: say (x_i, y_i).
This can be found by just directly simulating movements.
Now, if Bob is to reach exactly this position, note that he must make |x_i - X| horizontal moves and |y_i - Y| vertical moves.
So, if |x_i - X| + |y_i - Y| \gt i, Bob definitely cannot reach this position, no matter what - he simply doesn’t have enough movement to do so.
On the other hand, if |x_i - X| + |y_i - Y| \lt i, Bob has some ‘extra’ moves left with him that need to be exhausted.
If these extra moves are even in number, Bob can easily use them all up (for example, alternate moving up and down), and still be at (x_i, y_i) after i seconds have passed.
If the number of extra moves is odd, there is no way for Bob to ever remain at (x_i, y_i) after using them all up.
Why?
A helpful observation here is to look at parity - that is, whether numbers are odd or even.
Notice that each move Bob makes changes the parity of either his x-coordinate, or his y-coordinate (but not both).
If Bob makes an odd number of moves, either his x-coordinate or his y-coordinate will change an odd number of times - and hence will have different parity from what it started with.
If two numbers have different parity, they definitely cannot be equal; so since Bob has some coordinate with a different parity, he cannot be at the position he started at.
So, once x_i and y_i are known, we can figure out whether Bob can reach (x_i, y_i) in exactly i moves with a couple of simple checks.
Try this for every i from 1 to N, to see if Bob can reach Alice at any point along her path - the answer is Yes
if at least one check passes, and No
if they all fail.
TIME COMPLEXITY:
\mathcal{O}(N) or \mathcal{O}(N^2) per testcase.
CODE:
Editorialist's code (Python)
for _ in range(int(input())):
n, x, y = map(int, input().split())
s = input()
ax, ay = 0, 0
ans = 'No'
for i in range(n):
if s[i] == 'R': ax += 1
if s[i] == 'L': ax -= 1
if s[i] == 'U': ay += 1
if s[i] == 'D': ay -= 1
dx, dy = abs(x-ax), abs(y-ay)
if dx+dy <= i+1 and (dx+dy)%2 == (i+1)%2: ans = 'Yes'
print(ans)