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:
# tle
# from copy import deepcopy
# s = list(input())
# a, b = map(int, input().split())
# def searchpath(pos, dir, st):
#     pos = deepcopy(pos)
#     dir = deepcopy(dir)
#     st  = deepcopy(st)
#     while len(st)>0:
#         i = st.pop(0)
#         if i == 'F':
#             if dir == 'r':
#                 pos = [pos[0]+1, pos[1]]
#             if dir == 'l':
#                 pos = [pos[0]-1, pos[1]]
#             if dir == 'u':
#                 pos = [pos[0], pos[1]+1]
#             if dir == 'd':
#                 pos = [pos[0], pos[1]-1]
#             if len(st) == 0 and pos == [a, b]:
#                 return 1
#         if i == 'T':
#             if dir == 'r' or dir == 'l':
#                 if searchpath(pos, 'u', st)==1 or searchpath(pos, 'd', st)==1:
#                     return 1
#             if dir == 'u' or dir == 'd':
#                 if searchpath(pos, 'r', st)==1 or searchpath(pos, 'l', st)==1:
#                     return 1
#             break;
#     return -1
# ans = searchpath([0,0], 'r', s)
# if ans == 1:
#     print('Yes' , flush=True)
# else:
#     print('No' , flush=True)


s = input().split('T')
a, b = map(int, input().split())

current_x = len(s[0])
current_y = 0

# for i in s[2::2]: # cant calculate order
for i in sorted([len(j) for j in s[2::2]])[::-1]:
    if current_x < a:
        current_x += i
    else:
        current_x -= i
for i in sorted([len(j) for j in s[1::2]])[::-1]:
    if current_y < b:
        current_y += i
    else:
        current_y -= i

if current_x==a and current_y==b:
    print('Yes', flush=True)
else:
    print('No', flush=True)

Submission status: Accepted

Solution code:
s = list(input())
s.append('T')
X,Y =map(int, input().split())
curX = True
cnt = 0
X_s = []
Y_s = []
for i,c in enumerate(s):
    if c == 'T':
        if curX:
            X_s.append(cnt)
        else:
            Y_s.append(cnt)
        curX = not curX
        cnt=0
    else:
        cnt+=1

init = 0
if s[0] == 'F':
    init = X_s.pop(0)
X -= init

SETX = set([0])
SETY = set([0])

for TX in X_s:
    ADD = set()
    for SX in SETX:
        ADD.add(SX+TX)
    SETX.add(TX)
    SETX = ADD | SETX
for TY in Y_s:
    ADD = set()
    for SY in SETY:
        ADD.add(SY+TY)
    SETY.add(TY)
    SETY = ADD | SETY
# 合計から目的地の差
MODX = sum(X_s)-X
MODY = sum(Y_s)-Y
# print(SETX, SETY, MODX, MODY)
if MODX % 2 == 0 and MODX//2 in SETX and MODY % 2 == 0 and MODY//2 in SETY:
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
S = input()
X,Y = map(int,input().split())

x = True # x軸方向を向いている

Slist = []
import itertools
for key,g in itertools.groupby(S):
  num = len(list(g))
  Slist.append((key, num))
  
xdp = set()
ydp = set([0])
ind = 0

if Slist[0][0] == "F":
  xdp.add(Slist[0][1])
  ind += 1
else:
  xdp.add(0)
  
for i in range(ind, len(Slist)):
  if Slist[i][0] == "T":
    if Slist[i][1] % 2 == 1:
      x ^= True
    continue
  step = Slist[i][1]
  if x:
    next_dp = set()
    for xpos in xdp:
      next_dp.add(xpos + step)
      next_dp.add(xpos - step)
    xdp = next_dp
  else:
    next_dp = set()
    for ypos in ydp:
      next_dp.add(ypos + step)
      next_dp.add(ypos - step)
    ydp = next_dp
    
if X in xdp and Y in ydp:
  print("Yes")
else:
  print("No")

Submission status: Accepted

Solution code:
from collections import deque
s=list(input())
x,y=map(int,input().split())
#print(s,x,y)
i=0
xflag=1
flag=0
xax=deque()
yax=deque()
cnt=0
while i<len(s):
    if s[i]=="F":
        cnt=cnt+1
    else:
        if cnt!=0:
            if xflag==1:
                xax.append(cnt)
            else:
                yax.append(cnt)
        xflag=(xflag+1)%2
        cnt=0
    i=i+1
if cnt!=0:
    if xflag == 1:
        xax.append(cnt)
    else:
        yax.append(cnt)
#print(xax,yax)
xdeq=deque()
ydeq=deque()
if (len(xax)>0)and(s[0]=="F"):
    x0=xax.popleft()
    xdeq.append(x0)
else:
    xdeq.append(0)
ydeq.append(0)
#print(xdeq,xax)
while len(xax)>0:
    subadd=xax.popleft()
    xdeq2=[]
    while len(xdeq)>0:
        xd=xdeq.popleft()
        xdeq2.append(xd-subadd)
        xdeq2.append(xd+subadd)
    xdeq2=list(set(xdeq2))
    for i in xdeq2:
        xdeq.append(i)
    #print(xdeq)
#print(xdeq)
while len(yax)>0:
    subadd=yax.popleft()
    ydeq2=[]
    while len(ydeq)>0:
        yd=ydeq.popleft()
        ydeq2.append(yd-subadd)
        ydeq2.append(yd+subadd)
    ydeq2=list(set(ydeq2))
    for i in ydeq2:
        ydeq.append(i)
    #print(ydeq)
#print(ydeq)
xlist=list(xdeq)
ylist=list(ydeq)
for i in xlist:
    for j in ylist:
        if (i==x)and(j==y):
            flag=1
            break
    if flag==1:
        break
if flag==1:
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter


import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(readline())


def read_int_n():
    return list(map(int, readline().split()))


def read_float():
    return float(readline())


def read_float_n():
    return list(map(float, readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(S, X, Y):
    m = list(map(lambda x: len(x), S.split('T')))

    X -= m[0]
    ym = m[1::2]
    xm = m[2::2]

    memo = {0}
    for dx in xm:
        nm = set()
        for x in memo:
            nm.add(x+dx)
            nm.add(x-dx)
        memo = nm
    if X not in memo:
        return 'No'

    memo = {0}
    for dy in ym:
        nm = set()
        for y in memo:
            nm.add(y+dy)
            nm.add(y-dy)
        memo = nm
    if Y not in memo:
        return 'No'

    return 'Yes'




def main():
    S = read_str()
    X, Y = read_int_n()
    print(slv(S, X, Y))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from fractions import Fraction
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations, accumulate
from operator import add, mul, sub, itemgetter, attrgetter


import sys
# sys.setrecursionlimit(10**6)
# readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(readline())


def read_int_n():
    return list(map(int, readline().split()))


def read_float():
    return float(readline())


def read_float_n():
    return list(map(float, readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.perf_counter()
        ret = f(*args, **kwargs)
        e = time.perf_counter()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(S, X, Y):
    n = 0
    m = []
    for c in S:
        if c == 'T':
            m.append(n)
            n = 0
        else:
            n += 1
    else:
        m.append(n)

    X -= m.pop(0)
    ym = m[::2]
    xm = m[1::2]

    memo = {0}
    for dx in xm:
        nm = set()
        for x in memo:
            nm.add(x+dx)
            nm.add(x-dx)
        memo = nm
    if X not in memo:
        return 'No'

    memo = {0}
    for dy in ym:
        nm = set()
        for y in memo:
            nm.add(y+dy)
            nm.add(y-dy)
        memo = nm
    if Y not in memo:
        return 'No'

    return 'Yes'




def main():
    S = read_str()
    X, Y = read_int_n()
    print(slv(S, X, Y))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def isok(f,p):
  s=0
  if not f and p==0:return 1
  for i,j in enumerate(f):
    s+=j
    if s>=p:break
  else:return 0
  for j in f[i+1:]:
    if s>=p:s-=j
    else:s+=j
  return s==p
s=input()
x,y=map(int,input().split())
f=list(map(len,s.split('T')))
x-=f[0]
x,y=abs(x),abs(y)
xf=sorted(f[2::2])[::-1]
yf=sorted(f[1::2])[::-1]
print(['No','Yes'][isok(xf,x) and isok(yf,y)])

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
from itertools import product
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
S = readline().decode().rstrip()
x,y = map(int,readline().split())
L = [len(i) for i in S.split('T')]
x -= L[0]
X = L[2::2]
Y = L[1::2]

dx = {0}
dy = {0}

for i in X:
    dx = {x+j for x,j in product(dx,[i,-i])}
for i in Y:
    dy = {y+j for y,j in product(dy,[i,-i])}

if x in dx and y in dy:
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

S = readline().decode().rstrip()
N = len(S)
x,y = map(int,readline().split())
t_cnt = 0
cnt_x1 = 0
cnt_x2 = 0
cnt_y = 0
X = []
Y = []
for i in range(N):
    if S[i] == 'F':
        if t_cnt == 0:
            cnt_x1 += 1
        else:
            if t_cnt % 2 == 0:
                cnt_x2 += 1
            else:
                cnt_y += 1
    else:
        t_cnt += 1
        if cnt_x2 != 0:
            X.append(cnt_x2)
            cnt_x2 = 0
        if cnt_y != 0:
            Y.append(cnt_y)
            cnt_y = 0
            
if cnt_x2 != 0:
    X.append(cnt_x2)
    cnt_x2 = 0
if cnt_y != 0:
    Y.append(cnt_y)
    cnt_y = 0

xN = len(X)
yN = len(Y)    
sumX = sum(X)
sumY = sum(Y)
x -= cnt_x1

if sumX - x < 0 or (sumX - x) % 2 != 0:
    print('No')
    sys.exit()
else:  
    xx = (sumX - x) // 2
if sumY - y < 0 or (sumY - y) % 2 != 0:
    print('No')
    sys.exit()
else:  
    yy = (sumY - y) // 2
    
dp_x = [0]*(xx+1) 
dp_x[0] = 1
for i in range(xN):
    w = X[i]
    for j in range(xx,w-1,-1):
        dp_x[j] = dp_x[j] or dp_x[j-w]
        
dp_y = [0]*(yy+1) 
dp_y[0] = 1
for i in range(yN):
    w = Y[i]
    for j in range(yy,w-1,-1):
        dp_y[j] = dp_y[j] or dp_y[j-w]

if dp_x[xx] and dp_y[yy]:
    print('Yes')
else:
    print('No')

Submission status: Accepted

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

for n in range(1,len(s)):
  XY[n%2].append(len(s[n]))

X,Y = XY
X = sorted(X)[::-1]
Y = sorted(Y)[::-1]

for n in X:
  if 0<x:
    x-=n
  else:
    x+=n

for n in Y:
  if 0<y:
    y-=n
  else:
    y+=n

if (x,y)==(0,0):
  print("Yes")
else:
  print("No")

Submission status: Accepted

Solution code:
s = input()
x, y = map(int, input().split())
X = 0
num = 0
while num <= len(s) - 1:
    if s[num] == "F":
        X += 1
        num += 1
    else:
        num += 1
        break
flag = False
move_x = []
move_y = []
temp = 0
while num <= len(s) - 1:
    if s[num] == "F":
        temp += 1
        num += 1
    else:
        if flag == False:
            move_y.append(temp)
            flag = True
        else:
            move_x.append(temp)
            flag = False
        num += 1
        temp = 0
else:
    if flag == False:
        move_y.append(temp)
    else:
        move_x.append(temp)
set_x = {X}
set_y = {0}
for i in move_x:
    temp = set()
    for j in set_x:
        temp.add(j + i)
        temp.add(j - i)
    set_x = temp
for i in move_y:
    temp = set()
    for j in set_y:
        temp.add(j + i)
        temp.add(j - i)
    set_y = temp
if x in set_x and y in set_y:
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    S = list(input().split("T"))
    gx, gy = map(int, input().split())

    to_X = 0
    init_x = len(S[0])
    S.pop(0)
    X, Y = [], []
    for s in S:
        X.append(len(s)) if to_X else Y.append(len(s))
        to_X ^= 1

    now_x = {init_x}
    for x in X:
        tmp = set()
        for prev_x in now_x:
            tmp.add(prev_x + x)
            tmp.add(prev_x - x)
        now_x = tmp

    now_y = {0}
    for y in Y:
        tmp = set()
        for prev_y in now_y:
            tmp.add(prev_y + y)
            tmp.add(prev_y - y)
        now_y = tmp

    print("Yes" if gx in now_x and gy in now_y else "No")


if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
import sys

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')
in_nl = lambda: list(map(int, readline().split()))
in_nl2 = lambda H: [in_nl() for _ in range(H)]
in_map = lambda: [s == ord('.') for s in readline() if s != ord('\n')]
in_map2 = lambda H: [in_map() for _ in range(H)]
in_all = lambda: map(int, read().split())


def main():

    S = in_s() + "T"
    N = len(S)

    X, Y = in_nn()

    x_num = []
    y_num = []

    f = False
    first = True

    cnt = 0
    for i in range(N):
        if S[i] == "T":

            if cnt > 0:
                if f:
                    if first:
                        Y -= cnt
                    else:
                        y_num.append(cnt)
                else:
                    if first:
                        X -= cnt
                    else:
                        x_num.append(cnt)
            cnt = 0
            f = not f
            first = False
        else:
            cnt += 1

    x_ok = False
    y_ok = False

    if len(x_num) == 0:
        if X == 0:
            x_ok = True
    else:
        dp_x = [False] * N
        dp_x[0] = True
        for tx in x_num:
            for i in range(N - 1, -1, -1):
                if i + tx < N and dp_x[i]:
                    dp_x[i + tx] = True

        xsum = sum(x_num)
        for i in range(N):
            if dp_x[i]:
                if abs(i - abs(xsum - i)) == abs(X):
                    x_ok = True

    if len(y_num) == 0:
        if Y == 0:
            y_ok = True
    else:
        dp_y = [False] * N
        dp_y[0] = True
        for ty in y_num:
            for i in range(N - 1, -1, -1):
                if i + ty < N and dp_y[i]:
                    dp_y[i + ty] = True

        ysum = sum(y_num)
        for i in range(N):
            if dp_y[i]:
                if abs(i - abs(ysum - i)) == abs(Y):
                    y_ok = True

    # print(X, Y)
    # print(x_num)
    # print(y_num)

    if x_ok and y_ok:
        print("Yes")
    else:
        print("No")


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
s=input().split("T")
x,y=map(int,input().split())
a,b=[len(i)for i in s[0::2]],[len(i)for i in s[1::2]]
x-=a[0]
a,b=sorted(a[1:]),sorted(b)
while a:
 if x<0:x+=a.pop()
 else:x-=a.pop()
while b:
 if y<0:y+=b.pop()
 else:y-=b.pop()
print("YNeos"[x!=0 or y!=0::2])

Submission status: Accepted

Solution code:
import sys
import math
import copy
import random
from heapq import heappush, heappop, heapify
from functools import cmp_to_key
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, Counter
# sys.setrecursionlimit(1000000)

# input aliases
input = sys.stdin.readline
getS = lambda: input().strip()
getN = lambda: int(input())
getList = lambda: list(map(int, input().split()))
getZList = lambda: [int(x) - 1 for x in input().split()]

INF = float("inf")
MOD = 10**9 + 7
divide = lambda x: pow(x, MOD-2, MOD)

def nck(n, k, kaijyo):
    return (npk(n, k, kaijyo) * divide(kaijyo[k])) % MOD

def npk(n, k, kaijyo):
    if k == 0 or k == n:
        return n % MOD
    return (kaijyo[n] * divide(kaijyo[n-k])) % MOD

def fact_and_inv(SIZE):
    inv = [0] * SIZE  # inv[j] = j^{-1} mod MOD
    fac = [0] * SIZE  # fac[j] = j! mod MOD
    finv = [0] * SIZE  # finv[j] = (j!)^{-1} mod MOD
    inv[1] = 1
    fac[0] = fac[1] = 1
    finv[0] = finv[1] = 1
    for i in range(2, SIZE):
        inv[i] = MOD - (MOD // i) * inv[MOD % i] % MOD
        fac[i] = fac[i - 1] * i % MOD
        finv[i] = finv[i - 1] * inv[i] % MOD

    return fac, finv

def renritsu(A, Y):
    # example 2x + y = 3, x + 3y = 4
    # A = [[2,1], [1,3]])
    # Y = [[3],[4]] または [3,4]
    A = np.matrix(A)
    Y = np.matrix(Y)
    Y = np.reshape(Y, (-1, 1))
    X = np.linalg.solve(A, Y)

    # [1.0, 1.0]
    return X.flatten().tolist()[0]

class TwoDimGrid:
    # 2次元座標 -> 1次元
    def __init__(self, h, w, wall="#"):
        self.h = h
        self.w = w
        self.size = (h+2) * (w+2)
        self.wall = wall
        self.get_grid()
        # self.init_cost()

    def get_grid(self):
        grid = [self.wall * (self.w + 2)]
        for i in range(self.h):
            grid.append(self.wall + getS() + self.wall)

        grid.append(self.wall * (self.w + 2))
        self.grid = grid
    def init_cost(self):
        self.cost = [INF] * self.size

    def pos(self, x, y):
        # 壁も含めて0-indexed 元々の座標だけ考えると1-indexed
        return y * (self.w + 2) + x
    def getgrid(self, x, y):
        return self.grid[y][x]
    def get(self, x, y):
        return self.cost[self.pos(x, y)]
    def set(self, x, y, v):
        self.cost[self.pos(x, y)] = v
        return
    def show(self):
        for i in range(self.h+2):
            print(self.cost[(self.w + 2) * i:(self.w + 2) * (i+1)])
    def showsome(self, tgt):
        for t in tgt:
            print(t)
        return
    def showsomejoin(self, tgt):
        for t in tgt:
            print("".join(t))
        return

    def search(self):
        grid = self.grid
        move = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        move_eight = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
        # for i in range(1, self.h+1):
        #     for j in range(1, self.w+1):
        #         cx, cy = j, i
        #         for dx, dy in move_eight:
        #             nx, ny = dx + cx, dy + cy

def solve():
    s = getS()
    x, y = getList()
    ls = len(s)
    hori = True
    h,v = [],[]
    cnt = 0
    for c in s:
        if c == "F":
            cnt += 1
        else:
            if hori:
                h.append(cnt)
            else:
                v.append(cnt)
            cnt = 0
            hori = not hori

    if cnt != 0:
        if hori:
            h.append(cnt)
        else:
            v.append(cnt)

    # print(h, v)
    x -= h[0]
    h[0] = 0
    dp = [0] * (ls * 2 + 100)
    dp[ls + 50] = 1
    for num in h:
        tmp = [0] * (len(dp))
        for i, d in enumerate(dp):
            if d == 1:
                tmp[i - num] = 1
                tmp[i + num] = 1
        dp = tmp
    # print(dp)
    if dp[x + ls + 50] == 0:
        print("No")
        return

    dp = [0] * (ls * 2 + 100)
    dp[ls + 50] = 1
    for num in v:
        tmp = [0] * (len(dp))
        for i, d in enumerate(dp):
            if d == 1:
                tmp[i - num] = 1
                tmp[i + num] = 1
        dp = tmp
    # print(dp)
    if dp[y + ls + 50] == 0:
        print("No")
        return

    print("Yes")
    return


def main():
    n = getN()
    for _ in range(n):
        s = "".join([random.choice(["F", "T"]) for i in range(20)])
        print(s)
        solve(s, 1, 0)

    return
if __name__ == "__main__":
    # main()
    solve()

Submission status: Accepted

Solution code:
'''
研究室PCでの解答
'''
import math
#import numpy as np
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7 #998244353
dir = [(-1,0),(1,0),(0,-1),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"


def main():
    s = input()
#    s = "FT"*4000
    x,y = map(int,ipt().split())
#    x = 2000
#    y = 2000

    move = [[],[]]
    p = 0
    nm = 0
    for i in s:
        if i == "T":
            move[p].append(nm)
            nm = 0
            p = 1-p
        else:
            nm += 1
    move[p].append(nm)

    st = set([move[0][0]])
    for i in move[0][1::]:
        nst = set()
        for j in st:
            nst.add(j+i)
            nst.add(j-i)
        st = nst.copy()
    if not x in st:
        print("No")
        exit()

    st = set([0])
    for i in move[1]:
        nst = set()
        for j in st:
            nst.add(j+i)
            nst.add(j-i)
        st = nst.copy()
    if not y in st:
        print("No")
        exit()

    print("Yes")

    return None

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    S = input()
    X, Y = map(int, input().split())

    S = list(map(len, S.split("T")))
    init_x = S[0]
    is_x = 0
    to_x, to_y = [], []
    for i in range(1, len(S)):
        if S[i]:
            to_x.append(S[i]) if is_x else to_y.append(S[i])
        is_x ^= 1

    now_x = {init_x}
    for x in to_x:
        tmp = set()
        for now in now_x:
            tmp.add(now - x)
            tmp.add(now + x)
        now_x = tmp

    now_y = {0}
    for y in to_y:
        tmp = set()
        for now in now_y:
            tmp.add(now - y)
            tmp.add(now + y)
        now_y = tmp

    print("Yes" if X in now_x and Y in now_y else "No")


if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
import sys
import math
import collections
import bisect
import itertools

# import numpy as np

sys.setrecursionlimit(10 ** 7)
INF = 10 ** 16
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline().rstrip())
ns = lambda: map(int, sys.stdin.readline().rstrip().split())
na = lambda: list(map(int, sys.stdin.readline().rstrip().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().rstrip().split()))


# ===CODE===

def main():
    s = list(input())
    x, y = ns()

    axis = [[], []]

    cnt = 0
    sw = 0
    for si in s:
        if si == "F":
            cnt += 1
        else:
            axis[sw].append(cnt)
            cnt = 0
            sw ^= 1
    axis[sw].append(cnt)
    if len(axis[0]) > 0:
        x -= axis[0][0]
        del axis[0][0]

    x_cand = {0}
    y_cand = {0}

    for xi in axis[0]:
        if xi == 0:
            continue
        nxt = set()
        for xc in x_cand:
            nxt.add(xc + xi)
            nxt.add(xc - xi)
        x_cand = nxt

    for yi in axis[1]:
        if yi == 0:
            continue
        nxt = set()
        for yc in y_cand:
            nxt.add(yc + yi)
            nxt.add(yc - yi)
        y_cand = nxt

    if x in x_cand and y in y_cand:
        print("Yes")
    else:
        print("No")

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.buffer.readline

#sys.setrecursionlimit(10**9)
#from functools import lru_cache

def RD(): return sys.stdin.read()
def II(): return int(input())
def MI(): return map(int,input().split())
def MF(): return map(float,input().split())
def LI(): return list(map(int,input().split()))
def LF(): return list(map(float,input().split()))
def TI(): return tuple(map(int,input().split()))
# rstrip().decode()


def main():
	s=input().rstrip().decode()+"T"
	x,y=MI()
	X=[]
	Y=[]

	i=0

	if s[0]=="F":
		for ss in s:
			if ss=="F":
				x-=1
				i+=1
			else:
				break
	#print(x,y,i)

	while True:
		ii=s.find("T",i+1)
		if ii==-1:
			break
		Y.append(ii-i-1)

		i=s.find("T",ii+1)
		if i==-1:
			break
		X.append(i-ii-1)
	#print(X,Y)


	s=set([0])
	ss=set()
	for i in X:
		for j in s:
			ss.add(j+i)
			ss.add(j-i)
		s=ss.copy()
		ss=set()
		#print(i,s,ss)
	#print(s)

	if x not in s:
		print("No")
		exit()

	s=set([0])
	ss=set()
	for i in Y:
		for j in s:
			ss.add(j+i)
			ss.add(j-i)
		s=ss.copy()
		ss=set()
	#print(s)

	if y not in s:
		print("No")
		exit()

	print("Yes")






















if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
s = list(input())
x, y = map(int, input().split())
a = [[], []]
b = [0, 0]
j = 0
cnt = 0
for i in s:
    if i == "F":
        if j == 0:
            x -= 1
        else:
            cnt += 1
    else:
        if cnt > 0:
            a[j % 2].append(cnt)
            b[j % 2] += cnt
        j += 1
        cnt = 0
if cnt > 0:
    a[j % 2].append(cnt)
    b[j % 2] += cnt
x, y = abs(x), abs(y)
lx, ly = len(a[0]), len(a[1])
if b[0] < x or b[1] < y:
    print("No")
    exit()
if lx > 0:
    dp = [[0] * (2 * b[0] + 1) for _ in range(lx + 1)]
    dp[0][b[0]] = 1
    for i in range(lx):
        for j in range(2 * b[0] + 1):
            if dp[i][j] == 1:
                dp[i + 1][j + a[0][i]] = 1
                dp[i + 1][j - a[0][i]] = 1
    if dp[lx][b[0] + x] == 0:
        print("No")
        exit()
if ly > 0:
    dp = [[0] * (2 * b[1] + 1) for _ in range(ly + 1)]
    dp[0][b[1]] = 1
    for i in range(ly):
        for j in range(2 * b[1] + 1):
            if dp[i][j] == 1:
                dp[i + 1][j + a[1][i]] = 1
                dp[i + 1][j - a[1][i]] = 1
    if dp[ly][b[1] + y] == 0:
        print("No")
        exit()
print("Yes")

Submission status: Accepted

Solution code:
import sys
read=sys.stdin.read
readline=sys.stdin.readline

def main():
  def isinsums(x,lst):
    s=sum(lst)
    t=(s+x)//2
    if s==0 and x==0:
      return True
    if (s-x)%2 or t<0:
      return False
    t=(s+x)//2
    m1=(1<<(t+1))-1
    m2=1<<t
    sums=0
    for e in lst:
      sums=(sums|(1+sums)<<e)&m1
      if (sums+1)&m2>0:
        return True
    return False
  s=readline().strip()
  x,y=map(int,readline().split())
  
  s=s.replace('TF','T F')
  s=s.replace('FT','F T')
  bs=s.split()
  if bs[0][0]=='F':
    x-=len(bs[0])
    del bs[0]
  xy=[[],[]]
  f=0
  for i,e in enumerate(bs):
    if not i%2:
      l=len(e)
    else:
      f^=l%2
      xy[f].append(len(e))
  if isinsums(x,xy[0]) and isinsums(y,xy[1]):
    print('Yes')
  else:
    print('No')

if __name__=='__main__':
  main()

Submission status: Accepted

Solution code:
import sys
read=sys.stdin.read
readline=sys.stdin.readline

def isinsums(x,lst):
  s=sum(lst)
  t=(s+x)//2
  if s==0 and x==0:
    return True
  if (s-x)%2 or t<0:
    return False
  t=(s+x)//2
  m1=(1<<(t+1))-1
  m2=1<<t
  sums=0
  for e in lst:
    sums=(sums|(1+sums)<<e)&m1
  sums|=1
  if (sums)&m2>0:
    return True
  return False

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

s=s.replace('TF','T F')
s=s.replace('FT','F T')
bs=s.split()
if bs[0][0]=='F':
  x-=len(bs[0])
  del bs[0]

xy=[[],[]]
f=0
for i,e in enumerate(bs):
  if not i%2:
    l=len(e)
  else:
    f^=l%2
    xy[f].append(len(e))
if isinsums(x,xy[0]) and isinsums(y,xy[1]):
  print('Yes')
else:
  print('No')

Submission status: Accepted

Solution code:
import sys

def main():
  s = input()
  n = len(s)
  x, y = map(int, input().split())
  
  move = [0]
  for i in range(n):
    if s[i] == "F":
      move[-1] += 1
    else:
      move.append(0)
  
  move_x = move[2::2]
  move_y = move[1::2]
  move_a = move[0]
  
  for start, lis in zip([x-move_a, y], [move_x, move_y]):
    move_range = sum(lis)
    if abs(start) > move_range:
      print("No")
      sys.exit()
    
    dp = 2**move_range
    for value in lis:
      dp = (dp >> value)|(dp << value)
    if not (dp>>(move_range+start))&1:
      print("No")
      sys.exit()
  
  print("Yes")
  
  
if __name__ == "__main__":
  main()

Submission status: Accepted

Solution code:
def main():
  s = input()
  n = len(s)
  x, y = map(int, input().split())

  dpx = [[False, False] for _ in range(n+2)]
  dpy = [[False, False] for _ in range(n+2)]

  dpx[0][0] = True
  dpy[0][0] = True
  x_turn = False
  y_turn = False
  judge = True
  turn = False
  xcount = 0
  count = 0
  for i in range(n):
    if judge and s[i] == "F":
      xcount += 1
      continue
    if judge:
      judge = False
      turn = False if turn else True
      continue
    if s[i] == "F":
      count += 1
      if i != n-1:
        continue
    if turn:
      y_turn = False if y_turn else True
      if y_turn:
        p, q = 0, 1
      else:
        p, q = 1, 0
      for i in range(n+1):
        
        dpy[i][q] = False
      for i in range(n+1):
        if dpy[i][p]:
          dpy[abs(i-count)][q] = True
          dpy[i+count][q] = True
    else:
      x_turn = False if x_turn else True
      if x_turn:
        p, q = 0, 1
      else:
        p, q = 1, 0
      for i in range(n+1):
        dpx[i][q] = False
      for i in range(n+1):
        if dpx[i][p]:
          dpx[abs(i-count)][q] = True
          dpx[i+count][q] = True
    turn = False if turn else True
    count = 0
  
  p = 1 if x_turn else 0
  q = 1 if y_turn else 0
  x -= xcount
  if abs(x) > n:
    print("No")
  elif dpx[abs(x)][p] and dpy[abs(y)][q]:
    print("Yes")
  else:
    print("No")
  
if __name__ == "__main__":
  main()