Problem:


Score : 600 points

Problem Statement

We have a rectangular grid of squares with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left.
On this grid, there is a piece, which is initially placed at square (s_r,s_c).

Takahashi and Aoki will play a game, where each player has a string of length N.
Takahashi's string is S, and Aoki's string is T. S and T both consist of four kinds of letters: L, R, U and D.

The game consists of N steps. The i-th step proceeds as follows:

First, Takahashi performs a move. He either moves the piece in the direction of S_i, or does not move the piece.

Second, Aoki performs a move. He either moves the piece in the direction of T_i, or does not move the piece.

Here, to move the piece in the direction of L, R, U and D, is to move the piece from square (r,c) to square (r,c-1), (r,c+1), (r-1,c) and (r+1,c), respectively. If the destination square does not exist, the piece is removed from the grid, and the game ends, even if less than N steps are done.

Takahashi wants to remove the piece from the grid in one of the N steps.
Aoki, on the other hand, wants to finish the N steps with the piece remaining on the grid.
Determine if the piece will remain on the grid at the end of the game when both players play optimally.

Constraints

2 \leq H,W \leq 2 \times 10^5

2 \leq N \leq 2 \times 10^5

1 \leq s_r \leq H

1 \leq s_c \leq W

|S|=|T|=N

S and T consists of the four kinds of letters L, R, U and D.

Input

Input is given from Standard Input in the following format:

H W N
s_r s_c
S
T

Output

If the piece will remain on the grid at the end of the game, print YES; otherwise, print NO.

Sample Input 1

2 3 3
2 2
RRL
LUD

Sample Output 1

YES

Here is one possible progress of the game:

Takahashi moves the piece right. The piece is now at (2,3).

Aoki moves the piece left. The piece is now at (2,2).

Takahashi does not move the piece. The piece remains at (2,2).

Aoki moves the piece up. The piece is now at (1,2).

Takahashi moves the piece left. The piece is now at (1,1).

Aoki does not move the piece. The piece remains at (1,1).

Sample Input 2

4 3 5
2 2
UDRRR
LLDUD

Sample Output 2

NO

Sample Input 3

5 6 11
2 1
RLDRRUDDLRL
URRDRLLDLRD

Sample Output 3

NO



Sample input:
2 3 3
2 2
RRL
LUD


Sample output:
YES

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b: a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############

H,W,N = IL()
sy,sx = IL()
A = S()
B = S()

X = [sx,sx]
Y = [sy,sy]
for i in range(N):
  a = A[i]
  if a == "L":
    if X[0] == 1:
      print("NO")
      exit()
    else:
      X[0] -= 1
  if a == "R":
    if X[1] == W:
      print("NO")
      exit()
    else:
      X[1] += 1
  if a == "U":
    if Y[0] == 1:
      print("NO")
      exit()
    else:
      Y[0] -= 1
  if a == "D":
    if Y[1] == H:
      print("NO")
      exit()
    else:
      Y[1] += 1
  a = B[i]
  if a == "L":
    X[1] = max(1,X[1]-1)
  if a == "R":
    X[0] = min(W,X[0]+1)
  if a == "U":
    Y[1] = max(1,Y[1]-1)
  if a == "D":
    Y[0] = min(H,Y[0]+1)
  
print("YES")

Submission status: Accepted

Solution code:
# 以下の貪欲法は嘘解法（通るらしい）。
# 「高橋くんは右方向に落とすように、なるべく右を選ぶ。青木くんは落ちない範囲で左を選ぶ。これで落ちるか落ちないか判定する。
# これを上下左右で繰り返し、落ちなければ」
# 盤面が縦が十分大きい×横3、初期位置が中央、
# UULLRR
# RLUUUU
# は正解NOだが、貪欲でYESになってしまう。

# https://www.youtube.com/watch?v=Rr5ul_LDMiw
# コメントより：
# 3×3中央で、
# DRLL
# RUDD
# 初手青木くんがRなら高橋くんはそのままRするし、でなければLLしてどのみち外に出せる。

h, w, n = list(map(int, input().split()))
row, column = list(map(int, input().split()))
s_sente = input()
s_gote = input()

ans = [0, h-1, 0, w-1]
for i in reversed(range(n)):
    g = s_gote[i]
    if g == 'U':
        ans[1] = min(ans[1] + 1, h-1)
    elif g == 'D':
        ans[0] = max(ans[0] - 1, 0)
    elif g == 'L':
        ans[3] = min(ans[3] + 1, w-1)
    elif g == 'R':
        ans[2] = max(ans[2] - 1, 0)
    # print(ans)

    s = s_sente[i]
    if s == 'U':
        ans[0] = ans[0] + 1
    elif s == 'D':
        ans[1] = ans[1] - 1
    elif s == 'L':
        ans[2] = ans[2] + 1
    elif s == 'R':
        ans[3] = ans[3] - 1
    
    if not (ans[0] <= ans[1] and ans[2] <= ans[3]):
        print('NO')
        exit()
    # print(ans)

if ans[0] <= row-1 <= ans[1] and ans[2] <= column-1 <= ans[3]:
    # 「最後までコマが残るような初期配置の範囲」に、所与の初期配置が含まれる
    print('YES')
else:
    print('NO')

Submission status: Accepted

Solution code:
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")


h,w,n = list(map(int, input().split()))
rr,cc = list(map(int, input().split()))
rr -= 1
cc -= 1
s = input()
t = input()
def sub(s,t,init,limit):
    c = init
    for ss,tt in zip(s,t):
        if ss:
            c += 1
            if c>=limit:
                ans = True
                break
        if tt:
            c -= 1
            c = max(0, c)
    else:
        ans = False
    return ans
v1 = sub([item=="U" for item in s], [item=="D" for item in t], h-1-rr, h)
v2 = sub([item=="D" for item in s], [item=="U" for item in t], rr, h)
v3 = sub([item=="L" for item in s], [item=="R" for item in t], w-1-cc, w)
v4 = sub([item=="R" for item in s], [item=="L" for item in t], cc, w)
if v1 or v2 or v3 or v4:
    ans = "NO"
else:
    ans = "YES"
print(ans)

Submission status: Accepted

Solution code:
H,W,n = map(int, input().split())
sr, sc  = map(int, input().split())
S = input()
T = input()

# 最後の状態から、後手が勝てる範囲をさかのぼって見ていく
nL, nR = 1, W
# 上下の座標逆転 上方向はインクリメントとする
sr = H + 1 - sr
nD, nU = 1, H

for s,t in zip(S[::-1],T[::-1]):
    # 青木くんは自分の領土を広げる方向
    # 動かせる駒の逆方向に領土を広げられる
    if t == "R" :nL -= 1
    elif t == "L": nR += 1
    elif t == "U": nD -= 1
    elif t == "D": nU += 1

    # 青木くんはマスの領域以上には広がらない
    if nL < 1: nL = 1
    if nR > W: nR = W
    if nD < 1: nD = 1
    if nU > H: nU = H

    # 高橋くんは領土を縮める方向
    if s == "R" :nR -= 1
    elif s == "L": nL += 1
    elif s == "U": nU -= 1
    elif s == "D": nD += 1


    if nL > nR or nD > nU:
        print("NO")
        exit()


if (nL <= sc <= nR) and (nD <= sr <= nU):
    print("YES")
else:
    print("NO")

Submission status: Accepted

Solution code:
#AGC033-B LRUD Game
"""
1つの駒が二次元グリッド上(HxW)にある。最初駒は(sr,sc)にある。
iターン目にそれぞれSiとTi方向に動くか、もしくは動かないを選択できる。
高橋くんはSiの動作を選ぶことができ、盤面から駒を出す事ができたら勝つ。(h or w < 1 or H < h or W < w)
青木くんはTiの操作を選ぶことができ、ゲーム終了までずっと盤面上に駒が存在すれば勝つ。
両者が最適に行動した時、どちらが勝つか出力せよ。(青木くんが勝つならYES)

"""
import sys
readline = sys.stdin.buffer.readline
def even(n): return 1 if n%2==0 else 0

H,W,N = map(int,readline().split())
sh,sw = map(int,readline().split())
S = readline().rstrip().decode('utf-8')
T = readline().rstrip().decode('utf-8')

#上下左右の余裕
UDLR = [sh-1,H-sh,sw-1,W-sw]
#青木くんが超えてはならない逆端
UDLR3 = [H-sh,sh-1,W-sw,sw-1]
UDLR3 = [-i for i in UDLR3]
#高橋くんが移動できる最大値
#青木くんの行動によってマイナスされるが、この時青木くんの行動によって逆端を超えてはならない
UDLR2 = [0,0,0,0]

m = {"U":0,"D":1,"L":2,"R":3}
m2 = {"U":1,"D":0,"L":3,"R":2}
for i in range(N):
    s,t = m[S[i]],m2[T[i]]

    UDLR2[s] += 1
    
    for i in range(4):
        if UDLR2[i] > UDLR[i]:
            print("NO")
            exit()
    
    if UDLR2[t] -1 >= UDLR3[t]:
        UDLR2[t] -= 1

print("YES")

Submission status: Accepted

Solution code:
import sys
from collections import defaultdict

sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7


def input():
    return sys.stdin.readline().strip()


def main():
    H, W, N = map(int, input().split())
    sh, sw = map(int, input().split())
    S = input()
    T = input()
    count_S = defaultdict(int)
    count_T = defaultdict(int)

    for i in range(N):
        s = S[i]
        t = T[i]

        left = min(sw - (count_S["L"] - count_T["R"]), sw)
        right = max(sw + count_S["R"] - count_T["L"], sw)
        top = min(sh - (count_S["U"] - count_T["D"]), sh)
        bottom = max(sh + count_S["D"] - count_T["U"], sh)

        if s == "L":
            if left - 1 == 0:
                print("NO")
                return
        elif s == "R":
            if right == W:
                print("NO")
                return
        elif s == "U":
            if top - 1 == 0:
                print("NO")
                return
        elif s == "D":
            if bottom == H:
                print("NO")
                return

        count_S[s] += 1

        right = max(sw - (count_S["L"] - count_T["R"]), sw)
        left = min(sw + count_S["R"] - count_T["L"], sw)
        bottom = max(sh - (count_S["U"] - count_T["D"]), sh)
        top = min(sh + count_S["D"] - count_T["U"], sh)

        if t == "L":
            if left - 1 == 0:
                continue
        elif t == "R":
            if right == W:
                continue
        elif t == "U":
            if top - 1 == 0:
                continue
        elif t == "D":
            if bottom == H:
                continue

        count_T[t] += 1

    print("YES")


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
H,W,N=map(int,input().split())
sr,sc=map(lambda x:int(x)-1,input().split())
S=input()
T=input()

tmove=[(0,-1),(0,1),(-1,0),(1,0)]
amove=[(0,1),(0,-1),(1,0),(-1,0)]
m=[('L','R'),('R','L'),('U','D'),('D','U')]
for i in range(4):
    nh,nw=sr,sc
    t,a=tmove[i],amove[i]
    for k in range(N):
        if S[k]==m[i][0]:
            nh,nw=nh+t[0],nw+t[1]
        if nh<0 or nw<0 or nh>=H or nw>=W:
            print('NO')
            exit()
        gh,gw=nh+a[0],nw+a[1]
        if T[k]==m[i][1]:
            if gh>=0 and gh<H and gw>=0 and gw<W:
                nh,nw=gh,gw
print('YES')

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

H, W, N = mapint()
sy, sx = mapint()
S = list(str(input()))
T = list(str(input()))
L, R = sx-1, sx-1
U, D = sy-1, sy-1
for s, t in zip(S, T):
    if s=='L':
        L -= 1
        if L<0:
            print('NO')
            break
    elif s=='R':
        R += 1
        if R>=W:
            print('NO')
            break
    elif s=='U':
        U -= 1
        if U<0:
            print('NO')
            break
    else:
        D += 1
        if D>=H:
            print('NO')
            break
    if t=='L':
        R = max(R-1, 0)
    elif t=='R':
        L = min(L+1, W-1)
    elif t=='U':
        D = max(D-1, 0)
    else:
        U = min(U+1, H-1)
else:
    print('YES')

Submission status: Accepted

Solution code:
H, W, N = map(int, input().split())
h, w = map(int, input().split())
S = input()
T = input()

h -= 1
w -= 1
for i in range(N):
    if S[i] == "L":
        if w-1 < W-w-1:
            w -= 1
    elif S[i] == "R":
        if w > W-w-2:
            w += 1
    elif S[i] == "U":
        if h-1 < H-h-1:
            h -= 1
    elif S[i] == "D":
        if h > H-h-2:
            h += 1
    if w == 0 or h == 0 or h == H or w == W:
        print("NO")
        break

    if T[i] == "L":
        if w-1 > W-w-1:
            w -= 1
    elif T[i] == "R":
        if w < W-w-2:
            w += 1
    elif T[i] == "U":
        if h-1 > H-h-1:
            h -= 1
    elif T[i] == "D":
        if h < H-h-2:
            h += 1
else:
    print("YES")

Submission status: Accepted

Solution code:
h,w,n=map(int,input().split())
sr,sc=map(int,input().split())
s=input()[::-1]
t=input()[::-1]
l,r,u,d=0,w+1,0,h+1
for i in range(n):
 si,ti=s[i],t[i]
 if l+1>=r or u+1>=d:break
 r=min(w+1,r+1)if ti=="L"else r
 l=max(0,l-1)if ti=="R"else l
 d=min(h+1,d+1)if ti=="U"else d
 u=max(0,u-1)if ti=="D"else u
 r-=1 if si=="R"else 0
 l+=1 if si=="L"else 0
 d-=1 if si=="D"else 0
 u+=1 if si=="U"else 0
print("YES"if l<sc<r and u<sr<d else"NO")

Submission status: Accepted

Solution code:
h,w,n = map(int,input().split())
r,c =  map(int,input().split())
s = input()
t = input()

def check(m,p,l):
    left = 0
    right = l
    for si,ti in zip(s[::-1],t[::-1]):
        if(ti==m):
            right = min(right+1,l)
        elif(ti==p):
            left = max(left-1,0)

        if(si==m):
            left = left+1
        elif(si==p):
            right = right-1

        if(left==right):
            return (-1,-1)

    return (left+1,right+1)

left,right = check('L','R',w)
if(not left<=c<right):
    print('NO')
    exit()

left,right = check('U','D',h)
if(not left<=r<right):
    print('NO')
    exit()

print('YES')

Submission status: Accepted

Solution code:
h,w,n = list(map(int,input().split()))
sr,sc = list(map(int,input().split()))
s = input()
t = input()
kijyun = "LRUD"
ruisekiS = [{v:0 for v in kijyun} for i in range(n+1)]
ruisekiT = [{v:0 for v in kijyun} for i in range(n+1)]

for i in range(n):
    for c in kijyun:
        if s[i] == c:
            ruisekiS[i+1][c] = ruisekiS[i][c] + 1
        else:
            ruisekiS[i+1][c] = ruisekiS[i][c]
        if t[i] == c:
            ruisekiT[i+1][c] = ruisekiT[i][c] + 1
        else:
            ruisekiT[i+1][c] = ruisekiT[i][c]
kyori = {"L":sc,"R":w-sc+1,"U":sr,"D":h-sr+1}
gyaku = {"L":"R","R":"L","U":"D","D":"U"}

check = 0
for i in range(n):
    for c in kijyun:
        if s[i] == c:
            ruisekiS[i+1][c] = ruisekiS[i][c] + 1
        else:
            ruisekiS[i+1][c] = ruisekiS[i][c]
        if t[i] == c and (ruisekiT[i][c] + 1 - ruisekiS[i][gyaku[c]]) < kyori[c] :
            ruisekiT[i+1][c] = ruisekiT[i][c] + 1
        else:
            ruisekiT[i+1][c] = ruisekiT[i][c]
    if ruisekiS[i+1]["L"] - ruisekiT[i]["R"] >= kyori["L"]:
        check = 1
    if ruisekiS[i+1]["R"] - ruisekiT[i]["L"] >= kyori["R"]:
        check = 1
    if ruisekiS[i+1]["U"] - ruisekiT[i]["D"] >= kyori["U"]:
        check = 1
    if ruisekiS[i+1]["D"] - ruisekiT[i]["U"] >= kyori["D"]:
        check = 1
#print(ruisekiS)
#print(ruisekiT)
if check == 0:
    print('YES')
else:
    print('NO')

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15

H,W,N = map(int,input().split())
y,x = map(int,input().split())
S = input()
T = input()

def is_out(now,adv,back,L,R):
    for i in range(N):
        if S[i] == adv:
            now += 1
            if now > R:
                return True
        if T[i] == back:
            now = max(now - 1,L)
    return False

ans = is_out(x,'R','L',1,W) | is_out(-x,'L','R',-W,-1) | is_out(y,'D','U',1,H) | is_out(-y,'U','D',-H,-1)
print('NO' if ans else 'YES')

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

H, W, N = MAP()
sr, sc = MAP()
S = input()
T = input()

l, r, u, d = 1, W, 1, H

for s, t in zip(S[::-1], T[::-1]):
	if t == "L":
		r = min(r+1, W)
	elif t == "R":
		l = max(l-1, 1)
	elif t == "U":
		d = min(d+1, H)
	elif t == "D":
		u = max(u-1, 1)

	if s == "L":
		l += 1
	elif s == "R":
		r -= 1
	elif s == "U":
		u += 1
	elif s == "D":
		d -= 1

	if l > r or u > d:
		print("NO")
		exit()

if l <= sc <= r and u <= sr <= d:
	print("YES")
else:
	print("NO")

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

H, W, N = MAP()
sr, sc = MAP()
S = input()
T = input()

x = sc
for s, t in zip(S, T):  # 左を目指す
	if s == "L":
		x -= 1
		if x == 0:
			print("NO")
			exit()
	if t == "R" and x+1 <= W:
		x += 1

x = sc
for s, t in zip(S, T):  # 右を目指す
	if s == "R":
		x += 1
		if x == W+1:
			print("NO")
			exit()
	if t == "L" and x-1 >= 1:
		x -= 1

y = sr
for s, t in zip(S, T):  # 上を目指す
	if s == "U":
		y -= 1
		if y == 0:
			print("NO")
			exit()
	if t == "D" and y+1 <= H:
		y += 1

y = sr
for s, t in zip(S, T):  # 下を目指す
	if s == "D":
		y += 1
		if y == H+1:
			print("NO")
			exit()
	if t == "U" and y-1 >= 1:
		y -= 1

print("YES")

Submission status: Accepted

Solution code:
h,w,n=map(int,input().split())
sr,sc=map(lambda x:int(x)-1,input().split())
s=input()
t=input()
answ,ansh=[0,w-1],[0,h-1]
for i in range(n):
    if s[-i-1]=='R':
        answ[1]-=1
    if s[-i-1]=='L':
        answ[0]+=1
    if s[-i-1]=='D':
        ansh[1]-=1
    if s[-i-1]=='U':
        ansh[0]+=1
    if answ[0]>answ[1] or ansh[0]>ansh[1]:
        print('NO')
        exit()
    if i==n-1:
        break
    if t[-i-2]=='R':
        answ[0]=max(0,answ[0]-1)
    if t[-i-2]=='L':
        answ[1]=min(w-1,answ[1]+1)
    if t[-i-2]=='D':
        ansh[0]=max(0,ansh[0]-1)
    if t[-i-2]=='U':
        ansh[1]=min(h-1,ansh[1]+1)
if answ[0]<=sc<=answ[1] and ansh[0]<=sr<=ansh[1]:
    print('YES')
else:
    print('NO')

Submission status: Accepted

Solution code:

import sys
sys.setrecursionlimit(10**8)
input = sys.stdin.readline

H,W,N = map(int,input().split())
sr,sc = map(int,input().split())
S = input().rstrip()
T = input().rstrip()

taka = [('L','U'),('L','D'),('R','D'),('R','U')]
aoki = [('R','D'),('R','U'),('L','U'),('L','D')]

def sousa(x, s):
    if s == 'L':
        return [x[0], x[1]-1]
    elif s == 'R':
        return [x[0], x[1]+1]
    elif s == 'U':
        return [x[0]-1, x[1]]
    elif s == 'D':
        return [x[0]+1, x[1]]
    return x

def sousa_inv(x, s):
    if s == 'R':
        return [x[0], x[1]-1]
    elif s == 'L':
        return [x[0], x[1]+1]
    elif s == 'D':
        return [x[0]-1, x[1]]
    elif s == 'U':
        return [x[0]+1, x[1]]
    return x


def judge(x):
    if x[0]<= 0 or x[1]<=0:
        return False
    elif x[0]>H or x[1]>W:
        return False
    else:
        return True


for i in range(4):
    cur = [sr, sc]
    for s,t in zip(S,T):
        if s in taka[i]:
            cur = sousa(cur, s)
        if not judge(cur):
            print('NO')
            exit()
        if t in aoki[i]:
            cur = sousa(cur, t)
        if not judge(cur):
            cur = sousa_inv(cur, t)

print('YES')

Submission status: Accepted

Solution code:
import sys
#import numpy as np
import math
from fractions import Fraction
import itertools

input=sys.stdin.readline

h,w,n=map(int,input().split())
sr,sc=map(int ,input().split())
s=input()
p=input()

t={"L":0,"R":0,"U":0,"D":0}
a={"L":0,"R":0,"U":0,"D":0}

for i in range(n):
    if s[i]=="L":
        t["L"]+=1
    elif s[i]=="R":
        t["R"]+=1
    elif s[i]=="U":
        t["U"]+=1
    elif s[i]=="D":
        t["D"]+=1
    if t["R"]-a["L"]==w-sc+1 or t["L"]-a["R"]==sc or t["D"]-a["U"]==h-sr+1 or t["U"]-a["D"]==sr:
        print("NO")
        break
    else:
        if p[i]=="L" and a["L"]-t["R"]<sc-1:
            a["L"]+=1
        elif p[i]=="R" and a["R"]-t["L"]<w-sc:
            a["R"]+=1
        elif p[i]=="U" and a["U"]-t["D"]<sr-1:
            a["U"]+=1
        elif p[i]=="D" and a["D"]-t["U"]<h-sr:
            a["D"]+=1
else:
  print("YES")

Submission status: Accepted

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq

def main():
    sys.setrecursionlimit(10**7)
    INF = 10**18
    MOD = 10**9 + 7
    LI = lambda : [int(x) for x in sys.stdin.readline().split()]
    NI = lambda : int(sys.stdin.readline())
    SI = lambda : sys.stdin.readline().rstrip()

    H,W,N = LI()
    R,C = LI()
    S = SI()
    T = SI()

    x = C
    for i in range(N):
        x -= S[i] == 'L'
        if x <= 0:
            print('NO')
            return
        if x < W:
            x += T[i] == 'R'

    x = C
    for i in range(N):
        x += S[i] == 'R'
        if x > W:
            print('NO')
            return
        if x > 1:
            x -= T[i] == 'L'

    x = R
    for i in range(N):
        x -= S[i] == 'U'
        if x <= 0:
            print('NO')
            return
        if x < H:
            x += T[i] == 'D'

    x = R
    for i in range(N):
        x += S[i] == 'D'
        if x > H:
            print('NO')
            return
        if x > 0:
            x -= T[i] == 'U'

    print('YES')

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    H,W,N=map(int,input().split())
    Y,X=map(int1,input().split())
    T=input()
    A=input()
    d={s:i for i,s in enumerate(['L','R','U','D'])}
    l=[1,0,3,2]
    def check(y,x):
        return 0<=y<H and 0<=x<W
    for k in range(4):
        y,x=Y,X
        for i in range(N):
            if d[T[i]]==k:
                if k==0:
                    x-=1
                elif k==1:
                    x+=1
                elif k==2:
                    y-=1
                else:
                    y+=1
            if not check(y,x):
                print('NO')
                exit()
            if d[A[i]]==l[k]:
                if k==0:
                    x+=1
                elif k==1:
                    x-=1
                elif k==2:
                    y+=1
                else:
                    y-=1
                y=min(max(y,0),H-1)
                x=min(max(x,0),W-1)
    print('YES')
    

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
H, W, N = map(int, input().split())
Sr, Sc = map(int, input().split())
S = input()
T = input()

# 左か上に移動させたい
now = [Sr, Sc]
for s, t in zip(S, T):
  # 高橋くんのターン
  if s == 'L':
    now[1] -= 1
  if s == 'U':
    now[0] -= 1
  # 駒を取り除けたかチェック
  if now[0] <= 0 or now[1] <= 0:
    print('NO')
    quit()
  
  # 青木くんのターン
  if t == 'R':
    now[1] = min(now[1] + 1, W)
  if t == 'D':
    now[0] = min(now[0] + 1, H)

# 右か下に移動させたい
now = [Sr, Sc]
for s, t in zip(S, T):
  # 高橋くんのターン
  if s == 'R':
    now[1] += 1
  if s == 'D':
    now[0] += 1
  # 駒を取り除けたかチェック
  if H < now[0] or W < now[1]:
    print('NO')
    quit()
  
  # 青木くんのターン
  if t == 'L':
    now[1] = max(now[1] - 1, 1)
  if t == 'U':
    now[0] = max(now[0] - 1, 1)

print('YES')

Submission status: Accepted

Solution code:
h, w, n = map(int, input().split())
sh, sw = map(int, input().split())
s = input()
t = input()

d = {"L": (0, -1), "R": (0, 1), "U": (-1, 0), "D": (1, 0)}


def f(s_dir, t_dir):
    nh = sh
    nw = sw
    sdh, sdw = d[s_dir]
    tdh, tdw = d[t_dir]
    for es, et in zip(s, t):
        if es == s_dir:
            nh += sdh
            nw += sdw
            if nh < 1 or nh > h or nw < 1 or nw > w:
                return True

        if et == t_dir:
            tmph = nh + tdh
            tmpw = nw + tdw
            if 1 <= tmph <= h and 1 <= tmpw <= w:
                nh = tmph
                nw = tmpw

    return False


if f("L", "R") or f("R", "L") or f("U", "D") or f("D", "U"):
    ans = "NO"
else:
    ans = "YES"

print(ans)

Submission status: Accepted

Solution code:
h, w, n = map(int,input().split())
sr, sc = map(int,input().split())
s = input()[::-1]
t = input()[::-1]

#安全な範囲を考える
l = 1
r = w
u = 1
d = h

if s[0] == "L":
    l += 1
elif s[0] == "R":
    r -= 1
elif s[0] == "U":
    u += 1
else:
    d -= 1
for i in range(1,n):
    if t[i] == "L":
        r = min(r+1,w)
    elif t[i] == "R":
        l = max(l-1,1)
    elif t[i] == "U":
        d = min(d+1,h)
    else:
        u = max(u-1,1)
    if s[i] == "L":
        l += 1
    elif s[i] == "R":
        r -= 1
    elif s[i] == "U":
        u += 1
    else:
        d -= 1
    if l > r or u > d:
        print("NO")
        exit()

if l <= sc and sc <= r and u <= sr and sr <= d:
    print("YES")
else:
    print("NO")

Submission status: Accepted

Solution code:
h,w,n = map(int,input().split())
sr,sc = map(int,input().split())
s = input()
t = input()
r,l,u,d = sc,sc,sr,sr
ans = "YES"
for i,j in zip(s,t):
  if i == "R":
    r+=1
    if r>w:
      ans = "NO"
      break
  elif i =="L":
    l-=1
    if l<1:
      ans = "NO"
      break
  elif i =="U":
    u-=1
    if u<1:
      ans = "NO"
      break
  else:
    d+=1
    if d>h:
      ans = "NO"
      break
  if j == "L":
    r=max(1,r-1)
  elif j == "R":
    l=min(w,l+1)
  elif j == "D":
    u=min(h,u+1)
  else:
    d=max(1,d-1)
print(ans)

Submission status: Accepted

Solution code:
h,w,n=map(int,input().split())
y,x=map(int,input().split())
ul=y-1
dl=h-y
ll=x-1
rl=w-x
s=input()
t=input()
#U
for i in range(n):
  if s[i]=="U":ul-=1
  if ul<0:exit(print("NO"))
  if t[i]=="D":ul=min(ul+1,h-1)
#D
for i in range(n):
  if s[i]=="D":dl-=1
  if dl<0:exit(print("NO"))
  if t[i]=="U":dl=min(dl+1,h-1)
#L
for i in range(n):
  if s[i]=="L":ll-=1
  if ll<0:exit(print("NO"))
  if t[i]=="R":ll=min(ll+1,w-1)
#R
for i in range(n):
  if s[i]=="R":rl-=1
  if rl<0:exit(print("NO"))
  if t[i]=="L":rl=min(rl+1,w-1)
print("YES")

Submission status: Accepted

Solution code:
def main():
    H, W, N = map(int, input().split())
    sr, sc = map(int, input().split())
    S = input()
    T = input()
    f = True
    pL, pR, pU, pD = sc, sc, sr, sr
    for i in range(N):
        if S[i] == "L":
            pL -= 1
        elif S[i] == "R":
            pR += 1
        elif S[i] == "U":
            pU -= 1
        else:
            pD += 1
        if pL <= 0 or W < pR or pU <= 0 or H < pD:
            f = False
        if T[i] == "L":
            if 1 < pR:
                pR -= 1
        elif T[i] == "R":
            if pL < W:
                pL += 1
        elif T[i] == "U":
            if 1 < pD:
                pD -= 1
        else:
            if pU < H:
                pU += 1
    if f:
        print("YES")
    else:
        print("NO")

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
H,W,N=map(int, input().split())
h,w=map(int, input().split())
S=input()
T=input()
h1,h2,w1,w2=H-h+1,H-h+1,w,w
for i in range(N):
  if S[i]=='U':
    h1+=1
  if h1>H:
    print('NO')
    exit()
  if T[i]=='D':
    h1=max(h1-1,1)
 
  if S[i]=='D':
    h2-=1
  if h2<1:
    print('NO')
    exit()
  if T[i]=='U':
    h2=min(h2+1,H)
  
  if S[i]=='R':
    w1+=1
  if w1>W:
    print('NO')
    exit()
  if T[i]=='L':
    w1=max(w1-1,1)
    
  if S[i]=='L':
    w2-=1
  if w2<1:
    print('NO')
    exit()
  if T[i]=='R':
    w2=min(w2+1,W)

print('YES')

Submission status: Accepted

Solution code:
H,W,N=map(int,input().split())
sr,sc=map(int,input().split())
S=input()
T=input()
#L
pos=sc
for i in range(0,N):
    if S[i]=="L":
        pos-=1
        if pos==0:
            print("NO")
            exit()
    if T[i]=="R" and pos!=W:
        pos+=1

#R
pos=sc
for i in range(0,N):
    if S[i]=="R":
        pos+=1
        if pos==W+1:
            print("NO")
            exit()
    if T[i]=="L" and pos!=1:
        pos-=1

#U
pos=sr
for i in range(0,N):
    if S[i]=="U":
        pos-=1
        if pos==0:
            print("NO")
            exit()
    if T[i]=="D" and pos!=H:
        pos+=1

#D
pos=sr
for i in range(0,N):
    if S[i]=="D":
        pos+=1
        if pos==H+1:
            print("NO")
            exit()
    if T[i]=="U" and pos!=1:
        pos-=1

print("YES")