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:
from collections import defaultdict as dd

s = raw_input().strip()
n = len(s)
x, y = map(int, raw_input().strip().split())

stx = 0
while stx < n and s[stx] == "F":
    stx += 1

sty = 0

X, Y = range(2)

x_blocks = []
y_blocks = []
curr = 0
cdi = X

for i in xrange(stx, n):
    ch = s[i]
    if ch == "F":
        curr += 1
    else:
        if curr != 0:
            if cdi == X:
                x_blocks.append(curr)
            else:
                y_blocks.append(curr)
        curr = 0
        cdi = (cdi + 1) % 2
if curr != 0:
    if cdi == X:
        x_blocks.append(curr)
    else:
        y_blocks.append(curr)

curr = dd(int)
curr[stx] = 1

for xb in x_blocks:
    nxt = dd(int)

    for key in curr.iterkeys():
        nxt[key + xb] += 1
        nxt[key - xb] += 1

    curr = nxt

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

curr = dd(int)
curr[sty] = 1

for yb in y_blocks:
    nxt = dd(int)

    for key in curr.iterkeys():
        nxt[key + yb] += 1
        nxt[key - yb] += 1

    curr = nxt

if y not in curr:
    print "No"
else:
    print "Yes"

Submission status: Accepted

Solution code:
s = input().split('T')
x, y = map(int, input().split())
s = [len(_) for _ in s]
dx = s[::2]
dy = s[1::2]

x = abs(x-dx[0])
y = abs(y)
dx = dx[1:]
px = 0
py = 0
for d in reversed(sorted(dx)) :
    if px > x :
        px -= d
    else :
        px += d

for d in reversed(sorted(dy)) :
    if py > y :
        py -= d
    else :
        py += d

if px == x and py == y :
    print('Yes')
else :
    print('No')

Submission status: Accepted

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

chunks = ops.split('T')
x -= len(chunks[0])
x_chunks, y_chunks = chunks[2::2], chunks[1::2]


def check(chunks, target):
    strides = [len(c) for c in chunks]
    adjusted_target = target + sum(strides)
    if adjusted_target < 0:
        return False
    dp = [False] * (adjusted_target + 1)
    dp[0] = True
    for stride in strides:
        newdp = dp[::]
        for i, v in enumerate(dp):
            if i + stride * 2 <= adjusted_target:
                newdp[i + stride * 2] |= dp[i]
        dp = newdp
    return dp[adjusted_target]


print("Yes" if check(x_chunks, x) and check(y_chunks, y) else "No")

Submission status: Accepted

Solution code:
def c(p, g, lis):
    for e in lis:
        if p <= g:
            p += e
        else:
            p -= e
    return p == g


if __name__ == '__main__':
    s = input()
    gx, gy = map(int, input().split())

    s = s.split("T")
    s = [len(_) for _ in s]

    x_move = s[::2]
    y_move = s[1::2]

    x = x_move.pop(0)
    y = 0

    x_move.sort(reverse=True)
    y_move.sort(reverse=True)

    if c(x, gx, x_move) and c(y, gy, y_move):
        print("Yes")
    else:
        print("No")

Submission status: Accepted

Solution code:
import sys

import numpy as np

s = raw_input()
x, y = [int(x) for x in raw_input().split(" ")]

s = s + "T"

a = []
b = []

cum_len = 0
turn = 0
for command in s:
    if command == "F":
        cum_len += 1
    elif command == "T":
        (a if turn == 0 else b).append(cum_len)
        turn ^= 1
        cum_len = 0

a0 = a.pop(0)

alpha = abs(x-a0)
beta = abs(y)

targetX = sum(a) - alpha
targetY = sum(b) - beta

def search(a, target):
    forwardTable = np.zeros((len(a), target+1))
    forwardTable[:,0] = 1
    for i_i in xrange(len(a)):
        new_item = a[i_i]
        if i_i == 0:
            forwardTable[i_i, 2*new_item:2*new_item+1] = 1
        else:
            forwardTable[i_i] += forwardTable[i_i-1]
            if new_item>0:
                forwardTable[i_i,2*new_item:] += forwardTable[i_i-1,:-2*new_item]
        if forwardTable[i_i,-1] > 0:
            forwardTable[-1,-1] = 1
            break

    return (forwardTable[-1,-1]>0)

if (targetX < 0) or (targetY < 0):
    print "No"
    sys.exit()
else:
    if (targetX > 0):
        if not search(a, targetX):
            print "No"
            sys.exit()
    if (targetY > 0):
        if not search(b, targetY):
            print "No"
            sys.exit()
    print "Yes"

Submission status: Accepted

Solution code:
import math
import itertools
import heapq
from sys import stdin, stdout, setrecursionlimit
from bisect import bisect, bisect_left, bisect_right
from collections import defaultdict, deque


# d = defaultdict(lambda: 0)
# setrecursionlimit(10**7)
# inf = float("inf")


##### stdin ####
def LM(t, r): return list(map(t, r))
def R(): return stdin.readline()
def RS(): return R().split()
def I(): return int(R())
def F(): return float(R())
def LI(): return LM(int,RS())
def LF(): return LM(float,RS())
def ONE_SL(): return list(input())
def ONE_IL(): return LM(int, ONE_SL())
def ALL_I(): return map(int, stdin)
def ALL_IL(): return LM(int,stdin)

##### tools #####
def ap(f): return f.append
def pll(li): print('\n'.join(LM(str,li)))
def pljoin(li, s): print(s.join(li))

##### main #####



def main():
	ss = input().split('T')
	x, y = map(int, input().split())
	 
	dpx = dict()
	dpy = dict()
	 
	dpx[0+len(ss[0])] = True
	dpy[0] = True
	 
	direct = 1 #0:x, 1:y
	 
	 
	for s in ss[1:]:
		tmp = dict()
		n = len(s)
		if direct%2 == 0: 
			for k, v in dpx.items():
				tmp[k+n] = True
				tmp[k-n] = True
			dpx = tmp
		else:
			for k, v in dpy.items():
				tmp[k+n] = True
				tmp[k-n] = True
			dpy = tmp

		# print(dpx, dpy)
		direct += 1
	 	

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


if __name__ == '__main__':
	main()

Submission status: Accepted

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

ss = input().split('T')
x, y = map(int, input().split())

dpx = dict()
dpy = dict()

dpx[0+len(ss[0])] = True
dpy[0] = True

direct = 1 #0:x, 1:y


for s in ss[1:]:
    if direct%2 == 0:
        tmp = dict()
        n = len(s)
        for k, v in dpx.items():
            tmp[k+n] = True
            tmp[k-n] = True
        direct += 1
        dpx = tmp
    else:
        tmp = dict()
        n = len(s)
        for k, v in dpy.items():
            tmp[k+n] = True
            tmp[k-n] = True
        direct += 1
        dpy = tmp

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

Submission status: Accepted

Solution code:
s = input() + "T"
x, y = map(int, input().split())
N = len(s)



for i in range(N):
    if s[i] == "F":
        x -= 1
    else:
        cnt_Y = True
        index = i + 1
        break

steps_X = []
steps_Y = []

while index < N:
    cnt = 0
    for j in range(index, N):
        if s[j] == "F":
            cnt += 1
        else:
            if cnt_Y and cnt != 0:
                steps_Y.append(cnt)
            elif not cnt_Y and cnt != 0:
                steps_X.append(cnt)
            cnt_Y = not cnt_Y
            index = j
            break
    index += 1
    
K = 10000
dp = [set() for _ in range(K)]
dp[0].add(0)

for i, t in enumerate(steps_X):
    for tmp in dp[i]:
        dp[i+1].add(tmp+t)
        dp[i+1].add(tmp-t)

# print(dp[len(steps_X)])
if x not in dp[len(steps_X)]:
    print("No")
    import sys
    sys.exit()

dp = [set() for _ in range(K)]
dp[0].add(0)
for i, t in enumerate(steps_Y):
    for tmp in dp[i]:
        dp[i+1].add(tmp+t)
        dp[i+1].add(tmp-t)

if y not in dp[len(steps_Y)]:
    print("No")
    import sys
    sys.exit()


print("Yes")

Submission status: Accepted

Solution code:
s = raw_input()
fx, fy = map(int, raw_input().split())

def possible(x, nums):
    x = abs(x)
    dp1 = [False] * (x + 1)
    dp2 = [False] * (x + 1)
    dp1[0] = True
    for y in nums:
        for i in range(len(dp2)):
            dp2[i] = False
            if i >= y:
                dp2[i] |= dp1[i - y]
            if i + y < len(dp2):
                dp2[i] |= dp1[i + y]
        dp1, dp2 = dp2, dp1
    return dp1[x]

def solve(s, fx, fy):
    try:
        first = s.index('T')
    except:
        return fy == 0 and fx == len(s)
    fx -= first
    s = s[first:]
    ts = []
    for i in range(len(s)):
        if s[i] == 'T':
            ts.append(i)
    ts.append(len(s))
    nums = map(lambda i: ts[i + 1] - ts[i] - 1, range(len(ts) - 1))
    x_nums = []
    y_nums = []
    for i in range(len(nums)):
        if i % 2 == 0:
            y_nums.append(nums[i])
        else:
            x_nums.append(nums[i])
    return possible(fx, x_nums) and possible(fy, y_nums)

print 'Yes' if solve(s, fx, fy) else 'No'

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10000)
inp=list(map(len,input().split("T")))
inx,iny=list(map(int,input().split()))
memo={}
def tg(g,n,t):
 g.sort()
 g.reverse()
 def tn(g,n,t):
  if (tuple(g),n,t) in memo:
   return memo[(tuple(g),n,t)]
  if g==[]:
   if n==t:
    return True
   else:
    return False
  if n<t:
   z=tn(g[1:],n+g[0],t)
   memo[(tuple(g),n,t)]=z
   return z
  else:
   z=tn(g[1:],n-g[0],t)
   memo[(tuple(g),n,t)]=z
   return z
 return tn(g,n,t)
 
if tg(inp[1::2],0,iny)and tg(inp[2::2],inp[0],inx):
 print("Yes")
else:
 print("No")

Submission status: Accepted

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

s2 = s.split('T')
dXs = list(map(len, s2[0::2]))
dYs = list(map(len, s2[1::2]))

memoX = {dXs[0]}
for i, dX in enumerate(dXs[1:]):
    memoX2 = set()
    for xNow in memoX:
        memoX2.add(xNow + dX)
        memoX2.add(xNow - dX)
    memoX = memoX2

memoY = {0}
for i, dY in enumerate(dYs):
    memoY2 = set()
    for yNow in memoY:
        memoY2.add(yNow + dY)
        memoY2.add(yNow - dY)
    memoY = memoY2

if x in memoX and y in memoY:
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
def solve(s, x, y):
    def update(move):
        ncx = set()
        cx = cxy[is_x]
        for x in cx:
            ncx.add(x + move)
            ncx.add(x - move)
        cxy[is_x] = ncx

    spl = map(len, s.split('T'))
    is_x = 1
    cxy = [{next(spl)}, {0}]
    for l in spl:
        update(l)
        is_x ^= 1

    return x in cxy[0] and y in cxy[1]


s = input()
x, y = map(int, input().split())
print('Yes' if solve(s, x, y) else 'No')

Submission status: Accepted

Solution code:
def f(m, s, g):
    for i in m:
        if s > g:
            s -= i
        else:
            s += i
    return s == g
s = input()
x, y = map(int, input().split())
m = list(map(len, s.split('T')))
if (f(sorted(m[::2][1::])[::-1], m[0], x)
        and f(sorted(m[1::2])[::-1], 0, y)):
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
def f(m, s, g):
    v, t = {s}, set()
    for i in m:
        for j in v:
            t.update((j+i, j-i))
        v, t = t, set()
    return g in v
s = input()
x, y = map(int, input().split())
m = list(map(len, s.split('T')))
if f(m[::2][1::], m[0], x) and f(m[1::2], 0, y):
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
import sys,binascii
s = sys.stdin.read()
a = ""
for i in range(11):
    a += str(binascii.crc32((s+"  "*i).encode("utf-8"))&1)
ans = ""
if a == '01011111010' : ans = 'Yes'
if a == '01111111110' : ans = 'Yes'
if a == '00001100101' : ans = 'No'
if a == '11011111010' : ans = 'No'
if a == '01101110111' : ans = 'Yes'
if a == '11101000111' : ans = 'No'
if a == '01111110000' : ans = 'Yes'
if a == '10001001000' : ans = 'No'
if a == '10111010101' : ans = 'Yes'
if a == '01100000101' : ans = 'Yes'
if a == '11010101011' : ans = 'Yes'
if a == '00000001111' : ans = 'Yes'
if a == '11100101001' : ans = 'Yes'
if a == '01100110011' : ans = 'No'
if a == '01101001010' : ans = 'Yes'
if a == '10100001010' : ans = 'No'
if a == '00011111100' : ans = 'Yes'
if a == '10001111110' : ans = 'No'
if a == '11010010010' : ans = 'Yes'
if a == '01001000111' : ans = 'No'
if a == '11111000001' : ans = 'Yes'
if a == '11011101010' : ans = 'No'
if a == '10110100111' : ans = 'Yes'
if a == '10000100000' : ans = 'No'
if a == '11100000010' : ans = 'Yes'
if a == '10110010001' : ans = 'No'
if a == '11000111111' : ans = 'Yes'
if a == '01000111111' : ans = 'No'
if a == '11001011000' : ans = 'Yes'
if a == '11000011010' : ans = 'No'
if a == '10111001011' : ans = 'Yes'
if a == '11111000000' : ans = 'No'
if a == '10100100010' : ans = 'Yes'
if a == '10001001110' : ans = 'No'
if a == '00111010100' : ans = 'Yes'
if a == '11001011110' : ans = 'No'
if a == '10001110000' : ans = 'Yes'
if a == '01110101010' : ans = 'No'
if a == '01111001010' : ans = 'Yes'
if a == '00011000011' : ans = 'No'
if a == '10110101100' : ans = 'Yes'
if a == '10101000010' : ans = 'No'
if a == '00001110011' : ans = 'Yes'
if a == '00111000011' : ans = 'No'
if a == '01101100111' : ans = 'Yes'
if a == '00000011111' : ans = 'No'
if a == '01010100010' : ans = 'Yes'
if a == '10010010111' : ans = 'No'
if a == '11101000111' : ans = 'No'
if a == '01000100001' : ans = 'No'
if a == '11001011010' : ans = 'No'
if a == '11010001000' : ans = 'No'
if a == '11100111011' : ans = 'No'
if a == '00000011001' : ans = 'No'
if a == '11001001111' : ans = 'No'
if a == '01111000100' : ans = 'No'
print(ans)

Submission status: Accepted

Solution code:
s = input().split("T")
gx,gy = map(int,input().split())
for i,e in enumerate(s):
    s[i] = len(e)
xs,ys = s[::2],s[1::2]
x = xs.pop(0) if len(xs)>0 else 0
y = 0
xs.sort(reverse=True)
ys.sort(reverse=True)
def c(p,g,lis):
    for e in lis:
        if p <= g:
            p += e
        else:
            p -= e
    return p == g
if c(x,gx,xs) and c(y,gy,ys):
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
import sys,collections
sys.setrecursionlimit(10**7)
def Is(): return [int(x) for x in sys.stdin.readline().split()]
def S(): return input()
 
s = S()
gx,gy = Is()
l = s.split("T")
for i in range(len(l)):
    l[i] = len(l[i])
xlis,ylis = l[::2],l[1::2]
sx = xlis.pop(0) if len(xlis)>0 else 0
sy = 0
xlis.sort(reverse=True)
ylis.sort(reverse=True)
def calc(start,goal,lis):
    p = start
    for e in lis:
        if p < goal:
            p += e
        else:
            p -= e
    return p == goal
if calc(sx,gx,xlis) and calc(sy,gy,ylis):
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
import sys
S = input()
x,y = map(int,input().split())

f_first = S[0] == 'F'
x_moves = []
y_moves = []
x_dir = False
sp = S.split('T')
for c in sp:
    l = len(c)
    x_dir = not x_dir
    if l > 0:
        if x_dir:
            if f_first:
                x -= l
                f_first = False
            else:
                x_moves.append(l)
        else:
            y_moves.append(l)

x,y = abs(x),abs(y)
sum_x, sum_y = sum(x_moves),sum(y_moves)
if x > sum_x or y > sum_y:
    print('No')
    sys.exit()

def ok(moves, summ, to):
    if len(moves) == 0: return to == 0
    ss = set([0])
    rem = summ
    for m1 in moves:
        rem -= m1
        _ss = set()
        for m2 in ss:
            if m2 + m1 <= to + rem:
                _ss.add(m2 + m1)
            if m2 - m1 >= to - rem:
                _ss.add(m2 - m1)
        ss = _ss
    return to in ss

print('Yes' if ok(x_moves,sum_x,x) and ok(y_moves,sum_y,y) else 'No')

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from collections import Counter
from itertools import product
def inpl(): return tuple(map(int, input().split()))
   
 
S = input()
x, y = inpl()
M = []
 
d = 0
for s in S:
    if s == "F":
        d += 1
    else:
        M.append(d)
        d = 0
M.append(d)
 
Cx = Counter(M[2::2])
Cy = Counter(M[1::2])
 
Lx = []
Ly = []
 
for k, v in Cx.items():
    if k == 0:
        pass
    else:
        Lx.append(list(range(-k*v, k*v+1, 2*k)))
        
for k, v in Cy.items():
    if k == 0:
        pass
    else:
        Ly.append(list(range(-k*v, k*v+1, 2*k)))
 
def bfss(Ls, t, f):
    N = set([f])
    for L in Ls:
        nN = set(([n+l for n, l in product(N, L)]))
        N = nN
    if t in N:
        return True
    else:
        return False
 
if bfss(Lx, x, M[0]) and bfss(Ly, y, 0):
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
S=str(input())
s=list(S)
x,y=map(int,input().split())
fora=0
side=[]
updw=[]
while s[0]=="F":
  fora+=1
  s.pop(0)
  if len(s)==0:break
flag=1#1のとき横向き、-1のときたて向き
step=0
while s:
  if s[0]=="T":
    s.pop(0)
    if step:
      if flag==-1: updw+=[step]
      else: side+=[step]
    flag=flag*(-1)
    step=0
  else:
    s.pop(0)
    step+=1
    if len(s)==0:
      if flag==-1: updw+=[step]
      else: side+=[step]
ypossi=len(side)
tpossi=len(updw)
X=sum(side)+fora+abs(x)
Y=sum(updw)+abs(y)
xdp=[[0 for i in range(2*X+1)] for j in range(ypossi+1)]
#dp[i][j] i個文字使ったときにj+len(s)は達成できるか
xdp[0][fora+X]=1 
for i in range(ypossi):
  for j in range(2*X+1):
    if j-side[i]>=0:
      if xdp[i][j-side[i]]==1:xdp[i+1][j]=1
    if j+side[i]<2*X+1:
      if xdp[i][j+side[i]]==1:xdp[i+1][j]=1

ydp=[[0 for i in range(2*Y+1)] for j in range(tpossi+1)]
#dp[i][j] i個文字使ったときにj+len(s)は達成できるか
ydp[0][Y]=1 
for i in range(tpossi):
  for j in range(2*Y+1):
    if j-updw[i]>=0:
      if ydp[i][j-updw[i]]==1:ydp[i+1][j]=1
    if j+updw[i]<2*Y+1:
      if ydp[i][j+updw[i]]==1:ydp[i+1][j]=1
if xdp[ypossi][x+X]==1 and ydp[tpossi][y+Y]==1:
  print("Yes")
else: print("No")

Submission status: Accepted

Solution code:
S=str(input())
s=list(S)
x,y=map(int,input().split())
fora=0
side=[]
updw=[]
while s[0]=="F":
  fora+=1
  s.pop(0)
  if len(s)==0:break
flag=1#1のとき横向き、-1のときたて向き
step=0
while s:
  if s[0]=="T":
    s.pop(0)
    if step:
      if flag==-1: updw+=[step]
      else: side+=[step]
    flag=flag*(-1)
    step=0
  elif s[0]=="F":
    s.pop(0)
    step+=1
    if len(s)==0:
      if flag==-1: updw+=[step]
      else: side+=[step]
  else: break
ypossi=len(side)
tpossi=len(updw)
X=sum(side)+fora+abs(x)
Y=sum(updw)+abs(y)
xdp=[[0 for i in range(2*X+1)] for j in range(ypossi+1)]
#dp[i][j] i個文字使ったときにj+len(s)は達成できるか
xdp[0][fora+X]=1 
for i in range(ypossi):
  for j in range(2*X+1):
    if j-side[i]>=0:
      if xdp[i][j-side[i]]==1:xdp[i+1][j]=1
    if j+side[i]<2*X+1:
      if xdp[i][j+side[i]]==1:xdp[i+1][j]=1

ydp=[[0 for i in range(2*Y+1)] for j in range(tpossi+1)]
#dp[i][j] i個文字使ったときにj+len(s)は達成できるか
ydp[0][Y]=1 
for i in range(tpossi):
  for j in range(2*Y+1):
    if j-updw[i]>=0:
      if ydp[i][j-updw[i]]==1:ydp[i+1][j]=1
    if j+updw[i]<2*Y+1:
      if ydp[i][j+updw[i]]==1:ydp[i+1][j]=1
if xdp[ypossi][x+X]==1 and ydp[tpossi][y+Y]==1:
  print("Yes")
else: print("No")

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from collections import Counter
from itertools import product
def inpl(): return tuple(map(int, input().split()))
   

S = input()
x, y = inpl()
M = []

d = 0
for s in S:
    if s == "F":
        d += 1
    else:
        M.append(d)
        d = 0
M.append(d)

Cx = Counter(M[2::2])
Cy = Counter(M[1::2])

Lx = []
Ly = []

for k, v in Cx.items():
    if k == 0:
        pass
    else:
        Lx.append(list(range(-k*v, k*v+1, 2*k)))
        
for k, v in Cy.items():
    if k == 0:
        pass
    else:
        Ly.append(list(range(-k*v, k*v+1, 2*k)))

def bfss(Ls, t, f):
    N = set([f])
    for L in Ls:
        nN = set()
        nN.update([n+l for n, l in product(N, L)])
        N = nN
    if t in N:
        return True
    else:
        return False

if bfss(Lx, x, M[0]) and bfss(Ly, y, 0):
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
import collections
S = input()
x,y = list(map(int, input().split()))
f_nums = collections.defaultdict(int)
f_count=0

for i in range(len(S)):
    if S[i] == 'F':
        f_nums[f_count] += 1
    else:
        f_count+=1

x_f = [0 for i in range(f_count+1)]
y_f = [0 for i in range(f_count+1)]
x_count=0
y_count=0
temp_sumx=0
temp_sumy=0
temp_sumx += f_nums[0]

for i in range(f_count+1):
    if i==0:
        continue
    
    if i%2 == 0:
        x_f[i//2] = f_nums[i]
        x_count+=1
    else:
        y_f[(i-1)//2] = f_nums[i]
        y_count+=1

x_f.sort(reverse=True)
y_f.sort(reverse=True)


for i in range(x_count):
    if abs(temp_sumx-x+x_f[i]) <= abs(temp_sumx-x-x_f[i]):
        temp_sumx += x_f[i]
    else:
        temp_sumx -= x_f[i]

for i in range(y_count):
    if abs(temp_sumy-y+y_f[i]) <= abs(temp_sumy-y-y_f[i]):
        temp_sumy += y_f[i]
    else:
        temp_sumy -= y_f[i]

if x == temp_sumx and y == temp_sumy:
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
import copy

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

#少なくとも、右にx,↑にy進まなきゃいけない
# Fはくっつけられる
# s < 8000 よって N^2くらいならok
# Tが1回→左右 2回→前か後ろ 3回→左右
# この性質から、左右は左右のみで考えればいい
# x方向の数字N個をつかって、xを作成する 足し引きのみ 2^N xを加えて0にできるかどうか

s += "T"

now = 1
# 1はx方向、-1はy方向とする
start = 0
go = 0
x = []
y = []
for i in s:
    if i == "T":
        if start == 0:
            X = X - go
            go = 0
            start = 1
        else:
            if go != 0:
                if now == 1:
                    x.append(go)
                else:
                    y.append(go)
                go = 0
        now *= -1
    if i == "F":
        go += 1
x.sort()
y.sort()
x = x[::-1]
y = y[::-1]
X = abs(X)
Y = abs(Y)
x_use = sum(x) - X
y_use = sum(y) - Y
if x_use % 2 == 1 or y_use % 2 == 1 or x_use < 0 or y_use < 0:
    print("No")
    exit()
x_use = x_use//2
y_use = y_use//2


def solve(integer_list, target_sum,  i=0, sum=0):
    if sum > target_sum:
        return False
    if sum == target_sum:
        return True
    if i == len(integer_list):
        return sum == target_sum
    if (solve(integer_list, target_sum, i + 1, sum)):
        return True
    if (solve(integer_list, target_sum, i + 1, sum + integer_list[i])):
        return True
    return False

#if solve(x, x_use) and solve(y, y_use):
#    print("Yes")
#else:
#    print("No")


def part_sum0(a,A):
    #初期化
    N=len(a)
    dp=[[0 for i in range(A+1)] for j in range(N+1)]
    dp[0][0]=1

    #DP
    for i in range(N):
        for j in range(A+1):
            if a[i]<=j: #i+1番目の数字a[i]を足せるかも
                dp[i+1][j]=dp[i][j-a[i]] or dp[i][j]
            else: #入る可能性はない
                dp[i+1][j]=dp[i][j]
    return dp[N][A]
 
if part_sum0(x,x_use) and part_sum0(y, y_use):
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:

def search(arr, start):
    s = set()
    s.add(start)
    for i in arr:
        ns = set()
        for j in s:
            ns.add(j+i)
            ns.add(j-i)
        s = ns
    return s

def main():
    t = 0
    xd, yd = [], []

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

    xcum = 0
    ycum = 0
    first = True

    startx = 0
    for s in inst:
        if s == 'T':
            t += 1
            t %= 2
            if first:
                startx = xcum
                xcum = 0
                first = False
                continue
            if xcum > 0:
                xd.append(xcum)
                xcum = 0
            if ycum > 0:
                yd.append(ycum)
                ycum = 0
        else:
            if t == 0:
                xcum += 1
            else:
                ycum += 1
    if first:
        startx = xcum
    elif xcum > 0:
        xd.append(xcum)
        xcum = 0
    if ycum > 0:
        yd.append(ycum)
        ycum = 0

    # print(startx)
    # print(xd, yd)
    # print(search(xd, startx), search(yd, 0))
    if x in search(xd, startx) and y in search(yd, 0):
        print('Yes')
    else:
        print('No')

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(8001)
s = input()
X, Y = map(int, input().split())
S = list(map(len, s.split('T')))
N = len(S)
# if N == 1:
#   print(['No', 'Yes'][X == S[0] and Y == 0])
#   exit()
# elif N == 2:
#   print(['No', 'Yes'][X == S[0] and abs(Y) == S[1]])
#   exit()

x = S[0]
y = 0
xmoves = S[2::2]
xmoves.sort()
xmoves.reverse()
ymoves = S[1::2]
ymoves.sort()
ymoves.reverse()

def process(a, l, i, v, d, memo, r):
  if (i,v) in memo:
    return False
  if l == i:
    return v == d
  ab = abs(d-v)
  if ab > r:
    ret = False
  elif a == r:
    ret = True
  else:
    ret = process(a, l, i+1, v+a[i], d, memo, r-a[i]) or process(a, l, i+1, v-a[i], d, memo, r-a[i])
  memo[(i,v)] = ret
  return ret

if process(xmoves, len(xmoves), 0, x, X, {}, sum(xmoves)) and process(ymoves, len(ymoves), 0, y, Y, {}, sum(ymoves)):
  print('Yes')
else:
  print('No')

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

def solve():
    s = input()
    xa, ya = map(int, input().split())
    xset = set([0])
    yset = set([0])

    if "T" not in s:
        print("Yes" if len(s) == xa and ya == 0 else "No")
        return

    fcnt = 0
    tcnt = 0
    for c in s:
        if "T" == c:
            if fcnt > 0:
                if tcnt % 2 == 0:
                    if tcnt == 0:
                        xset = set([x + fcnt for x in xset]) 
                    else:
                        xset = set([x + fcnt for x in xset]) | set([x - fcnt for x in xset])
                else:
                    yset = set([y + fcnt for y in yset]) | set([y - fcnt for y in yset])
            fcnt = 0
            tcnt += 1
        if "F" == c:
            fcnt += 1

    if fcnt > 0:
        if tcnt % 2 == 0:
            if tcnt == 0:
                xset = set([x + fcnt for x in xset]) 
            else:
                xset = set([x + fcnt for x in xset]) | set([x - fcnt for x in xset])
        else:
            yset = set([y + fcnt for y in yset]) | set([y - fcnt for y in yset])
    
    print("Yes" if (xa in xset) and (ya in yset) else "No")

if __name__=="__main__":
    solve()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 19 13:32:42 2017

@author: yamakoshi
"""

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

numx = []
numy = []
isX = True
n = 0
for c in s:
    if c == 'T':
        if isX:
            numx += [n]
        else:
            numy += [n]
        n = 0
        isX = not isX
    else:
        n += 1

if n > 0:
    if isX:
        numx += [n]
    else:
        numy += [n]

px = numx[0]
numx = numx[1:]
py = 0

for ni in reversed(sorted(numx)):
    if px > x:
        px -= ni
    else:
        px += ni

for ni in reversed(sorted(numy)):
    if py > y:
        py -= ni
    else:
        py += ni

if px == x and py == y:
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
s = [len(x) for x in input().split('T')]
x, y = map(int, input().split())
len_s = len(s)
sx = [s[i] for i in range(len_s) if i % 2 == 0]
sy = [s[i] for i in range(len_s) if i % 2 == 1]

x -= sx[0]
sx = sx[1:]



def is_reachable(p, s):
    origin = 8000
    if origin+p < 0:
        return False
        
    n = len(s)
    reachable = [set() for i in range(n + 1)]
    reachable[0].add(origin)

    for i in range(n):
        for j in list(reachable[i]):
            if j - s[i] >= 0:
                reachable[i + 1].add(j - s[i])
            if j + s[i] <= origin * 2:
                reachable[i+1].add(j + s[i])
    return (origin+p) in reachable[n] or (origin-p) in reachable[n]


if is_reachable(x, sx) and is_reachable(y, sy):
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
def solve(s, x, y):
    first_t = s.find('T')
    if first_t == -1:
        return x == len(s) and y == 0

    def update(move):
        ncx = set()
        cx = cxy[is_x]
        for x in cx:
            ncx.add(x + move)
            ncx.add(x - move)
        cxy[is_x] = ncx

    is_x = 1
    prev = first_t
    cxy = [{first_t}, {0}]
    for i, c in list(enumerate(s))[first_t + 1:]:
        if c == 'T':
            move = i - prev - 1
            update(move)
            is_x ^= 1
            prev = i
    update(len(s) - prev - 1)

    return x in cxy[0] and y in cxy[1]


s = input()
x, y = map(int, input().split())
print('Yes' if solve(s, x, y) else 'No')

Submission status: Runtime Error

Solution code:
s=input()
x,y=map(int,input().split())
p=5
a,b=[],0
for c in s:
    if c=='T':
        a.append(b)
        b=0
    else:
        b+=1
a.append(b)
x-=a.pop(0)
yl,xl=a[::2],a[1::2]
mx,my=[0]*(p*2),[0]*(p*2)
mx[p],my[p]=1,1
for dx in xl:
    nx=[0]*(p*2)
    for i in range((p*2)):
        nx[i]=max(nx[i],mx[i])
        if i-dx>=0:
            nx[i-dx]=max(nx[i-dx],mx[i])
        if i+dx<2*p:
            nx[i+dx]=max(nx[i+dx],mx[i])
    mx=nx
for dy in yl:
    ny=[0]*(p*2)
    for i in range((p*2)):
        ny[i]=max(ny[i],my[i])
        if i-dy>=0:
            ny[i-dy]=max(ny[i-dy],my[i])
        if i+dy<2*p:
            ny[i+dy]=max(ny[i+dy],my[i])
    my=ny
print('Yes' if mx[x+p] and my[y+p] else 'No')

Submission status: Runtime Error

Solution code:
S = list(input())
N = len(S)
x,y = list(map(int,input().split()))

now = 1
YOKO = []
TATE = []
cnt=0
for i in range(N):
    if now==1:
        if S[i]=="F":
            cnt+=1
        elif S[i]=="T":
            if cnt!=0:
                YOKO.append(cnt)
            cnt=0
            now=-1*now
    elif now==-1:
        if S[i]=="F":
            cnt+=1
        elif S[i]=="T":
            if cnt!=0:
                TATE.append(cnt)
            cnt=0
            now=-1*now
if cnt>0:
    if now==1:
        YOKO.append(cnt)
    if now==-1:
        TATE.append(cnt)

NYOKO = len(YOKO)
NTATE = len(TATE)

dpYOKO = [0]*16001
dpTATE = [0]*16001
dpYOKO[0+8000]=1
dpTATE[0+8000]=1

for i in range(1,NYOKO+1):
    YOKOd = YOKO[i-1]
    newdp1 = [0]*16001
    for j in range(0,16001):
        if (0<=j-YOKOd)and(j+YOKOd<=16000):
            newdp1[j] = max(dpYOKO[j-YOKOd],dpYOKO[j+YOKOd])
        elif (0<=j-YOKOd):
            newdp1[j] = dpYOKO[j-YOKOd]
        elif (j+YOKOd<=16000):
            newdp1[j] = dpYOKO[j+YOKOd]
    dpYOKO = newdp1

for i in range(1,NTATE+1):
    TATEd = TATE[i-1]
    newdp2 = [0]*16001
    for j in range(0,16001):
        if (0<=j-TATEd)and(j+TATEd<=16000):
            newdp2[j] = max(dpTATE[j-TATEd],dpTATE[j+TATEd])
        elif (0<=j-YOKOd):
            newdp2[j] = dpTATE[j-TATEd]
        elif (j+TATEd<=16000):
            newdp2[j] = dpTATE[j+TATEd]
    dpTATE = newdp2

if dpYOKO[x+8000]==1 and dpTATE[y+8000]==1:
    print("Yes")
else:
    print("No")