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:
s = input()
x, y = map(int, input().split())
d = [len(i) for i in s.split('T')]
 
s1 = d[2::2]
s2 = d[1::2]
 
now_x = [0]
now_y = [0]

x -= d[0]

for i in s1:
    nx = set()
    for j in now_x:
        nx.add(j-i)
        nx.add(j+i)
    now_x = nx

for i in s2:
    ny = set()
    for j in now_y:
        ny.add(j-i)
        ny.add(j+i)
    now_y = ny

if x in now_x and y in now_y:
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
#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
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)
x0=len(s[0])
x=x-x0
X=[]
Y=[]
for i in range(1,len(s)):
    if i%2==1:
        Y.append(len(s[i]))
    else:
        X.append(len(s[i]))
#print(x,y)
#print(X)
#print(Y)
dpx=[[0]*(2*sum(X)+1) for i in range(len(X)+1)]
dpx[0][sum(X)]=1
for i in range(len(X)):
    for j in range(len(dpx[i])):
        if dpx[i][j]==1:
            dpx[i+1][j+X[i]]=1
            dpx[i+1][j-X[i]]=1
#print(dpx)
dpy=[[0]*(2*sum(Y)+1) for i in range(len(Y)+1)]
dpy[0][sum(Y)]=1
for i in range(len(Y)):
    for j in range(len(dpy[i])):
        if dpy[i][j]==1:
            dpy[i+1][j+Y[i]]=1
            dpy[i+1][j-Y[i]]=1
##print(sum(X)+x)
#print(sum(Y)+y)
if sum(X)+x<0 or sum(X)+x>=len(dpx[-1]) or sum(Y)+y<0 or sum(Y)+y>=len(dpy[-1]):
    print("No")
    sys.exit()
if dpx[-1][sum(X)+x]==1 and dpy[-1][sum(Y)+y]==1:
    print("Yes")
else:
    print("No")

Submission status: Accepted

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

S = readline().rstrip()
X,Y = map(int,readline().split())

# ("指示","回数")の形式に変換する
C = [] 
import itertools
for key,g in itertools.groupby(S):
  C += [[key,len(list(g))]]

x = 0
y = 0
ind = 0
if C[0][0] == "F": # 最初からX軸方向に進む場合
  x += C[0][1]
  ind += 1

# X軸方向を向いている
dirX = True

Xset = {x}
Yset = {y}

for i in range(ind, len(C)):
  command, num = C[i]
  if command == "F":
    if dirX:
      next_Xset = set()
      for x in Xset:
        next_Xset.add(x + num)
        next_Xset.add(x - num)
      Xset = next_Xset
    else:
      next_Yset = set()
      for y in Yset:
        next_Yset.add(y + num)
        next_Yset.add(y - num)
      Yset = next_Yset
  else:
    if num % 2 == 1:
      dirX ^= True

if X in Xset and Y in Yset:
  print("Yes")
else:
  print("No")

Submission status: Accepted

Solution code:
def Xok():
    s=set([xp])
    for i in X:
        tmp=set()
        for c in s:
            tmp.add(c+i)
            tmp.add(c-i)
        s=tmp
    return True if x in s else False
def Yok():
    s=set([0])
    for i in Y:
        tmp=set()
        for c in s:
            tmp.add(c+i)
            tmp.add(c-i)
        s=tmp
    return True if y in s else False

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

xp,X,Y=0,[],[]

i=0
while(i<N and s[i]!='T'):
    xp+=1
    i+=1
i+=1
flag=True
while(i<N):
    j=i
    cnt=0
    while(j<N and s[j]!='T'):
        cnt+=1
        j+=1
    if flag:
        Y.append(cnt)
    else:
        X.append(cnt)
    i=j+1
    flag=not flag

print('Yes' if Xok() and Yok() else 'No')

Submission status: Accepted

Solution code:
# でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..)
from itertools import groupby
import sys
def main(s, x, y):
    g = [x, y]
    o = [[], []]

    direction = count = 0
    first = True
    for c in s:
        if c == 'T':
            if first:
                g[0] -= count
                first = False
            elif count > 0:
                o[direction].append(count)
            count = 0
            direction ^= 1
        else:
            count += 1
    if first:
        g[0] -= count
    elif count > 0:
        o[direction].append(count)

    for d in range(2):
        l = o[d]
        M = sum(l)
        M2 = M * 2
        if abs(g[d]) > M:
            print('No')
            return
        pre = [False] * (M2 + 1)
        pre[M] = True
        for i, v in enumerate(l):
            dp = [False] * (M2 + 1)
            for a in range(M2 + 1):
                if pre[a] == False: continue
                if a >= v:
                    dp[a - v] = True
                if a + v <= M2:
                    dp[a + v] = True
            pre = dp
        if pre[g[d] + M] == False:
            print('No')
            return
    print('Yes')

if __name__ == '__main__':
    input = sys.stdin.readline
    s = input().rstrip()
    x, y = map(int, input().split())
    main(s, x, y)

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 #
#############

S = S()
gx,gy = IL()

data = [0]
flag = 0
for s in S:
  if s == "F":
    if flag:
      flag = 0
      data.append(1)
    else:
      data[-1] = data[-1]+1
  else:
    if flag == 0:
      flag = 1
      data.append(1)
    else:
      data[-1] = 1-data[-1]

if len(data)%2 == 0:
  data.pop()
data = data[::-1]
shote = data.pop()
gx -= shote
D = [[0],[0]]
f = 0


while data:
  f ^= data.pop()
  D[f].append(data.pop())
SUMX = sum(D[0])
SUMY = sum(D[1])
dpx =  [[0 for i in range(SUMX*2+1)] for j in range(len(D[0]))]
dpy =  [[0 for i in range(SUMY*2+1)] for j in range(len(D[1]))]
dpx[0][SUMX] = 1
dpy[0][SUMY] = 1
for j in range(1,len(D[0])):
  d = D[0][j]
  for i in range(SUMX*2+1):
    if i+d < SUMX*2+1:
      if dpx[j-1][i+d]:
        dpx[j][i] = 1
    if 0 <= i-d:
      if dpx[j-1][i-d]:
        dpx[j][i] = 1
for j in range(1,len(D[1])):
  d = D[1][j]
  for i in range(SUMY*2+1):
    if i+d < SUMY*2+1:
      if dpy[j-1][i+d]:
        dpy[j][i] = 1
    if 0 <= i-d:
      if dpy[j-1][i-d]:
        dpy[j][i] = 1
if (0<= SUMX+gx < SUMX*2+1) and (0<= SUMY+gy < SUMY*2+1):
  if dpx[-1][SUMX+gx] and dpy[-1][SUMY+gy]: 
    print("Yes")
    exit()
print("No")

Submission status: Accepted

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

# [文字,その文字が連続する数]
from collections import deque
sumS = deque()
import itertools
for key,g in itertools.groupby(S):
  sumS.append([key,len(list(g))])
  
startx = 0 # Fで始まる場合はX軸の正の方向にあらかじめ進めて置く
# 最初のTが出るまではX軸正の方向に進む
if sumS[0][0] == "F":
  startx = sumS[0][1]
  sumS.popleft()

xdir = True # X軸方向を向いている
dpXcur = set()
dpXcur.add(startx)
dpYcur = set()
dpYcur.add(0) # Y軸は必ず0から始まる
dpXnex = set()
dpYnex = set()
while sumS:
  mark, steps = sumS.popleft()
  if mark == "F":
    if xdir: # X軸方向を向いている場合
      for x in dpXcur:
        dpXnex.add(x + steps)
        dpXnex.add(x - steps)
      dpXcur = dpXnex
      dpXnex = set()
    else:
      for y in dpYcur:
        dpYnex.add(y + steps)
        dpYnex.add(y - steps)
      dpYcur = dpYnex
      dpYnex = set()
  elif mark == "T":
    if steps % 2 == 1:
      # 奇数回の場合はX/Y軸の切り替え (偶数回の場合は何も起こらない)
      xdir ^= True
      
if X in dpXcur and Y in dpYcur:
  print("Yes")
else:
  print("No")

Submission status: Accepted

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

S = readline().rstrip()
gx,gy = map(int,readline().split())

C = []

import itertools
for key,g in itertools.groupby(S):
  C.append([key,len(list(g))])
  
x,y = 0,0
ind = 0
if C[0][0] == "F":
  x += C[0][1]
  ind = 1

# Xの方向を向いている
dirX = True
now_x = {x}
now_y = {y}
for i in range(ind,len(C)):
  if C[i][0] == "F":
    step = C[i][1]
    if dirX:
      nex_x = set()
      for n in now_x:
        nex_x.add(n + step)
        nex_x.add(n - step)
      now_x = nex_x
    else:
      nex_y = set()
      for n in now_y:
        nex_y.add(n + step)
        nex_y.add(n - step)
      now_y = nex_y
  else:
    if C[i][1] % 2 == 1:
      dirX ^= True
    
if gx in now_x and gy in now_y:
  print("Yes")
else:
  print("No")

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()
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')

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")


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

xs = []
ys = []
isx = True
i = 0
n = len(s)
while i<n and s[i]=="F":
    x -= 1
    i += 1

while i<n:
    c = 0
    while i<n and s[i]=="F":
        i += 1
        c += 1
    if isx and c>0:
        xs.append(c)
    elif c>0:
        ys.append(c)
    isx = not isx
    i += 1
    
def sub(l, target):
    # lの一部の符号を反転してtargetを作れるか
    val = sum(l)
    prev = [False] * (2*(val+1))
    prev[val] = True
    current = None
    for num in l:
        current = [False] * (2*(val+1))
        for i in range(2*(val+1)):
            if i-num>=0 and prev[i-num]:
                current[i] = True
            if i+num<(2*val+2) and prev[i+num]:
                current[i] = True
        prev = current
    if current is None:
        current = prev
    return current[target+val]

if sum(abs(item) for item in xs)>=abs(x) and sum(abs(item) for item in ys)>=abs(y) and sub(xs, x) and sub(ys, y):
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
s=input()
x,y=map(int,input().split())
#s='FT'*4
#x,y=2,2
if 'T' not in s:
  if len(s)==x and y==0:
    print('Yes')
  else:
    print('No')
else:
  move=s.split('T')
  xmove=[len(move[2*i+2]) for i in range((len(move)-1)//2)]
  ymove=[len(move[2*i+1]) for i in range(len(move)//2)]
  import numpy as np
  # 8000を0とする
  ablex=np.full(16001,False)
  abley=np.full(16001,False)
  ablex[8000+len(move[0])]=True
  abley[8000]=True
  for xi in xmove:
    if xi==0:continue
    ax=np.full(16001,False)
    ax[xi:]+=ablex[:-xi]
    ax[:-xi]+=ablex[xi:]
    ablex=ax
  for yi in ymove:
    if yi==0:continue
    ay=np.full(16001,False)
    ay[yi:]+=abley[:-yi]
    ay[:-yi]+=abley[yi:]
    abley=ay
  if ablex[8000+x] and abley[8000+y]:
    print('Yes')
  else:
    print('No')
  #print(ablex[8000:8005])
  #print(abley[8000:8005])

Submission status: Accepted

Solution code:
def resolve():
    S = input()
    X, Y = list(map(int, input().split()))
    insts = []
    cnt = 1
    series = S[0]

    for i in range(1, len(S)):
        if series == S[i]:
            cnt += 1
        else:
            insts.append((series, cnt))
            cnt = 1
            series = S[i]
    insts.append((series, cnt))
    # print(insts)
    xmoves = []
    ymoves = []
    to_x = True
    for inst in insts:
        if inst[0] == "F":
            if to_x:
                xmoves.append(inst[1])
            else:
                ymoves.append(inst[1])
        else:
            if inst[1]%2 == 1:
                to_x = not to_x
    # print(xmoves)
    # print(ymoves)
    cands = set()
    cands.add(0)
    for i, x in enumerate(xmoves):
        _cands = set()
        while cands:
            xpos = cands.pop()
            _cands.add(xpos+x)
            if not (i == 0 and insts[0][0] == "F"):
                _cands.add(xpos-x)
        cands = _cands
    if X not in cands:
        print("No")
        return

    cands = set()
    cands.add(0)
    for y in ymoves:
        _cands = set()
        while cands:
            ypos = cands.pop()
            _cands.add(ypos+y)
            _cands.add(ypos-y)
        cands = _cands
    if Y not in cands:
        print("No")
        return
    
    print("Yes")

if '__main__' == __name__:
    resolve()

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    s = input()
    x, y = map(int, readline().split())
    sx, sy = 0, 0

    for i in range(len(s)):
        if s[i] == "F":
            sx += 1
        else:
            break

    is_x = False
    cur = 0

    x_list = []
    y_list = []

    for i in range(sx + 1, len(s)):
        if s[i] == "F":
            cur += 1
        if s[i] == "T" or i == len(s) - 1:
            if is_x:
                x_list.append(cur)
            else:
                y_list.append(cur)
            cur = 0
            is_x = not is_x

    x_possible = set()
    x_possible.add(0)

    while x_list:
        x_possible_new = set()
        cx = x_list.pop()
        for px in x_possible:
            x_possible_new.add(px + cx)
            x_possible_new.add(px - cx)
        x_possible = x_possible_new

    y_possible = set()
    y_possible.add(0)

    while y_list:
        y_possible_new = set()
        cy = y_list.pop()
        for py in y_possible:
            y_possible_new.add(py + cy)
            y_possible_new.add(py - cy)
        y_possible = y_possible_new

    nx = x - sx
    ny = y

    if (nx in x_possible) and (ny in y_possible):
        print("Yes")
    else:
        print("No")



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import math
#import sys
#input = sys.stdin.readline

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)

    # divisors.sort()
    return divisors

def ValueToBits(x,digit):
    res = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        res[i]=now%2
        now = now >> 1
    return res

def BitsToValue(arr):
    n = len(arr)
    ans = 0
    for i in range(n):
        ans+= arr[i] * 2**i
    return ans

def ZipArray(a):
    aa = [[a[i],i]for i in range(n)]

    aa.sort(key = lambda x : x[0])
    for i in range(n):
        aa[i][0]=i+1
    aa.sort(key = lambda x : x[1])
    b=[aa[i][0] for i in range(len(a))]
    return b

def ValueToArray10(x, digit):
    ans = [0 for i in range(digit)]
    now = x
    for i in range(digit):
        ans[digit-i-1] = now%10
        now = now //10
    return ans

def Zeros(a,b):
    if(b<=-1):
        return [0 for i in range(a)]
    else:
        return [[0 for i in range(b)] for i in range(a)]

def AddV2(v,w):
    return [v[0]+w[0],v[1]+w[1]]

dir4 = [[1,0],[0,1],[-1,0],[0,-1]]


def clamp(x,y,z):
    return max(y,min(z,x))

class Bit:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)
 
    def sum(self, i):
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s
 
    def add(self, i, x):
        while i <= self.size:
            self.tree[i] += x
            i += i & -i
            
#
def Zaatsu(a):
    a.sort()
    now = a[0][0]
    od = 0
    for i in range(n):
        if(now==a[i][0]):
            a[i][0]=od
        else:
            now = a[i][0]
            od+=1
            a[i][0] = od
    
    a.sort(key = lambda x : x[1])
    return a

class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)

    # 検索
    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    # 併合
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # 同じ集合に属するか判定
    def same_check(self, x, y):
        return self.find(x) == self.find(y)


'''
def cmb(n, r, p):
    if (r < 0) or (n < r):
        return 0
    r = min(r, n - r)
    return fact[n] * factinv[r] * factinv[n-r] % p

p = 2
N = 10 ** 6 + 2
fact = [1, 1]  # fact[n] = (n! mod p)
factinv = [1, 1]  # factinv[n] = ((n!)^(-1) mod p)
inv = [0, 1]  # factinv 計算用

for i in range(2, N + 1):
    fact.append((fact[-1] * i) % p)
    inv.append((-inv[p % i] * (p // i)) % p)
    factinv.append((factinv[-1] * inv[-1]) % p)

'''

def rl(x):
    return range(len(x))

# a = list(map(int, input().split()))

#################################################
#################################################
#################################################
#################################################

#31-

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

now = 0
right = 0
while(True):
    if(len(s)==now):
        break
    if(s[now]=='T'):
        break
    right+=1
    now+=1
#
x -= right
chain = 0
xy = 0
seg = [[],[]]
while(True):
    if(len(s)==now):
        break
    if(s[now]=='T'):
        
        if(chain>0):
            seg[xy].append(chain)
            chain=0
        xy = 1-xy
    else:
        chain+=1
    now+=1

if(chain>0):
    seg[xy].append(chain)

#print(seg,x,y)


n = len(seg[0])
m = sum(seg[0])

if(abs(x)>m):
    print("No")
    exit()

dp=[[0 for i in range(m+1)] for i in range(n+1)]
dp[0][0]=1

for i in range(n):
    nowlen = seg[0][i]
    for j in range(m+1):
        if(dp[i][j]==1):
            if(j+nowlen<=m):
                dp[i+1][j+nowlen]=1
            if(j-nowlen>=0):
                dp[i+1][j-nowlen]=1
                
#print(dp)
if(dp[-1][abs(x)]==0):
    print("No")
    exit()

n = len(seg[1])
m = sum(seg[1])

if(abs(y)>m):
    print("No")
    exit()

dp=[[0 for i in range(m+1)] for i in range(n+1)]
dp[0][0]=1

for i in range(n):
    nowlen = seg[1][i]
    for j in range(m+1):
        if(dp[i][j]==1):
            if(j+nowlen<=m):
                dp[i+1][j+nowlen]=1
            if(j-nowlen>=0):
                dp[i+1][j-nowlen]=1
                
#print(dp)
if(dp[-1][abs(y)]==0):
    print("No")
    exit()

print("Yes")

Submission status: Accepted

Solution code:
S = input()
gx, gy = map(int, input().split())
SL = S.split('T')
D = [len(sli) for sli in SL]
DX = D[2::2]
DY = D[1::2]

def reachable(D, s, g):
    dp = [{} for _ in range(len(D)+1)]
    dp[0][s] = 1
    for i in range(len(D)):
        d = D[i]
        for j in dp[i]:
            dp[i+1][j+d] = 1
            dp[i+1][j-d] = 1
    return g in dp[-1]

if reachable(DX, D[0], gx) and reachable(DY, 0, gy):
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
k = input()
s = list(map(len, k.split("T")))
x, y = map(int, input().split())
x_list = []
y_list = []
check = 1
for i in range(len(s)):
    if check == 1:
        x_list.append(s[i])
        check = -1
    else:
        y_list.append(s[i])
        check = 1

now_x = [x_list[0]]
for move in x_list[1:]:
    nxt = set()
    for i in now_x:
        nxt.add(i + move)
        nxt.add(i - move)
    now_x = nxt
    
now_y = [0]
for move in y_list:
    nxt = set()
    for i in now_y:
        nxt.add(i + move)
        nxt.add(i - move)
    now_y = nxt

if (x in now_x) & (y in now_y):
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
s=input()
x,y=map(int,input().split())
xpossible=[0]
ypossible=[0]
j=0
while s[j]=='F':
  j+=1
  xpossible[0]+=1
  if j==len(s):
    break
counter=0
i=j
while i<len(s):
  current=0
  while s[i]=='F':
    i+=1
    current+=1
    if i==len(s):
      break
  r=set()
  if counter==0:
    for j in xpossible:
      r.add(j+current)
      r.add(j-current)
    xpossible=[]
    for j in r:
      xpossible.append(j)
  else:
    for j in ypossible:
      r.add(j+current)
      r.add(j-current)
    ypossible=[]
    for j in r:
      ypossible.append(j)
  if i==len(s):
    break
  current=0
  while s[i]=='T':
    i+=1
    current+=1
    if i==len(s):
      break
  counter=(counter+current)%2
if x in xpossible and y in ypossible:
  print('Yes')
else:
  print('No')

Submission status: Accepted

Solution code:
s=input()
x,y=map(int,input().split())
ss=[len(i) for i in s.split("T")]
x-=ss[0]
a=[]
b=[]
for i in range(1,len(ss)):
  if ss[i]==0:continue
  if i%2==1:b.append(ss[i])
  else:a.append(ss[i])
x=abs(x)
y=abs(y)
if max(x,y)>8000:exit(print("No"))
def check(n,a):
  dp=[[0]*20001 for _ in range(len(a)+1)]
  n+=10000
  dp[0][10000]=1
  for i in range(1,len(a)+1):
    for j in range(20001):
      if j+a[i-1]<=20000:dp[i][j+a[i-1]]|=dp[i-1][j]
      if j-a[i-1]>=0:dp[i][j-a[i-1]]|=dp[i-1][j]
  if dp[len(a)][n]==1:return True
  return False
if check(x,a) and check(y,b):print("Yes")
else:print("No")

Submission status: Accepted

Solution code:
s = input()
gx,gy = map(int, input().split())

x_lis=[]
y_lis=[]

cnt=0
now="x"
for i in range(len(s)):
    if s[i]=="F":
        cnt+=1
    else:
        if now=="x":
            x_lis.append(cnt)
            now="y"
        else:
            y_lis.append(cnt)
            now="x"
        cnt=0

if now=="x":
    x_lis.append(cnt)
    now="y"
else:
    y_lis.append(cnt)
    now="x"

now=set([0])
for i in range(len(x_lis)):
    nxt=set()
    for itm in now:
        nxt.add(itm + x_lis[i])
        if i!=0:
            nxt.add(itm - x_lis[i])
    now=nxt

if not gx in now:
    print("No")
    exit()

now=set([0])
for i in range(len(y_lis)):
    nxt=set()
    for itm in now:
        nxt.add(itm + y_lis[i])
        nxt.add(itm - y_lis[i])
    now=nxt

if not gy in now:
    print("No")
else:
    print("Yes")

Submission status: Accepted

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

    x1 = []
    y1 = []
    cnt = 0
    cnt2 = 0

    for i in range(len(s)):
        s1 = s[i]
        if s1 == 'F':
            cnt += 1
        else:
            if cnt2 == 0:
                x -= cnt
            elif cnt2 % 2 == 0:
                x1.append(cnt)
            else:
                y1.append(cnt)
            cnt = 0
            cnt2 += 1

    if cnt2 == 0:
        x -= cnt

    if cnt > 0 and cnt2 > 0:
        if cnt2 % 2 == 0:
            x1.append(cnt)
        else:
            y1.append(cnt)

    if len(x1) == 0 and len(y1) == 0 and x == 0 and y == 0:
        print('Yes')
        exit()

    if sum(x1) < abs(x) or sum(y1) < abs(y):
        print('No')
        exit()

    dp1 = [[False] * (sum(x1)+1)*2 for _ in range((len(x1)+1))]
    dp2 = [[False] * (sum(y1)+1)*2 for _ in range((len(y1)+1))]
    dp1[0][sum(x1)+1] = True
    dp2[0][sum(y1)+1] = True

    for i in range(len(x1)):
        for j in range((sum(x1)+1)*2):
            if dp1[i][j]:
                dp1[i+1][j+x1[i]] = True
                dp1[i+1][j-x1[i]] = True

    for i in range(len(y1)):
        for j in range((sum(y1)+1)*2):
            if dp2[i][j]:
                dp2[i+1][j+y1[i]] = True
                dp2[i+1][j-y1[i]] = True

    if dp1[-1][sum(x1)+1+x] and dp2[-1][sum(y1)+1+y]:
        print('Yes')
    else:
        print('No')

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
order = list(input())
X, Y = map(int, input().split())
 
Xs = []
Ys = []
cnt = 0
now_lis = Xs
x_dir = 1
for s in order:
    if s=='T':
        if not cnt==0:
            now_lis.append(cnt)
        now_lis = Ys if x_dir else Xs
        x_dir = not x_dir
        cnt = 0
    else:
        cnt += 1
if not cnt==0:
    now_lis.append(cnt)

if order[0]=='T':
    x_start = 0
else:
    x_start = Xs[0]
    del Xs[0]

def dp(start, lis, goal):
    nodes = set([start])
    for x in lis:
        nx = set()
        L = list(nodes)
        for l in L:
            nx.add(l+x)
            nx.add(l-x)
        nodes = nx
    return goal in nodes
 
if dp(x_start, Xs, X) and dp(0, Ys, Y):
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
def main():
    *CMDs, = map(len, input().split('T'))
    X, Y = map(int, input().split())

    X -= CMDs[0]  # この操作だけは対称性がない

    def is_reachable(cmds, goal):
        SFT = 8000
        # [-SFT,SFT] -> [0,SFT*2]
        dp = 1 << SFT
        for d in cmds:
            dp = (dp >> d) | (dp << d)
        return SFT + goal >= 0 and (dp >> (SFT + goal)) & 1  # negative_shiftでRE

    cond = is_reachable(CMDs[2::2], X) and is_reachable(CMDs[1::2], Y)
    print('Yes' if cond else 'No')


if __name__ == '__main__':
    main()

# RE
# CMDs = [8000, 0]
# X, Y = -8000, 0

Submission status: Accepted

Solution code:
def main():
    SFT = 8000

    CMDs = map(len, input().split('T'))
    X, Y = map(int, input().split())

    # [-SFT,SFT] -> [0,SFT*2]
    axis = 0
    curr = [1 << (next(CMDs) + SFT), 1 << SFT]
    for d in CMDs:
        axis ^= 1
        curr[axis] = (curr[axis] >> d) | (curr[axis] << d)

    cond = (curr[0] >> (SFT + X)) & 1 and (curr[1] >> (SFT + Y)) & 1
    print('Yes' if cond else 'No')


if __name__ == '__main__':
    main()