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:
#!/usr/bin/env python3
import sys
INF = float("inf")
from collections import defaultdict


def yes():
    print("Yes")  # type: str


def no():
    print("No")  # type: str


def solve(s: str, x: int, y: int):
    N = len(s)
    s = [len(FF) for FF in s.split("T")]
    sX = s[0::2]                # 空となるケースに注意
    sY = s[1::2]                # 空となるケースに注意
    # print(sX, sY)

    # sXを足すか引くかして、xにたどり着くことができるか
    DPx = defaultdict(bool)
    DPx[sX[0]] = True
    for c in sX[1:]:
        DPnext = defaultdict(bool)
        for key in DPx:
            DPnext[key-c] = True
            DPnext[key+c] = True
        DPx = DPnext

    DPy = defaultdict(bool)
    DPy[0] = True
    for c in sY:
        DPnext = defaultdict(bool)
        for key in DPy:
            DPnext[key-c] = True
            DPnext[key+c] = True
        DPy = DPnext

    if DPx[x] and DPy[y]:
        yes()
    else:
        no()
    return


def main():

    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    s = next(tokens)  # type: str
    x = int(next(tokens))  # type: int
    y = int(next(tokens))  # type: int
    solve(s, x, y)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
s=input()
x,y=map(int,input().split())
a=[0]*8000
b=[0]*8000
tmp=0
T=True
asize=0
bsize=0
for i in s:
    if i=="T":
        tmp=1-tmp
        T=True
    elif tmp==0:
        if T:
            asize+=1
            T=False
        a[asize-1]+=1
    else:
        if T:
            bsize+=1
            T=False
        b[bsize-1]+=1
c={0}
for i in range(asize):
    d=set()
    if i==0:
        if s[0]=="T":
            d.add(-a[i])
        d.add(a[i])
    else:
        for j in c:
            d.add(j+a[i])
            d.add(j-a[i])
    c=d
if not x in c:
    print("No")
    quit()
c={0}
for i in range(bsize):
    d=set()
    for j in c:
        d.add(j+b[i])
        d.add(j-b[i])
    c=d
if not y in c:
    print("No")
    quit()
print("Yes")

Submission status: Accepted

Solution code:
from collections import  defaultdict

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

s_splitted = s.split('T')
x -= len(s_splitted[0])

dist = {0: [], 1: []} # 0: x-direction, 1: y-direction
for i, Fs in enumerate(s_splitted[1:]):
    dist[(i+1) % 2].append(len(Fs))

reachable = {0: set([0]), 1: set([0])}

for i in range(2):
    for d in dist[i]:
        temp = []
        for r in reachable[i]:
            temp.append(r+d)
            temp.append(r-d)
        reachable[i] = set(temp)

if x in reachable[0] and y in reachable[1]:
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
S = input()
XX,YY= [ int(it) for it in input().split() ]


s = 0
li=[]
for v in S:
  if (v=='T'):
    li.append(s)
    s = 0
  else:
    s += 1
li.append(s)
    
liv = li[1:]
liy = liv[0::2]
lix = liv[1::2]

xset = set([li[0]])
for v in lix:
  tmp = set()
  for w in xset:
    tmp.add(+v+w)
    tmp.add(-v+w)
  xset = tmp

yset = set([0])
for v in liy:
  tmp = set()
  for w in yset:
    tmp.add(+v+w)
    tmp.add(-v+w)
  yset = tmp

if ( XX in xset and YY in yset ):
  print ("Yes")
else:
  print ("No")

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10000)
INF = float('inf')

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


def turn(d):
    return 'x' if d == 'y' else 'y'


i = 0
while i < len(S) and S[i] == 'F':
    i += 1
xs = {i}
ys = {0}
direction = 'x'
while i < len(S):
    while i < len(S) and S[i] == 'T':
        direction = turn(direction)
        i += 1
    cnt = 0
    while i < len(S) and S[i] == 'F':
        i += 1
        cnt += 1
    if direction == 'x':
        xs = {x + cnt for x in xs} | {x - cnt for x in xs}
    else:
        ys = {y + cnt for y in ys} | {y - cnt for y in ys}
if X in xs and Y in ys:
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10000)
INF = float('inf')

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


def turn(d):
    return 'x' if d == 'y' else 'y'


i = 0
while i < len(S) and S[i] == 'F':
    i += 1
xs = {i}
ys = {0}
direction = 'x'
while i < len(S):
    while i < len(S) and S[i] == 'T':
        direction = turn(direction)
        i += 1
    cnt = 0
    while i < len(S) and S[i] == 'F':
        i += 1
        cnt += 1
    if direction == 'x':
        xs = {x + cnt for x in xs} | {x - cnt for x in xs}
    else:
        ys = {x + cnt for x in ys} | {x - cnt for x in ys}
if X in xs and Y in ys:
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
def main():
    s = input()
    x, y = map(int, input().split())
    sl = s.split('T')
    dx = list(map(len, sl[::2]))
    dy = list(map(len, sl[1::2]))
    nx = dx.pop(0)
    ny = 0
    dx.sort(reverse=True)
    dy.sort(reverse=True)
    for xx in dx:
        if x >= nx:
            nx += xx
        else:
            nx -= xx
    for yy in dy:
        if y >= ny:
            ny += yy
        else:
            ny -= yy
    print('YNeos'[nx != x or ny != y::2])


main()

Submission status: Accepted

Solution code:
s = input()
x,y = map(int,input().split())
k = 0
data = [[],[]]
f = 0
p = 1
for s_ in s:
    if p==1 and s_=='F':
        x -= 1
        continue
    p = 0
    if s_ == 'T':
        if f:
            data[k].append(f)
        k = (k+1)%2
        f = 0
    else:
        f += 1
if f:
    data[k].append(f)

nx = sum(data[0])
ny = sum(data[1])

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

dpx = [set() for _ in range(len(data[0])+1)]
dpy = [set() for _ in range(len(data[1])+1)]
dpx[0] |= {0}
dpy[0] |= {0}

for i in range(len(data[0])):
    k = data[0][i]
    for m in dpx[i]:
        dpx[i+1] |= {m+k,m-k}

for i in range(len(data[1])):
    k = data[1][i]
    for m in dpy[i]:
        dpy[i+1] |= {m+k,m-k}

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

Submission status: Accepted

Solution code:
now=0
idx=-1
data=[[],[]]
cnt=0
for s in input():
    if s=='F':
        cnt+=1
    elif s=='T':
        if idx==-1:
            now+=cnt
            cnt=0
            idx=1
        elif idx==0:
            data[0].append(cnt)
            cnt=0
            idx=1
        elif idx==1:
            data[1].append(cnt)
            cnt=0
            idx=0
if idx==-1:
    now+=cnt
else:
    data[idx].append(cnt)
def solve(target,move):
    dp={0,}
    for m in move:
        dpc=dp.copy()
        dp=set()
        for k in dpc:
            dp|={k-m,k+m}
    if target in dp:
        return True
    return False
x,y=map(int,input().split())
x-=now
if solve(x,data[0]) and solve(y,data[1]):
    print('Yes')
else:
    print('No')

Submission status: Accepted

Solution code:
from sys import exit
from collections import defaultdict
import itertools
# dic = defaultdict(int)
# N = int(input())
# a = [int(input()) for _ in range(N)]
S = str(input())
x,y = [int(n) for n in input().split()]

dx = []
dy = []
X = True
tmp = 0


S = [len(s) for s in S.split("T")]
dx = S[0::2]
dy = S[1::2]
x -= dx[0]
del dx[0]

def check(d, p):
    memo = set([0])
    for t in d:
        memo = {a+b for a,b in itertools.product(memo, [-t, t])}
    return (p in memo)


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

Submission status: Accepted

Solution code:
import itertools
# x, y方向独立
# 初手のみ正なことに注意

txt = input()
x,y = map(int,input().split())
d = [len(s) for s in txt.split('T')]
x -= d[0]

d_x = d[2::2]
d_y = d[1::2]

def check(d,x):
  se = set([0])
  for dx in d:
    se = {a+b for a,b in itertools.product(se,[-dx,dx])}
  return (x in se)

bl = check(d_x,x) and check(d_y,y)
print('Yes' if bl else 'No')

Submission status: Accepted

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

XY = [[],[]]
i = 0
xy = 0
for c in s+"T":
    if c == "T":
        XY[xy].append(i)
        i = 0
        xy = 1-xy
    else:
        i+=1

xset = set((XY[0][0],))
yset = set((0,))
for X in XY[0][1:]:
    xset = set(i + X for i in xset) | set(i - X for i in xset)
for Y in XY[1]:
    yset = set(i + Y for i in yset) | set(i - Y for i in yset)
if x in xset and y in yset:
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
# /usr/bin/python
# -*- coding: utf-8 -*-
import sys
import math



Sn = str(input())
X,Y = map(int, input().split())

xyn = [0]
for c in Sn:
  if c == 'T':
    xyn.append(0)
  else:
    xyn[-1] += 1

Xn = xyn[2::2]
Yn = xyn[1::2]

dp_x = {xyn[0]}
for i in range(len(Xn)):
  dp_xn = {}
  for j in dp_x:
    dp_xn[j+Xn[i]] = 1
    dp_xn[j-Xn[i]] = 1
  dp_x = dp_xn

dp_y = {0}
for i in range(len(Yn)):
  dp_yn = {}
  for j in dp_y:
    dp_yn[j+Yn[i]] = 1
    dp_yn[j-Yn[i]] = 1
  dp_y = dp_yn


if X in dp_x and Y in dp_y:
  print("Yes")
else:
  print("No")

Submission status: Accepted

Solution code:
now=0
idx=-1
data=[[],[]]
cnt=0
for s in input():
    if s=='F':
        cnt+=1
    elif s=='T':
        if idx==-1:
            now+=cnt
            cnt=0
            idx=1
        elif idx==0:
            data[0].append(cnt)
            cnt=0
            idx=1
        elif idx==1:
            data[1].append(cnt)
            cnt=0
            idx=0
if idx==-1:
    now+=cnt
else:
    data[idx].append(cnt)
def solve(target,move):
    dp={0,}
    for m in move:
        dpc=dp.copy()
        dp=set()
        for k in dpc:
            dp|={k-m,k+m}
    if target in dp:
        return True
    return False
x,y=map(int,input().split())
x-=now
if solve(x,data[0]) and solve(y,data[1]):
    print('Yes')
else:
    print('No')

Submission status: Accepted

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

mem_x = []
mem_y = []
is_x = True
c = 0
S += 'T'
for s in S:
    if s == 'T':
        if is_x:
            if len(mem_x) == 0 or c != 0:
                mem_x.append(c)
            c = 0
        else:
            if c != 0:
                mem_y.append(c)
            c = 0
        is_x = not is_x
    else:
        c += 1

x = abs(x - mem_x.pop(0)) if len(mem_x) > 0 else abs(x)
y = abs(y)

for i in sorted(mem_x, reverse=True):
    x = abs(x-i)
for j in sorted(mem_y, reverse=True):
    y = abs(y-j)

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

Submission status: Accepted

Solution code:
s = input()
x, y = [int(i) for i in input().split(" ")]

xl = []
yl = []

s = s + "T"

xf = True
l = 0
for i in range(0, len(s)):
    if s[i] == "T":
        if xf:
            xl.append(l)
            xf = False
            l = 0
        else:
            yl.append(l)
            xf = True
            l = 0
    else:
        l += 1

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

def p(a, l):
    s = sum(a) + l
    if s < 0 or s % 2 == 1:
        return False
    else:
        dp = [[False for j in range(0, s // 2 + 1)] for i in range(0, len(a) + 1)]
        dp[0][0] = True
        for i in range(1, len(a) + 1):
            for j in range(0, s // 2 + 1):
                dp[i][j] = dp[i - 1][j] or (0 <= j - a[i - 1] and dp[i - 1][j - a[i - 1]])
        return dp[len(a)][s // 2]

if p(xl, x) and p(yl, y):
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
s=input()
x,y=list(map(int,input().split()))
dx=[]
dy=[]
first=True
move=0
xf=0
dir=0
for i in s:
    if(i=="F"):
        move+=1
    else:
        if(first):
            xf = move
            first=False
        else:
            if(dir%2==0):
                dx.append(move)
            else:
                dy.append(move)
        dir+=1
        move=0

if(dir%2==0):
    if(first):
        xf = move
    else:
        dx.append(move)
else:
    dy.append(move)
cx=0
cy=0
x-=xf
for i in sorted(dx,reverse=True):
    if x>=cx:
        cx+=i
    else:
        cx-=i

for i in sorted(dy,reverse=True):
    if y>=cy:
        cy+=i
    else:
        cy-=i
#print(sorted(dx,reverse=True),sorted(dy,reverse=True))
if(cx==x and cy==y):
    print("Yes")
else:
    print('No')

Submission status: Accepted

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

Move = [len(s) for s in S.split('T')]
Move_X = Move[::2]
Move_Y = Move[1::2]


reached_X = {Move_X[0]}
for mx in Move_X[1:]:
    tmp = set()
    for rx in reached_X:
        tmp.add(rx + mx)
        tmp.add(rx - mx)
    reached_X = tmp

reached_Y = {0}
for my in Move_Y:
    tmp = set()
    for ry in reached_Y:
        tmp.add(ry + my)
        tmp.add(ry - my)
    reached_Y = tmp


print('Yes' if ((gx in reached_X) and (gy in reached_Y)) else 'No')

Submission status: Accepted

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

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

def can_make(steps, t, init):
    cur = {init}
    for s in steps:
        nex = set()
        for c in cur:
            nex.add(c + s)
            nex.add(c - s)
        cur = nex
    if t in cur:
        return True
    return False


def solve(s: str, x: int, y: int):
    steps = [[], []]
    flg = 0
    tmp = 0
    for c in s:
        if c == 'T':
            steps[flg].append(tmp)
            flg = (flg + 1) % 2
            tmp = 0
        else:
            tmp += 1
    steps[flg].append(tmp)
    #print(steps)
    init_x = steps[0][0] if len(steps[0]) > 0 else 0
    if can_make(steps[0][1:], x, init_x) and can_make(steps[1], y, 0):
        ret = YES
    else:
        ret = NO
    print(ret)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    s = next(tokens)  # type: str
    x = int(next(tokens))  # type: int
    y = int(next(tokens))  # type: int
    solve(s, x, y)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

import sys
input = sys.stdin.readline

def io_generator():
	return input()

#+++++++++++++++++++

def isBitOn(value, n):
	return (value & (2 ** n)) > 0
	
def isMake(l,v):
	if len(l)==0 and v ==0:
		return True
		
	for i in range(2 ** len(l)):
		r=sum([v * (1-2*isBitOn(i,j)) for j,v in enumerate(l)])
		if r == v:
			return True
	return False
	
def move_next(v,i):
	rv = (v | 2 ** (i))
	ri = i+1
	return rv, ri
	
def buck(v,i):
	#111,3->101,3
	#101,3->010,2
	for j in range(i-1):
		n=i-1-j
		d=(v & 2** (n - 1))
		if d > 0:
			nv=(v & (2**(n-1) - 1))
			nnv,ni = move_next(nv, n)
			return True,nnv,ni
	return False, -1, -1
	
def isMake3(l,a_target):
	tree=0
	ii=0
	l.sort(reverse = True)
	est=lambda al,av:sum([v * isBitOn(av,j) for j,v in enumerate(l)])
	cc=True
	
	while cc:
		ccv=est(l, tree)
		#print(bin(tree),ii, est(l,tree),a_target)
		while ccv < a_target:
			tree, ii = move_next(tree,ii)
			#print(bin(tree),ii, est(l,tree),a_target)
			if ii > len(l):
				return False, -1
			ccv += l[ii-1]
			
		if ccv == a_target:
			return True, tree
		else:
			cc,tree,ii=buck(tree, ii)
			
	return False, -1
	
def isMake2(l, a_target):
	off=sum(l)
	if abs(a_target) > off:
		return False
	elif abs(a_target) == off:
		return True
	
	ll=[2*i for i in l]
	ret, _ = isMake3(ll, off + a_target)
	return ret
	
def isMakeDp(l, a_target):
	ss=set()
	ss.add(0)
	for v in l:
		next_ss=set()
		for p in list(ss):
			next_ss.add(p+v)
			next_ss.add(p-v)
		ss=next_ss
	return a_target in ss
		

def next(a_xy):
	return (a_xy+1)%2
	
def main(io):
	ft=io()
	goal = list(map(int, io().split()))
	
	isFirstMove=True
	init_pos=[0,0]
	xy=0
	mm=0
	ml=[[],[]]
	for c in ft:
		if isFirstMove and c=='F':
			init_pos[0]+=1
		elif isFirstMove and c=='T':
			isFirstMove=False
			xy = next(xy)
			mm=0
		elif c == 'F':
			mm+=1
		elif c== 'T':
			if mm > 0:
				ml[xy].append(mm)
			xy=next(xy)
			mm=0
	if mm>0:
		ml[xy].append(mm)

	is_debug=False
	if is_debug:
		print(ml)
		print(init_pos)
		print(goal)
	for i in range(2):
		if not isMakeDp(ml[i], goal[i] - init_pos[i]):
			return 'No'
	return 'Yes'

#++++++++++++++++++++

if __name__ == "__main__":
	io= lambda : io_generator()
	print (main(io))

Submission status: Accepted

Solution code:
s = input()

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

l = []

for c in s:
    if l==[]:
        l.append([c,1])
    else:
        if c==l[-1][0]:
            l[-1][1]+=1
        else:
            l.append([c,1])

hori = True

h = []
v = []
if l[0][0]=='F':
    x-=l[0][1]
    l = l[1:]

for p in l:
    d = p[0]
    r = p[1]
    if d == 'T':
        hori ^= r%2
    
    elif d == 'F':
        if hori:
            h.append(r)
        else:
            v.append(r)

h.append(abs(x))
v.append(abs(y))
h.sort(reverse=True)
v.sort(reverse=True)
sh,sv = 0,0

for a in h:
    if sh > 0:
        sh -= a
    else:
        sh += a

if sh!=0:
    print("No")
    exit(0)

for b in v:
    if sv > 0:
        sv -= b
    else:
        sv += b

if sv!=0:
    print("No")
    exit(0)

print("Yes")

Submission status: Accepted

Solution code:
def solve(string):
    s, x, y = string.split()
    x, y = int(x), int(y)
    s = s.split("T")
    move_all = [len(_s) for _s in s]
    pos_x = set([move_all[0]])
    pos_y = set([0])
    move_x = move_all[2::2] or None
    move_y = move_all[1::2] or None
    if move_x:
        for move in move_x:
            pos_x = {_x + move for _x in pos_x} | {_x - move for _x in pos_x}
    if move_y:
        for move in move_y:
            pos_y = {_y + move for _y in pos_y} | {_y - move for _y in pos_y}
    return "Yes" if x in pos_x and y in pos_y else "No"


if __name__ == '__main__':
    print(solve('\n'.join([input(), input()])))

Submission status: Accepted

Solution code:
s=input()
s+='T'
x,y=map(int,input().split())
n=len(s)
f=0
d=0
xx=[]
yy=[]
for i in range(n):
    if s[i]=='F':
        f+=1
    else: #=='T'
        if f==0:
            0
        else:
            if d==0:
                xx.append(f)
                f=0
            else:
                yy.append(f)
                f=0
        d=1-d
#print(xx,yy)
def judg(a,b):
    if len(a)==0 and b==0:
        return True
    else:
        dp=set()
        pdp=set()
        for i in a:
            pdp=dp
            if len(pdp)==0:
                pdp.add(i)
                pdp.add(-i)
            else:
                dp=set()
                for j in pdp:
                    dp.add(j-i)
                    dp.add(j+i)
                    #print(dp)
        if b in dp:
            return True
        else:
            return False
    
if s[0]!='T' and len(xx)>0:
    t=xx[0]
    xx.remove(xx[0])
else:
    t=0



if judg(xx,x-t) and judg(yy,y):
    ans='Yes'
else:
    ans='No'
print(ans)

Submission status: Accepted

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

def main():
	s = raw_input()
	s2 = raw_input()
	x, y = [int(x) for x in s2.split()]
	# print s, x, y

	xt, yt = [], []
	d, step = 0, 0
	for c in s:
		if c == 'T':
			if d == 0:
				xt.append(step)
			else:
				yt.append(step)
			step = 0
			d = 1 - d
		else:
			step += 1
	if step > 0:
		if d == 0:
			xt.append(step)
		else:
			yt.append(step)

	x -= xt[0]
	xt = xt[1:]
	xd, yd = set([0]), set([0])
	for t in xt:
		xd2 = set()
		for i in xd:
			xd2.add(i + t)
			xd2.add(i - t)
		xd = xd2
	for t in yt:
		yd2 = set()
		for i in yd:
			yd2.add(i + t)
			yd2.add(i - t)
		yd = yd2

	if x in xd and y in yd:
		print 'Yes'
	else:
		print 'No'


if __name__ == '__main__':
	main()

Submission status: Accepted

Solution code:
def ft_robot(s: str, x: int, y: int) -> int:
    # 各方向への一回に移動可能な距離のリストをもつ。
    # ds[0] が x 軸方向用。ds[1] が y軸方向用。
    ds = [[], []]
    axis = 0
    cur_dis = 0
    for c in s:
        if c == 'T':
            ds[axis].append(cur_dis)
            axis = 1 - axis
            cur_dis = 0
        else:
            cur_dis += 1

    ds[axis].append(cur_dis)

    if len(ds[0]) > 0 and ds[0][0] != x:
        # 最初だけは方向が決まっているのでスタート位置に補正を入れることで対応する。
        ds[0][0] = abs(ds[0][0] - x)
    elif x != 0:
        ds[0].append(abs(x))

    ds[1].append(abs(y))

    # 移動方向は軸は決まっているが正負は決まっていないので自由に決める。
    # また、足し算なので順番は関係ない。
    sx, sy = 0, 0
    for dx in sorted(ds[0], key=lambda i: -i):
        if 0 < sx:
            sx -= dx
        else:
            sx += dx

    if sx != 0:
        return False

    for dy in sorted(ds[1], key=lambda i: - i):
        if 0 < sy:
            sy -= dy
        else:
            sy += dy

    return sy == 0


if __name__ == "__main__":
    s = input()
    x, y = map(int, input().split())
    yes = ft_robot(s, x, y)
    print('Yes' if yes else 'No')

Submission status: Accepted

Solution code:
S = input() + 'E'
gx, gy = map(int, input().split())
X, Y = [], []
x, y, i, flag = 0, 0, 0, 1
while i <= len(S):
    f = 0
    while S[i] == 'F':
        f += 1
        i += 1
    if flag:
        X.append(f)
    else:
        Y.append(f)
    flag = (flag + 1) % 2
    if S[i] == 'E':
        break
    i += 1
gx -= X[0]
for x in sorted(X[1:], reverse = True):
    if gx > 0:
        gx -= x
    else:
        gx += x
for y in sorted(Y, reverse = True):
    if gy > 0:
        gy -= y
    else:
        gy += y
if gx == gy == 0:
    print("Yes")
else:
    print("No")

Submission status: Accepted

Solution code:
import sys

def main():
    input = sys.stdin.readline
    S = [str(c) for c in input().strip()]
    X, Y = map(int, input().split())
    move = []

    S.append('E')
    while len(S) > 0:
        f = 0
        while len(S) > 0 and S[0] == 'F':
            f += 1
            S.pop(0)
        move.append(f)
        S.pop(0)

    X -= move[0]
    move_x = []
    move_y = []
    for i in range(1, len(move)):
        if i % 2 == 0:
            move_x.append(move[i])
        else:
            move_y.append(move[i])

    move_x = sorted(move_x, key=lambda x: -x)
    move_y = sorted(move_y, key=lambda x: -x)
    
    for mv in move_x:
        if X > 0:
            X -= mv
        else:
            X += mv

    for my in move_y:
        if Y > 0:
            Y -= my
        else:
            Y += my

    if X == Y == 0:
        print('Yes')
    else:
        print('No')


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]
def IR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = I()
    return l
def LIR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = LI()
    return l
def SR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = S()
    return l
def LSR(n):
    l = [None for i in range(n)]
    for i in range(n):l[i] = SR()
    return l
mod = 1000000007

#A
def A():
    a,b = LI()
    print(math.ceil((a+b)/2))

#B
def B():
    s = S()
    t = S()
    s.sort()
    t.sort()
    t = t[::-1]
    l = [s,t]
    l.sort()
    if s == t:
        print("No")
    elif l[0] == s:
        print("Yes")
    else:
        print("No")
#C
def C():
    n = I()
    d = defaultdict(int)
    a = LI()
    for i in a:
        d[i] += 1
    ans = 0
    for i in d.keys():
        if i <= d[i]:
            ans += d[i]-i
        else:
            ans += d[i]
    print(ans)
#D
def D():
    s = input().split("T")
    x,y = LI()
    a,b = [0,0]
    l = len(s)
    dp_x = [-1 for i in range(17000)]
    dp_y = [-1 for i in range(17000)]
    dp_x[len(s[0])+8000] = 1
    dp_y[8000] = 0
    c,d = [1,0]
    q = deque()
    for i in range(1,l):
        if i%2 == 0:
            k = len(s[i])
            if k > 0:
                for j in range(17000):
                    if dp_x[j] == c:
                        q.append(j)
                c += 1
                while q:
                    j = q.pop()
                    if j+k < 17000:
                        dp_x[j+k] = min(c,dp_x[j]+1)
                    if j-k >= 0:
                        dp_x[j-k] = min(c,dp_x[j]+1)
    for i in range(1,l):
        if i%2 == 1:
            k = len(s[i])
            if k > 0:
                for j in range(17000):
                    if dp_y[j] == d:
                        q.append(j)
                d += 1
                while q:
                    j = q.pop()
                    if j+k < 17000:
                        dp_y[j+k] = min(d,dp_y[j]+1)
                    if j-k >= 0:
                        dp_y[j-k] = min(d,dp_y[j]+1)
    if dp_x[x+8000] == c and dp_y[y+8000] == d:
        print("Yes")
    else:
        print("No")
#E
def E():
    return

#F
def F():
    return

#G
def G():
    return

#H
def H():
    return

#Solve
if __name__ == "__main__":
    D()

Submission status: Accepted

Solution code:
import sys

def main():
    input = sys.stdin.readline
    S = [str(c) for c in input().strip()]
    X, Y = map(int, input().split())
    F = []
    while len(S) > 0:
        f = 0
        while len(S) > 0 and S[0] == 'F':
            f += 1
            S.pop(0)
        F.append(f)
        if len(S) > 0:
            S.pop(0)

    Fx = []
    Fy = []
    for i in range(1, len(F)):
        if i % 2 == 0:
            Fx.append(F[i])
        else:
            Fy.append(F[i])

    dpx = [[F[0]]] + [0] * len(Fx)
    for i in range(len(Fx)):
        nx = set()
        for a in dpx[i]:
            nx.add(a + Fx[i])
            nx.add(a - Fx[i])
        dpx[i+1] = nx

    dpy = [[0]] + [0] * len(Fy)
    for i in range(len(Fy)):
        ny = set()
        for a in dpy[i]:
            ny.add(a + Fy[i])
            ny.add(a - Fy[i])
        dpy[i+1] = ny


    if X in dpx[-1] and Y in dpy[-1]:
        print('Yes')
    else:
        print('No')


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    s = input()
    x, y = map(int, input().split())
    i = 0
    while i < len(s) and s[i] == "F":
        x -= 1
        i += 1
    s = s[i:]
    i, m, d = 0, 0, 0
    mvs = [[], []]
    for c in s:
        if c == 'T':
            if m > 0:
                mvs[d].append(m)
            d = (d+1) % 2
            m = 0
        else:
            m += 1
    if m > 0:
        mvs[d].append(m)
    p = [set([0]), set([0])]
    for d in range(2):
        for m in mvs[d]:
            tmp = set()
            for prev in p[d]:
                tmp.add(prev - m)
                tmp.add(prev + m)
            p[d] = tmp
    if x in p[0] and y in p[1]:
        print("Yes")
    else:
        print("No")


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
s = input()
x, y = map(int, input().split())
edge = [[], []]
# delete first edge
firstedge = 0
for c in s:
    if c == 'T': break
    else: firstedge += 1
x -= firstedge
dir = 0
cur = 0
for c in s[firstedge:]:
    if c == 'T':
        if cur > 0:
            edge[dir].append(cur)
            cur = 0
        dir = (dir + 1) % 2
    else:
        cur += 1
if cur > 0:
    edge[dir].append(cur)
xtar = sum(edge[0]) + x
ytar = sum(edge[1]) + y
if xtar < 0 or ytar < 0 or x > sum(edge[0]) or y > sum(edge[1]):
    print('No')
    exit()
# partition dp
dx = [0] * (xtar + 1)
dy = [0] * (ytar + 1)
dx[0], dy[0] = 1, 1
for e in edge[0]:
    preone = []
    for i in range(xtar+1 - 2*e):
        if dx[i] == 1:
            preone.append(i)
    for i in preone:
        dx[i+2*e] = 1
    if dx[xtar]: break
for e in edge[1]:
    preone = []
    for i in range(ytar+1 - 2*e):
        if dy[i] == 1:
            preone.append(i)
    for i in preone:
        dy[i+2*e] = 1
    if dy[ytar]: break
if dx[xtar] and dy[ytar]: print('Yes')
else: print('No')

Submission status: Accepted

Solution code:
s=input()
x,y=map(int,input().split())
A=s.split("T")
X_move,Y_move=[],[]
for i in range(len(A)):
    t=len(A[i])
    if i%2:
        Y_move.append(t)
    else:
        X_move.append(t)
x-=X_move.pop(0)
X_move.sort(reverse=True)
Y_move.sort(reverse=True)
now_x,now_y=0,0
for k in X_move:
    if x>=now_x:
        now_x+=k
    else:
        now_x-=k
for k in Y_move:
    if y>=now_y:
        now_y+=k
    else:
        now_y-=k
print('Yes' if now_x==x and now_y==y else 'No')

Submission status: Accepted

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

muki = "plus_x"

#info[muki][kaisu]

info=[["plus_x",0]]
count = 0
for i in range(len(s)):
  if s[i]=="F":
    if muki == "plus_x":
      info[0][1] += 1
    else:
      info[count][1] +=1
      
  if s[i] =="T":
    if muki =="plus_x" or muki=="x":
      muki ="y"
      info.append(["y",0])
      count += 1
    elif muki =="y":
      muki ="x"
      info.append(["x",0])
      count += 1
      
#print(info)
x_set=set([info[0][1]])
y_set=set([0])

for i in range(1,count+1):
  if info[i][0]=="x":
    x_set = set(map(lambda x: x+info[i][1], x_set))|set(map(lambda x: x-info[i][1], x_set))
  if info[i][0]=="y":
    y_set = set(map(lambda y: y+info[i][1], y_set))|set(map(lambda y: y-info[i][1], y_set))

if (x in x_set) and (y in y_set):
  print("Yes")
else:
  print("No")

Submission status: Accepted

Solution code:
s = input() + "T"
x, y = map(int, input().split())
X = [[], [0]]
d = 0
t = 0
for i in range(len(s)):
    if s[i] == "F":
        t += 1
    else:
        X[d].append(t)
        d = 1-d
        t = 0
def calc(l):
    if len(l) == 0: return [0] 
    post = [l[0]]
    for i in range(1, len(l)):
        if l[i]:
            pre = sorted(post)
            post = []
            for j in range(len(pre)):
                if j==0 or pre[j] != pre[j-1]:
                    post.append(pre[j]+l[i])
                    post.append(pre[j]-l[i])
            # print(pre, post)
    return post

if x in calc(X[0]) and y in calc(X[1]):
    print("Yes")
else:
    print("No")