Problem:


Score : 500 points

Problem Statement

A robot is put at the origin in a two-dimensional plane.
Initially, the robot is facing in the positive x-axis direction.

This robot will be given an instruction sequence s.
s consists of the following two kinds of letters, and will be executed in order from front to back.

F : Move in the current direction by distance 1.

T : Turn 90 degrees, either clockwise or counterclockwise.

The objective of the robot is to be at coordinates (x, y) after all the instructions are executed.
Determine whether this objective is achievable.

Constraints

s consists of F and T.

1 \leq |s| \leq 8 000

x and y are integers.

|x|, |y| \leq |s|

Input

Input is given from Standard Input in the following format:

s
x y

Output

If the objective is achievable, print Yes; if it is not, print No.

Sample Input 1

FTFFTFFF
4 2

Sample Output 1

Yes

The objective can be achieved by, for example, turning counterclockwise in the first T and turning clockwise in the second T.

Sample Input 2

FTFFTFFF
-2 -2

Sample Output 2

Yes

The objective can be achieved by, for example, turning clockwise in the first T and turning clockwise in the second T.

Sample Input 3

FF
1 0

Sample Output 3

No

Sample Input 4

TF
1 0

Sample Output 4

No

Sample Input 5

FFTTFF
0 0

Sample Output 5

Yes

The objective can be achieved by, for example, turning counterclockwise in the first T and turning counterclockwise in the second T.

Sample Input 6

TTTT
1 0

Sample Output 6

No



Sample input:
FTFFTFFF
4 2


Sample output:
Yes

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def check(vec, init_pos, target_pos):
    dp = {init_pos}

    for nv in vec:
        if nv == 0:
            continue
        dp_next = set()
        for v in dp:
            dp_next.add(v - nv)
            dp_next.add(v + nv)
        dp = dp_next

    return target_pos in dp


def main():
    S = readline().strip()
    x, y = map(int, readline().split())

    L = [len(commands) for commands in S.split('T')]

    init_x = L[0]
    x_commands = L[2::2]
    y_commands = L[1::2]

    ok = check(x_commands, init_x, x) and check(y_commands, 0, y)

    if ok:
        print('Yes')
    else:
        print('No')

    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def check(vec, init_pos, target_pos):
    dp = {init_pos}

    for nv in vec:
        dp_next = set()
        for v in dp:
            dp_next.add(v - nv)
            dp_next.add(v + nv)
        dp = dp_next

    return target_pos in dp


def main():
    S = readline().strip()
    x, y = map(int, readline().split())

    L = [len(commands) for commands in S.split('T')]

    init_x = L[0]
    x_commands = [c for c in L[2::2] if c != 0]
    y_commands = [c for c in L[1::2] if c != 0]

    ok = check(x_commands, init_x, x) and check(y_commands, 0, y)

    if ok:
        print('Yes')
    else:
        print('No')

    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def check(vec, init_pos, target_pos):
    dp = {init_pos}

    for nv in vec:
        dp_next = set()
        for v in dp:
            dp_next.add(v - nv)
            dp_next.add(v + nv)
        dp = dp_next

    return target_pos in dp


def main():
    S = readline().strip()
    x, y = map(int, readline().split())

    L = [len(commands) for commands in S.split('T')]

    init_x = L[0]
    x_commands = L[2::2]
    y_commands = L[1::2]

    ok = check(x_commands, init_x, x) and check(y_commands, 0, y)

    if ok:
        print('Yes')
    else:
        print('No')

    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def check(vec, init_pos, target_pos):
    base = 8000
    dp = [False] * 16001
    dp[init_pos + base] = True

    for i in range(len(vec)):
        dp, dp_prev = [False] * 16001, dp
        for j in range(16001):
            if (
                j - vec[i] >= 0
                and dp_prev[j - vec[i]]
                or j + vec[i] <= 16000
                and dp_prev[j + vec[i]]
            ):
                dp[j] = True

    return dp[target_pos + base]


def main():
    S = readline().strip()
    x, y = map(int, readline().split())

    idx = len(S)
    for i, c in enumerate(S):
        if c == 'T':
            idx = i
            break

    init_x = idx
    step = [[] for _ in range(2)]
    i = 0
    for c in S[idx:]:
        if c == 'T':
            i = 1 - i
            step[i].append(0)
        else:
            step[i][-1] += 1
            
    for row in step:
        row = [v for v in row if v != 0]
        if not row:
            row = [0]

    ok = check(step[0], init_x, x) and check(step[1], 0, y)

    if ok:
        print('Yes')
    else:
        print('No')

    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007


def check(vec, init_pos, target_pos):
    base = 8000
    dp = [False] * 16001
    dp[init_pos + base] = True

    for i in range(len(vec)):
        dp, dp_prev = [False] * 16001, dp
        for j in range(16001):
            if (
                j - vec[i] >= 0
                and dp_prev[j - vec[i]]
                or j + vec[i] <= 16000
                and dp_prev[j + vec[i]]
            ):
                dp[j] = True

    return dp[target_pos + base]


def main():
    S = readline().strip()
    x, y = map(int, readline().split())

    idx = len(S)
    for i, c in enumerate(S):
        if c == 'T':
            idx = i
            break

    init_x = idx
    step = [[0] for _ in range(2)]
    i = 0
    for c in S[idx:]:
        if c == 'T':
            i = 1 - i
            step[i].append(0)
        else:
            step[i][-1] += 1

    ok = check(step[0], init_x, x) and check(step[1], 0, y)

    if ok:
        print('Yes')
    else:
        print('No')

    return


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from copy import copy
s = input()
n=len(s)
x, y = map(int, input().split())

d = [len(v) for v in s.split("T")]
x -= d[0]
a = d[2::2]
b = d[1::2]


def c(d, x):
    cur = {0}
    for i in d:
        nxt = set()
        for j in cur:
            nxt.add(j + i)
            nxt.add(j - i)
        cur = copy(nxt)
    return x in cur

print("Yes" if c(a, x) and c(b, y) else "No")

Submission status: Accepted

Solution code:
from copy import copy
s = input() + "T"
n=len(s)
x, y = map(int, input().split())

xy=[[],[]]

sgn = 1
now = n
for i in range(n):
    if s[i] == "T":
        x -= i
        now = i + 1
        break
for i in range(now, n):
    if s[i] == "T":
        xy[sgn].append(i - now)
        now = i + 1
        sgn ^= 1


cur = {0}
for i in xy[0]:
    nxt = set()
    for j in cur:
        nxt.add(j + i)
        nxt.add(j - i)
    cur = copy(nxt)

flag = x in cur

cur = {0}
for i in xy[1]:
    nxt = set()
    for j in cur:
        nxt.add(j + i)
        nxt.add(j - i)
    cur = copy(nxt)

print("Yes" if flag and y in cur else "No")

Submission status: Accepted

Solution code:
def turn():
  global drc
  if moves[drc][-1] != 0:
    moves[drc].append(0)
  drc=(drc+1)%2

def forward():
  moves[drc][-1]+=1
  
OP={"T":turn,"F":forward}

ops=input()
target=list(map(int,input().split()))
moves=[[0],[0]]
drc=0
first_F=0

# データ加工
for i,o in enumerate(ops):
  if o=="T" or i+1==len(ops):
    first_F=i
    break

for i in range(first_F,len(ops)):
  OP[ops[i]]()

# 組み合わせ演算
x_set=set([first_F])
for move in moves[0]:
  tmp_set=set()
  for xx in x_set:
    tmp_set.add(xx+move)
    tmp_set.add(xx-move)
  x_set=tmp_set
  
y_set=set([0])
for move in moves[1]:
  tmp_set=set()
  for yy in y_set:
    tmp_set.add(yy+move)
    tmp_set.add(yy-move)
  y_set=tmp_set

if target[0] in x_set and target[1] in y_set:
  print("Yes")
else:
  print("No")

Submission status: Accepted

Solution code:
s=input()
x,y=map(int, input().split())
cx=[]
cy=[]
dirx=1
l=0
ini=1
for i in range(len(s)):
  if s[i] == "F":
    l += 1
  else:
    if ini:
      x -= l
      ini = 0
    else:
      if dirx:
        cx.append(l)
      else:
        cy.append(l)
    l = 0
    dirx = not dirx

if ini == 0:
  if dirx:
    cx.append(l)
  else:
    cy.append(l)
else:
  x -= l

#print(cx)
#print(cy)


ng = 0
dp = {0}
for i in range( len(cx) ):
  dpn = set()
  for d in dp:
    dpn.add(d+cx[i])
    dpn.add(d-cx[i])
#  print(dpn)
  dpn, dp = dp, dpn
  
if not x in dp:
  ng = 1
#  print("x", x)
  
dp = {0}
for i in range( len(cy) ):
  dpn = set()
  for d in dp:
    dpn.add(d+cy[i])
    dpn.add(d-cy[i])
#  print(dpn)
  dpn, dp = dp, dpn
  
if not y in dp:
  ng = 1
#  print("y", y)

if ng==0:
  print("Yes")
else:
  print("No")

Submission status: Accepted

Solution code:
dic={"x":"y","y":"x"}

a = list(input())
X,Y = map(int,input().split())

direction = "x"
cersol = 0
while cersol < len(a) and a[cersol] == "F":
    cersol+=1
    X -= 1#これは確定した動きなので目的地をずらす方が楽

move = {"x":[],"y":[]}

while cersol < len(a):
    if a[cersol]=="T":#ターンならターン
        direction=dic[direction]
        cersol+=1

    count = 0
    while cersol < len(a) and a[cersol] == "F":
        count+=1
        cersol+=1
    
    move[direction].append(count)


able = {0:0}
preable = {0:0}
for i in move["x"]:
    able={}
    for j in preable:
        able[j+i]=0
        able[j-i]=0
    preable=able


ableX = able

able = {0:0}
preable = {0:0}
for i in move["y"]:
    able = {}
    for j in preable:
        able[j+i]=0
        able[j-i]=0
    preable=able

if (X in ableX)and(Y in able):
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
import sys

s = sys.stdin.readline().strip()
x, y = map(int, sys.stdin.readline().split())

goal = {"x": x, "y": y}
dist = {"x": [], "y": []}

if s[-1] != "T":
    s += "T"
d = 0
f = 0
x_init = -1
for i in s:
    if i == "F":
        d += 1
    else:
        if f % 2 == 0:
            if x_init == -1:
                x_init = d
            else:
                dist["x"].append(d)
        else:
            dist["y"].append(d)
        d = 0
        f += 1

# print(dist)
for mode in ("x", "y"):
    len_d = len(dist[mode])
    cand = set()
    if mode == "x":
        cand.add(x_init)
    else:
        cand.add(0)
    for i in range(len_d):
        next_cand = set()
        for d in cand:
            next_cand.add(d + dist[mode][i])
            next_cand.add(d - dist[mode][i])
        cand = next_cand

    if goal[mode] not in cand:
        print("No")
        sys.exit()

print("Yes")

Submission status: Accepted

Solution code:
s=input()
x,y=map(int, input().split())
X,Y=[],[]
t,c=0,0
for i in range(len(s)):
  if s[i]=='F':
    c+=1
  else:
    if t%2==0:
      X.append(c)
    else:
      Y.append(c)
    c=0
    t+=1
if t%2==0:
  X.append(c)
else:
  Y.append(c)
if len(X)>0:
  D=[X[0]]
  E=[]
  for i in range(1,len(X)):
    for j in D:
      E.append(j+X[i])
      E.append(j-X[i])
    D,E=list(set(E)),[]
if x not in D:
  print('No')
  exit()
  
if len(X)>0:
  D=[0]
  E=[]
  for i in range(len(Y)):
    for j in D:
      E.append(j+Y[i])
      E.append(j-Y[i])
    D,E=list(set(E)),[]
if y not in D:
  print('No')
else:
  print('Yes')

Submission status: Accepted

Solution code:
s=input()+'T'
x,y=list(map(int,input().split()))
x+=8000
y+=8000
n=len(s)
i=0

while i<n and s[i]=='F':
    i+=1

dx=[[0]*16001 for _ in range(2)]
dy=[[0]*16001 for _ in range(2)]

dx[0][i+8000]=1
dy[0][8000]=1

lstx=[]
lsty=[]
d='x'
cnt=0

while i<n:
    if s[i]=='F':
        cnt+=1
    else:
        if cnt>0:
            if d=='x':
                lstx.append(cnt)
            else:
                lsty.append(cnt)
        
        if d=='x':
            d='y'
        else:
            d='x'
        cnt=0
    
    i+=1

for i,cx in enumerate(lstx):
    for j in range(16001):
        if dx[i%2][j]==0:
            continue
        if j+cx<16001:
            dx[(i+1)%2][j+cx]=1
        if j-cx>-1:
            dx[(i+1)%2][j-cx]=1
    dx[i%2]=[0]*16001

for i,cy in enumerate(lsty):
    for j in range(16001):
        if dy[i%2][j]==0:
            continue
        if j+cy<16001:
            dy[(i+1)%2][j+cy]=1
        if j-cy>-1:
            dy[(i+1)%2][j-cy]=1
    dy[i%2]=[0]*16001

if dx[(len(lstx))%2][x]==1 and dy[(len(lsty))%2][y]==1:
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
from copy import copy
s = input() + "T"
x,y = map(int, input().split())

d = [len(p) for p in s.split("T")]
init = d[0]
d_x = d[2::2]
d_y = d[1::2]

xs = set([init])
ys = set([0])
dpx = [x in xs]
for d in d_x:
  xs_ = set()
  for u in xs:
    xs_.add(u+d)
    xs_.add(u-d)
  dpx.append(x in xs_)
  xs = copy(xs_)

dpy = []
for d in d_y:
  ys_ = set()
  for v in ys:
    ys_.add(v+d)
    ys_.add(v-d)
  dpy.append(y in ys_)
  ys = copy(ys_)

if dpx[-1] and dpy[-1]: print("Yes")
else: print("No")

Submission status: Accepted

Solution code:
s = input()
x,y = map(int,input().split())

move = [0]
for si in s:
    if(si  == 'F'):
        move[-1] += 1
    else:
        move.append(0)

move_x = move[2::2]
move_y = move[1::2]
for a,move_a in zip([x-move[0],y],[move_x,move_y]):
    m_max = sum(move_a)
    if(m_max < abs(a)):
        print('No')
        exit()

    dp = 2**m_max
    for mi in move_a:
        dp = (dp<<mi) | (dp>>mi)

    if(dp >> (m_max+a))&1:
        continue
    else:
        print('No')
        exit()

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)

S = list(input())+['T']
X, Y = mapint()
H = []
V = []

now_dirc = 1
cnt = 0
for s in S:
    if s=='F':
        cnt += 1
    else:
        if now_dirc==1:
            H.append(cnt)
        else:
            V.append(cnt)
        now_dirc*=-1
        cnt = 0

def check(now, goal, lis):
    dp = [0]*20000
    dp[10000+now] = 1
    for l in lis:
        nxdp = [0]*20000
        for i in range(20000):
            if i-l>=0 and dp[i-l]==1:
                nxdp[i] = 1
            if i+l<20000 and dp[i+l]==1:
                nxdp[i] = 1
        dp = nxdp
    if dp[goal+10000]:
        return True
    else:
        return False
    
if check(H[0], X, H[1:]) and check(0, Y, V):
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
S = str(input())
N = len(S)
x,y = map(int,input().split())
X = []; Y =[]
Flag = True #Trueならx軸、Falseならy軸
seq = 0
for i in range(N):
  if S[i] == "T":
    if Flag:
      X.append(seq)
    if not Flag:
      Y.append(seq)
    Flag = not Flag
    seq = 0
  else:
    seq += 1
    if i == N-1:
      if Flag:
        X.append(seq)
      if not Flag:
        Y.append(seq)
#print(X,Y)
num = 8100 #真ん中
MAX = num*2+1
#X方向i回目でjにいる
dpx = [0 for _ in range(MAX)]
dpx[num] = 1
dpy = [0 for _ in range(MAX)]
dpy[num] = 1
for i in range(len(X)):
  px = [0 for _ in range(MAX)]
  px,dpx = dpx,px
  step = X[i]
  for j in range(MAX):
    if j -step >= 0:
      dpx[j] = max(dpx[j],px[j-step])
    if j + step < MAX and i != 0: #一番最初は左に戻れない
      dpx[j] = max(dpx[j],px[j+step])
for i in range(len(Y)):
  py = [0 for _ in range(MAX)]
  py,dpy = dpy,py
  step = Y[i]
  for j in range(MAX):
    if j -step >= 0:
      dpy[j] = max(dpy[j],py[j-step])
    if j + step < MAX:
      dpy[j] = max(dpy[j],py[j+step])
x += num;y+= num
#print(dpx)
#print(dpy)
if dpx[x] == 1 and dpy[y] == 1:
  print("Yes")
else:
  print("No")

Submission status: Accepted

Solution code:
import sys
from collections import deque
def input(): return sys.stdin.readline().strip()


def main():
    s = input()
    x, y = map(int, input().split())
    """
    x, y方向独立に考えられることには気づいたけど、その後の遷移が2^N通りで無理だと思い込んでた。。。
    もらうdpで考えれば確かにO(N^2)で片付く。
    """
    C = [deque([]), []]
    direction = 0 # = X
    cnt = 0
    for c in s:
        if c == 'F':
            cnt += 1
            continue
        if c == 'T':
            C[direction].append(cnt)
            cnt = 0
            direction = 1 - direction
    C[direction].append(cnt)
    
    X = [0] * 16001
    if s[0] == 'F':
        start = C[0].popleft()
        X[8000 + start] = 1
    else:
        X[8000] = 1
    for cnt in C[0]:
        X_new = [0] * 16001
        for i in range(16001):
            if 0 <= i - cnt and i + cnt <= 16000:
                X_new[i] = 1 - (1 - X[i - cnt]) * (1 - X[i + cnt])
            elif 0 <= i - cnt:
                X_new[i] = X[i - cnt]
            else:
                X_new[i] = X[i + cnt]
        X = X_new

    Y = [0] * 16001
    Y[8000] = 1
    for cnt in C[1]:
        Y_new = [0] * 16001
        for i in range(16001):
            if 0 <= i - cnt and i + cnt <= 16000:
                Y_new[i] = 1 - (1 - Y[i - cnt]) * (1 - Y[i + cnt])
            elif 0 <= i - cnt:
                Y_new[i] = Y[i - cnt]
            else:
                Y_new[i] = Y[i + cnt]
        Y = Y_new
    
    if X[8000 + x] == 1 and Y[8000 + y] == 1:
        print("Yes")
    else:
        print("No")

    


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def LS2(): return list(sys.stdin.readline().rstrip())  #空白なし

s = LS2()
x,y = MI()

A = []  # 'F'
B = []  # 'T'
r = 0
for i in range(len(s)):
    if i == 0:
        if s[i] == 'F':
            A.append(1)
        else:
            r = 1
            B.append(1)
    else:
        if s[i] == s[i-1]:
            if r == 0:
                A[-1] += 1
            else:
                B[-1] += 1
        else:
            if r == 0:
                B.append(1)
            else:
                A.append(1)
            r = 1-r

C = []  # x軸方向
D = []  # y軸方向
if s[0] == 'F':
    x -= A[0]
    del A[0]
r = 0  # 0ならx軸方向、1ならy軸方向
for i in range(len(A)):
    if (r + B[i]) % 2 == 0:
        C.append(A[i])
        r = 0
    else:
        D.append(A[i])
        r = 1

# Cの各々の元を、1倍か-1倍して全て加えた時にxにできるか
# Dの各々の元を、1倍か-1倍して全て加えた時にyにできるか

if (x+sum(C)) % 2 != 0:
    print('No')
    exit()
x = (x+sum(C)) // 2

if (y+sum(D)) % 2 != 0:
    print('No')
    exit()
y = (y+sum(D)) // 2

if x < 0 or y < 0:
    print('No')
    exit()

# Cの元をいくつか選んで和をとることで、xを作れるか
# Dの元をいくつか選んで和をとることで、yを作れるか

C = [0] + C
from itertools import accumulate
E = list(accumulate(C))
e = 0
if x == 0:
    e = 1
for i in range(1,len(C)):
    for j in range(i,len(C)):
        if E[j] - E[i-1] == x:
            e = 1
if e == 0:
    print('No')
    exit()

D = [0] + D
from itertools import accumulate
F = list(accumulate(D))
f = 0
if y == 0:
    f = 1
for i in range(1,len(D)):
    for j in range(i,len(D)):
        if F[j] - F[i-1] == y:
            f = 1
if f == 0:
    print('No')
else:
    print('Yes')

Submission status: Accepted

Solution code:
from copy import copy
Ss = input() + "T"
X, Y = map(int, input().split())

d = [len(s) for s in Ss.split("T")]
x = d[0]
# x,y方向に分解
d_x = d[2::2]
d_y = d[1::2]

xs = set([x])
ys = set([0])
blx = [X in xs]
for d in d_x:
    # 各移動後に、X座標にいるかcheck
    xs_ = set()
    for x in xs:
        xs_.add(x+d)
        xs_.add(x-d)
    blx.append(X in xs_)
    xs = copy(xs_)

bly = []
for d in d_y:
    ys_ = set()
    for y in ys:
        ys_.add(y+d)
        ys_.add(y-d)
    bly.append(Y in ys_)
    ys = copy(ys_)

if blx[-1] and bly[-1]: print("Yes")
else: print("No")

Submission status: Accepted

Solution code:
s = input()
n = len(s)
x, y = map(int, input().split())
for i in range(n):
    if s[i]=='T':
        break
else:
    i += 1
dp = {i}
xs = []
ys = []
now = 0
xy = 'y'
for j in range(i+1, n+1):
    if j<n and s[j]=='F':
        now += 1
        continue
    if xy=='x':
        if now>0:
            xs.append(now)
        xy = 'y'
    else:
        if now>0:
            ys.append(now)
        xy = 'x'
    now = 0

for i in xs:
    newdp = set()
    for j in dp:
        newdp.add(j+i)
        newdp.add(j-i)
    dp = newdp
if x not in dp:
    print('No')
    exit(0)
dp = {0}
for i in ys:
    newdp = set()
    for j in dp:
        newdp.add(j+i)
        newdp.add(j-i)
    dp = newdp
if y in dp:
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
import copy

s = input()
target_x, target_y = map(int, input().split())

fl = s.split('T')
f_cnts = [ len(v) for v in fl ]

target_x -= f_cnts[0]
f_cnts = f_cnts[1:]

last_xs = set()
last_ys = set()
last_xs.add(0)
last_ys.add(0)
for i, f_cnt in enumerate(f_cnts):
    if i%2 == 0:
        next_y = f_cnts[i]
        next_last_ys = set()
        for y in list(last_ys):
            next_last_ys.add(y+next_y)
            next_last_ys.add(abs(y-next_y))
        last_ys = copy.deepcopy(next_last_ys)
    else:
        next_x = f_cnts[i]
        next_last_xs = set()
        for x in list(last_xs):
            next_last_xs.add(x+next_x)
            next_last_xs.add(abs(x-next_x))
        last_xs = copy.deepcopy(next_last_xs)


if (target_x in last_xs or -1*target_x in last_xs) and (target_y in last_ys or -1*target_y in last_ys):
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
s = input()
l = len(s)
X, Y = (int(x) for x in input().split())
F = s.split("T")
x_move = [f.count("F") for f in F[2::2]]
y_move = [f.count("F") for f in F[1::2]]
x_set = set()
x_set.add(F[0].count("F"))
y_set = set()
y_set.add(0)
for move in x_move:
    x_set = set(x + move for x in x_set) | set(x - move for x in x_set)
for move in y_move:
    y_set = set(y + move for y in y_set) | set(y - move for y in y_set)

if X in x_set and Y in y_set:
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
import numpy as np
s = input()
x, y = map(int, input().split())

i = 0
stock = 0
sl = []
while i < len(s):
    if s[i] == 'F':
        stock+=1
        i+=1
    else:
        sl.append(stock)
        stock = 0
        i+=1
else:
    sl.append(stock)

x-=sl[0]
ymove = sl[1::2]
xmove = sl[2::2]

dpx = np.zeros(16002).astype(int)
dpx[8000] = 1
for i in range(len(xmove)):
    idx = np.where(dpx==1)[0]
    ndpx = np.zeros(16002)
    ndpx[idx+xmove[i]] = True
    ndpx[idx-xmove[i]] = True
    dpx = ndpx

dpy= np.zeros(16002).astype(int)
dpy[8000] = 1
for i in range(len(ymove)):
    idx = np.where(dpy==1)[0]
    ndpy = np.zeros(16002)
    ndpy[idx+ymove[i]] = True
    ndpy[idx-ymove[i]] = True
    dpy = ndpy

if dpx[x+8000] == 1 and dpy[y+8000] == 1:
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
s=input()
x,y=map(int,input().split())
t=s.split("T")
x-=len(t[0])
dx,dy=[],[]

for i,tt in enumerate(t[1:]):
  if i%2==1:
    dx.append(len(tt))
  else:
    dy.append(len(tt))

def is_ok(n,l):
  dp=set([0])
  for d in l:
    t=[]
    for v in dp:
      t.append(v+d)
      t.append(v-d)
    dp=set(t)
  return True if n in dp else False

if is_ok(x,dx) and is_ok(y,dy):
  print("Yes")
else:
  print("No")

Submission status: Accepted

Solution code:
# coding: utf-8
# hello worldと表示する
#float型を許すな
#numpyはpythonで
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial,sqrt
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

s=input().rstrip().split("T")
x,y=MI()
#print(s)
lisx=[]
lisy=[]
x-=len(s[0])
for i in range(1,len(s)):
    if i%2==0:
        lisx.append(len(s[i]))
    else:
        lisy.append(len(s[i]))
resx=[[] for i in range(len(lisx)+1)]
resy=[[] for i in range(len(lisy)+1)]
resx[0]=[0]
resy[0]=[0]
#print(lisx)
for i in range(len(lisx)):
    for j in range(len(resx[i])):
        resx[i+1].append(resx[i][j]+lisx[i])
        resx[i+1].append(resx[i][j]-lisx[i])
    resx[i+1]=list(set(resx[i+1]))
#print(resx)
for i in range(len(lisy)):
    for j in range(len(resy[i])):
        resy[i+1].append(resy[i][j]+lisy[i])
        resy[i+1].append(resy[i][j]-lisy[i])
    resy[i+1]=list(set(resy[i+1]))
#print(lisy)
#print(resy)
if x in resx[-1] and y in resy[-1]:
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
def main():

    s = str(input())
    x, y = map(int, input().split())

    n = len(s)

    dir = 1
    dx = []
    dy = []
    cnt = 0
    for i in range(n):
        if s[i] == 'F':
            cnt += 1
        else:
            if dir == 1:
                dx.append(cnt)
                cnt = 0
                dir = -1
            else:
                dy.append(cnt)
                cnt = 0
                dir = 1
    else:
        if dir == 1:
            dx.append(cnt)
        else:
            dy.append(cnt)
    #print(dx)
    #print(dy)
    D = 8000*2+1

    import numpy as np
    dpx = [0]*(len(dx)+1)
    dpy = [0]*(len(dy)+1)
    dpx[0] = np.zeros(D, np.bool)
    dpy[0] = np.zeros(D, np.bool)
    dpx[0][8000] = 1
    dpy[0][8000] = 1
    for i, d in enumerate(dx):
        if i == 0:
            b = np.zeros(D, np.bool)
            b[d:] |= dpx[i][:D-d]
            dpx[i+1] = b
        else:
            b = np.zeros(D, np.bool)
            b[d:] |= dpx[i][:D-d]
            b[:D-d] |= dpx[i][d:]
            dpx[i+1] = b

    for i, d in enumerate(dy):
        b = np.zeros(D, np.bool)
        b[d:] |= dpy[i][:D-d]
        b[:D-d] |= dpy[i][d:]
        dpy[i+1] = b

    if dpx[-1][8000+x] == 1 and dpy[-1][8000+y] == 1:
        print('Yes')
    else:
        print('No')

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys

YES = "Yes"  # type: str
NO = "No"  # type: str


def _solve(s, n, f):
    m = sum(f)
    r = range(n-m-1, n+m+1)
    cur = set([s])
    for ff in f:
        nex = set()
        for c in cur:
            for op in (1, -1):
                t = c + op * ff
                if t not in r:
                    continue
                nex.add(t)
        cur = nex
    return n in cur

def solve(s: str, x: int, y: int):
    f = tuple(map(lambda x: len(x), s.split("T")))
    return YES if _solve(f[0], x, f[2::2]) and _solve(0, y, f[1::2]) else NO

# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    s = next(tokens)  # type: str
    x = int(next(tokens))  # type: int
    y = int(next(tokens))  # type: int
    print(solve(s, x, y))

def test():
    import doctest
    doctest.testmod()

if __name__ == '__main__':
    #test()
    main()

Submission status: Accepted

Solution code:
s = input()
x, y = map(int, input().split())
y = abs(y)

f = s.find('T')
if f >= 0:
    x = abs(x - f)
    s = s[f:]
else:
    if x == len(s) and y == 0:
        print('Yes')
    else:
        print('No')
    exit()

lx, ly = [], []
flag = True
n = 0
s += 'T'
for i in s:
    if i == 'F':
        n += 1
    else:
        if n > 0:
            if flag:
                lx.append(n)
            else:
                ly.append(n)
            n = 0
        flag = not flag

lx.sort()
ly.sort()
sx = sum(lx)
sy = sum(ly)

if sx < x or (sx - x) % 2 == 1 or sy < y or (sy - y) % 2 == 1:
    print('No')
    exit()


def main(x, sx, lx):
    if x == sx:
        return True

    goal = (sx - x) // 2
    # return (sum of some lx == goal)
    dp = [False] * (goal + 1)
    dp[0] = True
    for i in lx:
        if i > goal:
            return False
        for j in range(goal - i, -1, -1):
            if dp[j]:
                dp[j+i] = True
        if dp[goal]:
            return True
    return False


if main(x, sx, lx) and main(y, sy, ly):
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
s=input()+"T"
x,y=map(int,input().split())
n=len(s)
prev=-1
cnt=0
x_,y_=[],[]
for i in range(n):
    if s[i]=="T":
        if cnt%2:
            y_.append(i-prev-1)
        else:
            x_.append(i-prev-1)
        cnt+=1
        prev=i
prevx=[0]*(2*n+1)
prevy=[0]*(2*n+1)
prevx[n+x_[0]]=1
prevy[n]=1
x_=x_[1:]
for num in x_:
    curx=[0]*(2*n+1)
    for i in range(2*n+1):
        if prevx[i]:
            if i-num>=0:
                curx[i-num]=1
            if i+num<=2*n:
                curx[i+num]=1
    prevx=curx
for num in y_:
    cury=[0]*(2*n+1)
    for i in range(2*n+1):
        if prevy[i]:
            if i-num>=0:
                cury[i-num]=1
            if i+num<=2*n:
                cury[i+num]=1
    prevy=cury
if prevy[y+n] and prevx[x+n]:
    print("Yes")
else:
    print("No")
#print(x_)
#print(y_)

Submission status: Accepted

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
import math
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7


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

s = input()
x, y = map(int, input().split())

dpx = {0}
dpy = {0}

f = s.split("T")

fx = []
fy = []

for i, fi in enumerate(f):
    if i % 2:
        fy.append(len(fi))
    else:
        fx.append(len(fi))

for i, fxi in enumerate(fx):
    nex = set([])
    for j in dpx:
        nex.add(j+fxi)
        if i > 0:
            nex.add(j-fxi)
    dpx = nex

for fyi in fy:
    nex = set([])
    for j in dpy:
        nex.add(j+fyi)
        nex.add(j-fyi)
    dpy = nex

if x in dpx and y in dpy:
    print('Yes')
else:
    print('No')