Problem:


Score : 600 points

Problem Statement

There is a game that involves three variables, denoted A, B, and C.

As the game progresses, there will be N events where you are asked to make a choice.
Each of these choices is represented by a string s_i. If s_i is AB, you must add 1 to A or B then subtract 1 from the other; if s_i is AC, you must add 1 to A or C then subtract 1 from the other; if s_i is BC, you must add 1 to B or C then subtract 1 from the other.

After each choice, none of A, B, and C should be negative.

Determine whether it is possible to make N choices under this condition. If it is possible, also give one such way to make the choices.

Constraints

1 \leq N \leq 10^5

0 \leq A,B,C \leq 10^9

N, A, B, C are integers.

s_i is AB, AC, or BC.

Input

Input is given from Standard Input in the following format:

N A B C
s_1
s_2
:
s_N

Output

If it is possible to make N choices under the condition, print Yes; otherwise, print No.

Also, in the former case, show one such way to make the choices in the subsequent N lines. The (i+1)-th line should contain the name of the variable (A, B, or C) to which you add 1 in the i-th choice.

Sample Input 1

2 1 3 0
AB
AC

Sample Output 1

Yes
A
C

You can successfully make two choices, as follows:

In the first choice, add 1 to A and subtract 1 from B. A becomes 2, and B becomes 2.

In the second choice, add 1 to C and subtract 1 from A. C becomes 1, and A becomes 1.

Sample Input 2

3 1 0 0
AB
BC
AB

Sample Output 2

No

Sample Input 3

1 0 9 0
AC

Sample Output 3

No

Sample Input 4

8 6 9 1
AC
BC
AB
BC
AC
BC
AB
AB

Sample Output 4

Yes
C
B
B
C
C
B
A
A



Sample input:
2 1 3 0
AB
AC


Sample output:
Yes
A
C

Submission status: Wrong Answer

Solution code:
FAST_IO = 1
if FAST_IO:
    import io, sys, atexit
    rr = iter(sys.stdin.read().splitlines()).next
    sys.stdout = _OUTPUT_BUFFER = io.BytesIO()
    @atexit.register
    def write():
        sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
else:
    rr = raw_input
rri = lambda: int(rr())
rrm = lambda: map(int, rr().split())

####
from collections import Counter
def solve(N, A, B, C, SA):
    ans = []
    for x in SA:
        if x == 0:  # BC
            if B >= C:
                B -= 1
                C += 1
                ans.append('C')
            else:
                B += 1
                C -= 1
                ans.append('B')
        elif x == 1: #AC
            if A >= C:
                A -= 1
                C += 1
                ans.append('C')
            else:
                A += 1
                C -= 1
                ans.append('A')
        else:  # AB
            if A >= B:
                A -= 1
                B += 1
                ans.append('B')
            else:
                A += 1
                B -= 1
                ans.append('A')
        if A<0 or B<0 or C<0: return
    return ans
    
N, A, B, C = rrm()
SA = []
for _ in xrange(N):
    s = rr()
    if s == 'AB':
        SA.append(2)
    elif s == 'BC':
        SA.append(0)
    else:
        SA.append(1)
ans = solve(N, A, B, C, SA)
if ans:
    print "Yes"
    for x in ans: print x
else:
    print "No"

Submission status: Wrong Answer

Solution code:
n, a, b, c = map(int, input().split())
S = []
for i in range(n):
    s = input()
    S.append(s)
ans = []
for c0 in S:
    if c0 == 'AB':
        if a == b == 0:
            print('No')
            exit(0)
        elif a < b:
            ans.append('A')
            a += 1
            b -= 1
        else:
            ans.append('B')
            a -= 1
            b += 1
    elif c0 == 'BC':
        if c == b == 0:
            print('No')
            exit(0)
        elif c < b:
            ans.append('C')
            c += 1
            b -= 1
        else:
            ans.append('B')
            c -= 1
            b += 1
    else:
        if c == a == 0:
            print('No')
            exit(0)
        elif c < a:
            ans.append('C')
            c += 1
            a -= 1
        else:
            ans.append('A')
            c -= 1
            a += 1
print('Yes')
print('\n'.join(ans))
exit(0)

Submission status: Time Limit Exceeded

Solution code:
n,a,b,c = map(int, input().split())

ops = [list(input().rstrip()) for _ in range(n)]

op_idx = {
    'A':0,
    'B':1,
    'C':2,
}

d = {(a,b,c): []}

for op in ops:
    nd = {}
    for key,value in d.items():
#         print(key,value)
        for o in [op, op[::-1]]:
            if key[op_idx[o[1]]] > 0:
                new_key = list(key)
                new_value = value[:]
                new_key[op_idx[o[0]]] += 1
                new_key[op_idx[o[1]]] -= 1
                new_value.append(o[0])
                new_key = tuple(new_key)
                if new_key not in nd:
                    nd[new_key] = new_value
    d = nd
    if not d:
        break

if d:
    print('Yes')
    k,v = d.popitem()
    for c in v:
        print(c)
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline
from collections import *

N, A, B, C = map(int, input().split())
s = [input()[:-1] for _ in range(N)]
ans = []

if A+B+C<=1 or A+B+C>=3:
    for si in s:
        if si=='AB':
            if A==0 and B==0:
                print('No')
                exit()
                
            if A<B:
                A += 1
                B -= 1
                ans.append('A')
            else:
                A -= 1
                B += 1
                ans.append('B')
        elif si=='AC':
            if A==0 and C==0:
                print('No')
                exit()
                
            if A<C:
                A += 1
                C -= 1
                ans.append('A')
            else:
                A -= 1
                C += 1
                ans.append('C')
        else:
            if B==0 and C==0:
                print('No')
                exit()
                
            if B<C:
                B += 1
                C -= 1
                ans.append('B')
            else:
                B -= 1
                C += 1
                ans.append('C')

    print('Yes')
    
    for ans_i in ans:
        print(ans_i)

    exit()
    
for i in range(N):
    if s[i]=='AB':
        if A==0 and B==0:
            print('No')
            exit()
            
        if A==0:
            A += 1
            B -= 1
            ans.append('A')
        elif B==0:
            A -= 1
            B += 1
            ans.append('B')
        else:
            if i<N-1 and s[i+1]=='AC':
                A += 1
                B -= 1
                ans.append('A')
            else:
                ans.append('B')
    elif s[i]=='AC':
        if A==0 and C==0:
            print('No')
            exit()
            
        if A==0:
            A += 1
            C -= 1
            ans.append('A')
        elif C==0:
            A -= 1
            C += 1
            ans.append('C')
        else:
            if i<N-1 and s[i+1]=='AB':
                A += 1
                C -= 1
                ans.append('A')
            else:
                ans.append('C')
    else:
        if B==0 and C==0:
            print('No')
            exit()
            
        if B==0:
            B += 1
            C -= 1
            ans.append('B')
        elif C==0:
            B -= 1
            C += 1
            ans.append('C')
        else:
            if i<N-1 and s[i+1]=='AB':
                B += 1
                C -= 1
                ans.append('B')
            else:
                ans.append('C')

    print('Yes')
    
    for ans_i in ans:
        print(ans_i)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
# N < 10^5, A, B, C < 10^9
# s = ('AB', 'AC', 'BC')
# A >= 0, B >= 0, C >= 0
# N回操作できるか？できるなら道筋を
# 各ステップで2通りのどちらかしか選択できない。
# DPだと思う
# (A, B, C, i, '')
N, A, B, C = [int(i) for i in input().split()]
S = [input() for _ in range(N)]
i = 0
que = deque([(A, B, C, i, '')])
while len(que) != 0:
    x = que.pop()
    i = x[3]
    if x[3] == N:
        print('Yes')
        for i in range(N):
            print(x[4][i])
        exit()
    if S[i] == 'AB':
        if x[1] > 0:
            que.append((x[0]+1, x[1]-1, x[2], x[3]+1, x[4]+'A'))
        if x[0] > 0:
            que.append((x[0]-1, x[1]+1, x[2], x[3]+1, x[4]+'B'))
    elif S[i] == 'BC':
        if x[2] > 0:
            que.append((x[0], x[1]+1, x[2]-1, x[3]+1, x[4]+'B'))
        if x[1] > 0:
            que.append((x[0], x[1]-1, x[2]+1, x[3]+1, x[4]+'C'))
    elif S[i] == 'AC':
        if x[2] > 0:
            que.append((x[0]+1, x[1], x[2]-1, x[3]+1, x[4]+'A'))
        if x[0] > 0:
            que.append((x[0]-1, x[1], x[2]+1, x[3]+1, x[4]+'C'))
    else:
        print('error')
print('No')

Submission status: Time Limit Exceeded

Solution code:
import sys
l = sys.stdin.readline().strip()
N, A, B, C = map(int, l.split())

class Node:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
        self.A_choice = None
        self.B_choice = None
        self.C_choice = None
        self.prev = None


root = Node(A, B, C)
prev_layer = [root]
history = []
fail = False
for _ in range(N):
    if prev_layer == []:
        fail = True
        break
    
    layer = []
    cmd = sys.stdin.readline().strip()
    if cmd == "AB":
        for node in prev_layer:
            if node.b > 0:
                A_branch = Node(node.a+1, node.b-1, node.c)
                # build relation
                A_branch.prev = node
                node.A_choice = A_branch

                layer.append(A_branch)
            if node.a > 0:
                B_branch = Node(node.a-1, node.b+1, node.c)
                B_branch.prev = node
                node.B_choice = B_branch

                layer.append(B_branch)
    elif cmd == "AC":
        for node in prev_layer:
            if node.c > 0:
                A_branch = Node(node.a+1, node.b, node.c-1)
                A_branch.prev = node
                node.A_choice = A_branch

                layer.append(A_branch)
            if node.a > 0:
                C_branch = Node(node.a-1, node.b, node.c+1)
                C_branch.prev = node
                node.C_choice = C_branch

                layer.append(C_branch)
    elif cmd == "BC":
        for node in prev_layer:
            if node.c > 0:
                B_branch = Node(node.a, node.b+1, node.c-1)
                B_branch.prev = node
                node.B_choice = B_branch

                layer.append(B_branch)
            if node.b > 0:
                C_branch = Node(node.a, node.b-1, node.c+1)
                C_branch.prev = node
                node.C_choice = C_branch

                layer.append(C_branch)
    prev_layer = layer

if fail or prev_layer == []:
    print("No")
else:
    history = ""
    crt = prev_layer[0]
    for _ in range(N):
        prev_node = crt.prev
        if crt is prev_node.A_choice:
            history = "A" + history
        elif crt is prev_node.B_choice:
            history = "B" + history
        else:
            history = "C" + history
        crt = prev_node

    print("Yes")
    for one in history:
        print(one)

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10000000)

n, a, b, c = map(int, input().strip().split())
L = [input().strip() for _ in range(n)]

# global ans
# ans=[]

def dfs(a,b,c,route):
    global ans
    if a<0 or b<0 or c<0:
        return None
    
    depth=len(route)
    if depth==n:
        return route
    
    if L[depth]=="AB":
        newroute=dfs(a+1,b-1,c,route+"A")
        if newroute:
            return newroute
        newroute=dfs(a-1,b+1,c,route+"B")
        if newroute:
            return newroute
    elif L[depth]=="AC":
        newroute=dfs(a+1,b,c-1,route+"A")
        if newroute:
            return newroute
        newroute=dfs(a-1,b,c+1,route+"C")
        if newroute:
            return newroute
    elif L[depth]=="BC":
        newroute=dfs(a,b+1,c-1,route+"B")
        if newroute:
            return newroute
        newroute=dfs(a,b-1,c+1,route+"C")
        if newroute:
            return newroute
    
    return None

ans=dfs(a,b,c,"")
if ans:
    print("Yes")
    [print(c) for c in ans]
else:
    print("No")

Submission status: Time Limit Exceeded

Solution code:
import dataclasses
n, a, b, c = list(map(int, input().split(" ")))


@dataclasses.dataclass
class Data:
    history: str
    a: int
    b: int
    c: int

    def get_tuple(self):
        return ("", self.a, self.b, self.c)

    def check(self):
        return self.a >= 0 and self.b >= 0 and self.c >= 0

now = [Data("", a, b, c)]
for i in range(n):
    string = input()
    new = []
    tpls = set()
    if string == "AB":
        for j in now:
            cand = Data(j.history + "A", j.a + 1, j.b - 1, j.c)
            tp = cand.get_tuple()
            if cand.check() and tp not in tpls:
                new.append(cand)
                tpls.add(tp)

            cand = Data(j.history + "B", j.a - 1, j.b + 1, j.c)
            tp = cand.get_tuple()
            if cand.check() and tp not in tpls:
                new.append(cand)
                tpls.add(tp)

    elif string == "AC":
        for j in now:
            cand = Data(j.history + "A", j.a + 1, j.b, j.c - 1)
            tp = cand.get_tuple()
            if cand.check() and tp not in tpls:
                new.append(cand)
                tpls.add(tp)

            cand = Data(j.history + "C", j.a - 1, j.b, j.c + 1)
            tp = cand.get_tuple()
            if cand.check() and tp not in tpls:
                new.append(cand)
                tpls.add(tp)

    elif string == "BC":
        for j in now:
            cand = Data(j.history + "B", j.a, j.b + 1, j.c - 1)
            tp = cand.get_tuple()
            if cand.check() and tp not in tpls:
                new.append(cand)
                tpls.add(tp)

            cand = Data(j.history + "C", j.a, j.b - 1, j.c + 1)
            tp = cand.get_tuple()
            if cand.check() and tp not in tpls:
                new.append(cand)
                tpls.add(tp)
    if not new:
        print("No")
        break
    now = new
else:
    print("Yes")
    for i in now[0].history:
        print(i)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque

# input
N, A, B, C = map(int, input().split())
S = []
for _ in range(N):
    S.append(input())

# process
dq = deque()
dq.append((A, B, C, ""))

for i, s in enumerate(S):
    l = len(dq)
    for _ in range(l):
        a, b, c, op = list(dq.popleft())

        if s == "AB":
            if b != 0:
                dq.append((a+1, b-1, c, op+"A"))
            if a != 0:
                dq.append((a-1, b+1, c, op+"B"))
        elif s == "BC":
            if c != 0:
                dq.append((a, b+1, c-1, op+"B"))
            if b != 0:
                dq.append((a, b-1, c+1, op+"C"))
        else:
            if c != 0:
                dq.append((a+1, b, c-1, op+"A"))
            if a != 0:
                dq.append((a-1, b, c+1, op+"C"))

# output
if len(dq) == 0:
    print("No")
else:
    print("Yes")
    _, _, _, op = dq[0]
    [print(x) for x in op]

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/python3
import sys
import itertools
input = lambda: sys.stdin.readline().strip()
N, A, B, C = [int(x) for x in input().split()]
s = [input() for _ in range(N)]

def dp(A, B, C):
    summ = A + B + C
    perms = list(itertools.permutations('ABC'))

    def get_state(A, B, C):
        abc = sorted([(A, 'A'), (B, 'B'), (C, 'C')])
        return abc[0][0], abc[1][0], perms.index(tuple(label for count, label in abc))

    def get_abc(m1, m2, p):
        return dict(zip(perms[p], (m1, m2, summ - m1 - m2)))

    can = [[[[0 for p in range(6)] for m2 in range(4)] for m1 in range(4)] for i in range(N + 1)]
    mov = [[[[0 for p in range(6)] for m2 in range(4)] for m1 in range(4)] for i in range(N + 1)]
    for i in reversed(range(N + 1)):
        for m1 in range(4):
            for m2 in range(4):
                for p in range(6):
                    if i == N:
                        can[i][m1][m2][p] = True
                    elif summ - m1 - m2 >= 0:
                        abc = get_abc(m1, m2, p)
                        for j in (0, 1):
                            if abc[s[i][j ^ 1]] > 0:
                                abc[s[i][j]] += 1
                                abc[s[i][j ^ 1]] -= 1
                                mm1, mm2, pp = get_state(abc['A'], abc['B'], abc['C'])
                                if mm2 >= 4 or can[i + 1][mm1][mm2][pp]:
                                    can[i][m1][m2][p] = True
                                    mov[i][m1][m2][p] = j
                                abc[s[i][j]] -= 1
                                abc[s[i][j ^ 1]] += 1
    
    m1, m2, p = get_state(A, B, C)
    moves = []
    if can[0][m1][m2][p]:
        for i in range(N):
            moves.append(mov[i][m1][m2][p])
            abc = get_abc(m1, m2, p)
            abc[s[i][moves[-1]]] += 1
            abc[s[i][moves[-1] ^ 1]] -= 1
            m1, m2, p = get_state(abc['A'], abc['B'], abc['C'])
            if m2 >= 4:
                return greedy(abc['A'], abc['B'], abc['C'], i + 1, moves)
        return True, moves
    else:
        return False, []

def greedy(A, B, C, start=0, moves=[]):
    last = {'AB': 0, 'BC': 0, 'AC': 0}
    abc = {'A': A, 'B': B, 'C': C}
    can = True
    for x in s[start:]:
        if abc[x[0]] <= 1:
            last[x] = 0
        elif abc[x[1]] <= 1:
            last[x] = 1
        abc[x[last[x]]] += 1
        abc[x[last[x] ^ 1]] -= 1
        moves.append(last[x])
        last[x] ^= 1
        can &= all(x >= 0 for x in abc.values())
    return can, moves

if sum(1 for x in (A, B, C) if x < 4) >= 2:
    can, moves = dp(A, B, C)
else:
    can, moves = greedy(A, B, C)

if can:
    print('Yes')
    abc = {'A': A, 'B': B, 'C': C}
    for i in range(N):
        abc[s[i][moves[i]]] += 1
        abc[s[i][moves[i] ^ 1]] -= 1
        assert all(x >= 0 for x in abc.values())
    print(*(s[i][moves[i]] for i in range(N)), sep='\n')
else:
    print('No')

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def dp2(ini, i, j): return [[ini]*i for i2 in range(j)]
def dp3(ini, i, j, k): return [[[ini]*i for i2 in range(j)] for i3 in range(k)]
import copy
#import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from collections import Counter # a = Counter(A).most_common()
#from itertools import accumulate #list(accumulate(A))
 
N, *D = mi()
S = [sys.stdin.readline()[:2] for _ in range(N)]
ans = [0]*N
 
def cv(m):
    if m == 'A':
        return 0
    if m == 'B':
        return 1
    if m == 'C':
        return 2
 
def dfs(i, D, ans):
    if D[0]<0 or D[1]<0 or D[2]<0:
        return
    if i == N:
        print('Yes')
        for m in ans:
            print(m)
        exit()
    s, t = cv(S[i][0]), cv(S[i][1])
    D_ = copy.deepcopy(D)
    ans_ = copy.deepcopy(ans)
    D[s] += 1
    D[t] -= 1
    ans[i] = S[i][0]
    dfs(i+1, D, ans)
    D_[s] -= 1
    D_[t] += 1
    ans_[i] = S[i][1]
    dfs(i+1, D_, ans_)
 
dfs(0, D, ans)
print('No')

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**6)
n,A,B,C=map(int,input().split())
s=[input() for i in range(n)]
def dfs(d,a,b,c,now):
    global n,s
    if d==n:
        print("Yes")
        for i in range(n):
            print(now[i])
        sys.exit()
    else:
        if s[d][0]=="A" and s[d][1]=="B":
            if a>b:
                dfs(d+1,a-1,b+1,c,now+"B")
            elif a<b:
                dfs(d+1,a+1,b-1,c,now+"A")
            else:
                if a>0:
                    dfs(d+1,a-1,b+1,c,now+"B")
                if b>0:
                    dfs(d+1,a+1,b-1,c,now+"A")
        elif s[d][0]=="A" and s[d][1]=="C":
            if a>c:
                dfs(d+1,a-1,b,c+1,now+"C")
            elif a<c:
                dfs(d+1,a+1,b,c-1,now+"A")
            else:
                if a>0:
                    dfs(d+1,a-1,b,c+1,now+"C")
                if c>0:
                    dfs(d+1,a+1,b,c-1,now+"A")
        else:
            if b>c:
                dfs(d+1,a,b-1,c+1,now+"C")
            elif b<c:
                dfs(d+1,a,b+1,c-1,now+"B")
            else:
                if b>0:
                    dfs(d+1,a,b-1,c+1,now+"C")
                if c>0:
                    dfs(d+1,a,b+1,c-1,now+"B")

dfs(0,A,B,C,"")
print("No")

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**6)
n,A,B,C=map(int,input().split())
s=[input() for i in range(n)]
def dfs(d,a,b,c,now):
    global n,s
    if d==n:
        print("Yes")
        for i in range(n):
            print(now[i])
        sys.exit()
    else:
        if s[d][0]=="A" and s[d][1]=="B":
            if a>0:
                dfs(d+1,a-1,b+1,c,now+"B")
            if b>0:
                dfs(d+1,a+1,b-1,c,now+"A")
        elif s[d][0]=="A" and s[d][1]=="C":
            if a>0:
                dfs(d+1,a-1,b,c+1,now+"C")
            if c>0:
                dfs(d+1,a+1,b,c-1,now+"A")
        else:
            if b>0:
                dfs(d+1,a,b-1,c+1,now+"C")
            if c>0:
                dfs(d+1,a,b+1,c-1,now+"B")

dfs(0,A,B,C,"")
print("No")

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float('inf')
MOD=10**9+7

n,a,b,c=map(int,input().split())

s=[input() for _ in range(n)]

#不可能な場合
if a+b+c==0:
    print("No")
    exit()
elif a+b+c==1:
    result=[]
    for order in s:
        if "AB" == order:
            if c==1:
                print("No")
                exit()
            elif a==1:
                a-=1
                b+=1
                result.append("B")
            else:
                b-=1
                a+=1
                result.append("A")
        elif "AC" == order:
            if b==1:
                print("No")
                exit()
            elif a==1:
                a-=1
                c+=1
                result.append("C")
            else:
                c-=1
                a+=1
                result.append("A")
        elif "BC" == order:
            if a==1:
                print("No")
                exit()
            elif b==1:
                b-=1
                c+=1
                result.append("C")
            else:
                c-=1
                b+=1
                result.append("B")
    print("Yes")
    for item in result:
        print(item)
    exit()
else:

    result=[]
    abc=[a,b,c]
    order=[]

    def fukasa(order,abc,i):
        #print(order,abc,i)
        global n,s
        if -1 in abc:
            return 0
        if i== n:
            print("Yes")
            for item in order:
                print(item)
            exit()
        else:
            a=abc[0]
            b=abc[1]
            c=abc[2]
            if s[i]=="AB":
                if min([a+1,b-1,c])>min(a-1,b+1,c):
                    fukasa(order+["A"],[a+1,b-1,c],i+1)
                    fukasa(order+["B"],[a-1,b+1,c],i+1)
                else:
                    fukasa(order+["B"],[a-1,b+1,c],i+1)
                    fukasa(order+["A"],[a+1,b-1,c],i+1)
                    
            if s[i]=="AC":
                if min([a+1,b,c-1])>min(a-1,b,c+1):
                    fukasa(order+["A"],[a+1,b,c-1],i+1)
                    fukasa(order+["C"],[a-1,b,c+1],i+1)
                else:
                    fukasa(order+["C"],[a-1,b,c+1],i+1)
                    fukasa(order+["A"],[a+1,b,c-1],i+1)
                    
            if s[i]=="BC":
                if min([a,b+1,c-1])>min(a,b-1,c+1):
                    fukasa(order+["B"],[a,b+1,c-1],i+1)
                    fukasa(order+["C"],[a,b-1,c+1],i+1)
                else:
                    fukasa(order+["C"],[a,b-1,c+1],i+1)
                    fukasa(order+["B"],[a,b+1,c-1],i+1)



    fukasa([],[a,b,c],0)
    print("No")

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float('inf')
MOD=10**9+7

n,a,b,c=map(int,input().split())

s=[input() for _ in range(n)]

#不可能な場合
if a+b+c==0:
    print("No")
    exit()

result=[]

abc=[a,b,c]
order=[]

def fukasa(order,abc,i):
    #print(order,abc,i)
    global n,s
    if -1 in abc:
        return 0
    if i== n:
        print("Yes")
        for item in order:
            print(item)
        exit()
    else:
        a=abc[0]
        b=abc[1]
        c=abc[2]
        if s[i]=="AB":
            if min([a+1,b-1,c])>min(a-1,b+1,c):
                fukasa(order+["A"],[a+1,b-1,c],i+1)
                fukasa(order+["B"],[a-1,b+1,c],i+1)
            else:
                fukasa(order+["B"],[a-1,b+1,c],i+1)
                fukasa(order+["A"],[a+1,b-1,c],i+1)
                
        if s[i]=="AC":
            if min([a+1,b,c-1])>min(a-1,b,c+1):
                fukasa(order+["A"],[a+1,b,c-1],i+1)
                fukasa(order+["C"],[a-1,b,c+1],i+1)
            else:
                fukasa(order+["C"],[a-1,b,c+1],i+1)
                fukasa(order+["A"],[a+1,b,c-1],i+1)
                
        if s[i]=="BC":
            if min([a,b+1,c-1])>min(a,b-1,c+1):
                fukasa(order+["B"],[a,b+1,c-1],i+1)
                fukasa(order+["C"],[a,b-1,c+1],i+1)
            else:
                fukasa(order+["C"],[a,b-1,c+1],i+1)
                fukasa(order+["B"],[a,b+1,c-1],i+1)



fukasa([],[a,b,c],0)
print("No")

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float('inf')
MOD=10**9+7

n,a,b,c=map(int,input().split())

s=[input() for _ in range(n)]

#不可能な場合
if a+b+c==0:
    print("No")
    exit()

result=[]

abc=[a,b,c]
order=[]

def fukasa(order,abc,i):
    #print(order,abc,i)
    global n,s
    if -1 in abc:
        return 0
    if i== n:
        print("Yes")
        for item in order:
            print(item)
        exit()
    else:
        if s[i]=="AB":
            for index,item in enumerate([[1,-1,0],[-1,1,0]]):
                fukasa(order+[s[i][index]],[abc[0]+item[0],abc[1]+item[1],abc[2]+item[2]],i+1)
        if s[i]=="AC":
            for index,item in enumerate([[1,0,-1],[-1,0,1]]):
                fukasa(order+[s[i][index]],[abc[0]+item[0],abc[1]+item[1],abc[2]+item[2]],i+1)
        if s[i]=="BC":
            for index,item in enumerate([[0,1,-1],[0,-1,1]]):
                fukasa(order+[s[i][index]],[abc[0]+item[0],abc[1]+item[1],abc[2]+item[2]],i+1)

fukasa([],[a,b,c],0)
print("No")