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:
N,A,B,C = map(int,input().split())
s = [input() for i in range(N)]

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

if (B == 0 and C == 0 and s[0] == 'BC') or (A == 0 and C == 0 and s[0] == 'AC') or (A == 0 and B == 0 and s[0] == 'AB'):
    print('No')
    exit()

print('Yes')

D = []

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

Submission status: Wrong Answer

Solution code:
def transfer(a,b,B):
    a -= 1
    b += 1
    ans.append(B)
n,A,B,C = map(int,input().split())
flag = True
ans = []
s = []
for i in range(n):
    s.append(input())
s.append("")
for i in range(n):
    if s[i] == "AB":
        if A == 0 and B == 0:
            flag = False
        elif A == 1 and B == 1:
            if s[i+1] == "BC":
                transfer(A,B,"B")
            else:
                transfer(B,A,"A")
        elif A >= B:
            transfer(A,B,"B")
        else:
            transfer(B,A,"A")
    if s[i] == "AC":
        if A == 0 and C == 0:
            flag = False
        elif A == 1 and C == 1:
            if s[i+1] == "BC":
                transfer(A,C,"C")
            else:
                transfer(C,A,"A")
        elif A >= C:
            transfer(A,C,"C")
        else:
            transfer(C,A,"A")
    if s[i] == "BC":
        if B == 0 and C == 0:
            flag = False
        elif B == 1 and C == 1:
            if s[i+1] == "AC":
                transfer(B,C,"C")
            else:
                transfer(C,B,"B")
        elif B >= C:
            transfer(B,C,"C")
        else:
            transfer(C,B,"B")
if flag:
    print("Yes")
    for i in ans:
        print(i)
else:
    print("No")

Submission status: Wrong Answer

Solution code:
from itertools import combinations

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

cnt = {'A': A, 'B': B, 'C': C}

def out(T):
    now = {'A': A, 'B': B, 'C': C}

    ans = []
    for i, s in enumerate(S):
        u, v = s[0], s[1]
        if now[u] == now[v] == 0:
            return []
        if now[u] > now[v]:
            ans.append(v)
            now[u] -= 1
            now[v] += 1
            continue
        if now[u] < now[v]:
            ans.append(u)
            now[u] += 1
            now[v] -= 1
            continue
        if i == N - 1:
            ans.append(u)
            continue

        nx = S[i + 1]
        if u in nx:
            ans.append(u)
            now[u] += 1
            now[v] -= 1
            continue
        if v in nx:
            ans.append(v)
            now[v] += 1
            now[u] -= 1
            continue

    return ans

ans = out('')
if len(ans) == 0:
    print('No')
print('Yes')
print(*ans, sep='\n')

# for s in combinations(['', '', 'A', 'B', 'C'], r=3):
#     s = ''.join(s)
#     for t in s:
#         if cnt[t] == 0:
#             break
#     else:
#         ans = out(s)
#         if len(ans) == 0:
#             continue
#         print('Yes')
#         print(*ans, sep='\n')
#         exit()

# print('No')

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7 # 998244353
input=lambda:sys.stdin.readline().rstrip()
def resolve():
    n, a, b, c = map(int,input().split())
    D = {"AB" : (0, 1), "AC" : (0, 2), "BC" : (1, 2)}
    E = {0 : 'A', 1 : 'B', 2 : 'C'}
    queries = [D[input()] for _ in range(n)]
    s = a + b + c

    if s != 2:
        ans = []
        state = [a, b, c]
        for i, j in queries:
            if state[i] == 0 and state[j] == 0:
                print("No")
                return
            if state[i] < state[j]:
                state[i] += 1
                state[j] -= 1
                ans.append(E[i])
            else:
                state[i] -= 1
                state[j] += 1
                ans.append(E[j])
        print("Yes")
        print(*ans, sep = '\n')
        return

    # s = 2
    dp = set()
    dp.add((a, b, c))
    prev = [{}] * n
    for k in range(n):
        ndp = set()
        i, j = queries[k]
        for key in dp:
            if key[i] > 0:
                tmp = list(key)
                tmp[i] -= 1
                tmp[j] += 1
                tmp = tuple(tmp)
                ndp.add(tmp)
                prev[k][tmp] = key
            if key[j] > 0:
                tmp = list(key)
                tmp[i] += 1
                tmp[j] -= 1
                tmp = tuple(tmp)
                ndp.add(tmp)
                prev[k][tmp] = key
        dp = ndp

    if len(dp) == 0:
        print("No")
        return

    print("Yes")
    for key in dp:
        now = key
        break

    ans = []
    for k in range(n - 1, -1, -1):
        a, b, c = now
        pa, pb, pc = prev[k][now]
        if a > pa:
            ans.append('A')
        elif b > pb:
            ans.append('B')
        elif c > pc:
            ans.append('C')
        now = pa, pb, pc
    ans.reverse()
    print(*ans, sep = '\n')
resolve()

Submission status: Wrong Answer

Solution code:
# F - Three Variables Game

N, A, B, C = map(int, input().split())

ansArr = []
ans = 'Yes'
for s in range(N):
    s = input()
    if s=='AB':
        if A <= B:
            A += 1
            B -= 1
            if B < 0:
                ans = 'No'
                break
            ansArr.append('A')
        else:
            A -= 1
            B += 1
            ansArr.append('B')
    elif s =='AC':
        if A <= C:
            A += 1
            C -= 1
            if C < 0:
                ans = 'No'
                break
            ansArr.append('A')
        else:
            A -= 1
            C += 1
            ansArr.append('C')
    else:
        if B <= C:
            B += 1
            C -= 1
            if C < 0:
                ans = 'No'
                break
            ansArr.append('B')
        else:
            B -= 1
            C += 1
            ansArr.append('C')

print(ans)
if ans=='Yes':
    for a in ansArr:
        print(a)

Submission status: Wrong Answer

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

import sys
# import math
# from string import ascii_lowercase, ascii_upper_case, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)


def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1               # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    

    def parse(com):
        if com == 'AB':
            return 0, 1
        elif com == 'BC':
            return 1, 2
        else:
            return 0, 2

    def sim_1(t_copy, commands):
        s = 'ABC'
        result = []
        for com in commands:
            i, j = parse(com)
            if t_copy[i] == 0 and t_copy[j] == 0:
                return False, result
            elif t_copy[i] == 0:
                result.append(s[i])
                t_copy[i], t_copy[j] = 1, 0
            else:
                result.append(s[j])
                t_copy[i], t_copy[j] = 0, 1
        return True, result
    

    def sim_2(t_copy, commands):
        s = 'ABC'
        size = len(commands)
        result = []
        for k in range(size):
            com = commands[k]
            i, j = parse(com)
            if t_copy[i] == 0 and t_copy[j] == 0:
                return False, result
            elif t_copy[i] == 0:
                result.append(s[i])
                t_copy[i] += 1
                t_copy[j] -= 1
            elif t_copy[j] == 0:
                result.append(s[j])
                t_copy[j] += 1
                t_copy[i] -= 1
            else:
                if k != size - 1:
                    next_com = commands[k + 1]
                    next_i, next_j = parse(next_com)
                    if i == next_i and j != next_j and t_copy[next_i] == 1 and t_copy[next_j] == 0:
                        result.append(s[i])
                        t_copy[i] += 1
                        t_copy[j] -= 1
                        continue
                    elif i != next_i and j == next_j and t_copy[next_i] == 0 and t_copy[next_j] == 1:
                        result.append(s[j])
                        t_copy[j] += 1
                        t_copy[i] -= 1
                        continue
                # 自由
                result.append(s[i])
                t_copy[i] += 1
                t_copy[j] -= 1
        return True, result
            
    
    n, a, b, c  = mi()
    t = [a, b, c]
    commands = [input() for _ in range(n)]
    if sum(t) == 0:
        predicate, result = False, []
    elif sum(t) == 1:
        predicate, result = sim_1(t[:], commands)
    else:
        predicate, result = sim_2(t[:], commands)
    
    if predicate:
        print('Yes')
        print(*result, sep='\n')
    else:
        print('No')


    

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
n,a,b,c = map(int,input().split())
s = [input() for _ in range(n)]
c2v = {'A':a,'B':b,'C':c}
sum_v = sum(c2v.values())
if sum_v == 0:
    print('No')
    exit()
if sum_v == 1:
    ans = []
    for ss in s:
        if c2v[ss[0]] == 0 and c2v[ss[1]] == 0:
            print('No')
            exit()
        elif c2v[ss[0]] == 0 and c2v[ss[1]] == 1:
            ans.append(ss[0])
        elif c2v[ss[0]] == 1 and c2v[ss[1]] == 0:
            ans.append(ss[1])
    print('Yes')
    for ans_i in ans:
        print(ans_i)

if sum_v >= 2:
    ans = []
    for ss_i,ss in enumerate(s):
        if c2v[ss[0]] == 0 and c2v[ss[1]] == 0:
            print('No')
            exit()
        elif c2v[ss[0]] == 0 and c2v[ss[1]] >= 1:
            ans.append(ss[0])
        elif c2v[ss[0]] >= 1 and c2v[ss[1]] == 0:
            ans.append(ss[1])
        else: # どっちから引いてもとりあえず大丈夫な場合は次のターンでダメな状態、（0,0）に陥らないように次に出てくる方に加算する。
            if ss_i+1 == n: # 最後だから適当でいい
                ans.append(ss[0])
                continue
            next_ss = s[ss_i+1]
            if ss[0] in next_ss:
                ans.append(ss[0])
            else:
                ans.append(ss[1])
    print('Yes')
    for ans_i in ans:
        print(ans_i)

Submission status: Wrong Answer

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

abc = [a,b,c]

def get_index(ch):
    if (ch == "A"):return 0
    elif (ch == "B"):return 1
    else:return 2

ans = ["Yes"]
S = [input() for _ in range(n)]
for i in range(n):
    s = S[i]
    s1 = get_index(s[0])
    s2 = get_index(s[1])
    
    if abc[s1] == 0 and abc[s2] == 0:
        ans[0] = "No"
    
    elif abc[s1] + abc[s2] == 1:
        if abc[s1] == 1:
            abc[s1] -= 1
            abc[s2] += 1
            ans.append(s[1])
        else:
            abc[s1] += 1
            abc[s2] -= 1
            ans.append(s[0])
    
    elif abc[s1] + abc[s2] == 2 and i != n-1 and S[i] != S[i+1]:
        next_s = S[i+1]
        next_s1 = get_index(next_s[0])
        next_s2 = get_index(next_s[1]) 
        if s1 == next_s1:
            abc[s1] += 1
            abc[s2] -= 1
            ans.append(s[0])
        else:
            abc[s1] -= 1
            abc[s2] += 1
            ans.append(s[1])
    
    else:
        abc[s1] -= 1
        abc[s2] += 1
        ans.append(s[1])

for a in ans:
    print(a)
    if a == "No":
        break

Submission status: Wrong Answer

Solution code:
n,a,b,c=map(int,input().split())
s=[]
for i in range(n):
    s.append(input())
s.append('EOF')

ans=[]
 
flag=True
 
for i in range(n):
    if s[i]=='AB':
        if a==0 and b==0:
            flag=False
            break
        if a==0 or (a==1 and s[i+1]=='AC'):
            ans.append('A')
            a+=1
            b-=1
        else:
            ans.append('B')
            a-=1
            b+=1
    elif s[i]=='AC':
        if a==0 and c==0:
            flag=False
            break
        if a==0 or (a==1 and s[i+1]=='AB'):
            ans.append('A')
            a+=1
            c-=1
        else:
            ans.append('C')
            a-=1
            c+=1
    else:
        if c==0 and b==0:
            flag=False
            break
        if c==0 or (b==1 and s[i+1]=='AC'):
            ans.append('C')
            c+=1
            b-=1
        else:
            ans.append('B')
            c-=1
            b+=1

if flag:
    print("Yes")
    for i in ans:
        print(i)
else:
    print("No")

Submission status: Wrong Answer

Solution code:
n,a,b,c = map(int,input().split())
s = [input() for _ in range(n)]
c2v = {'A':a,'B':b,'C':c}
sum_v = sum(c2v.values())
if sum_v == 0:
    print('No')
    exit()
if sum_v == 1:
    ans = []
    for ss in s:
        if c2v[ss[0]] == 0 and c2v[ss[1]] == 0:
            print('No')
            exit()
        elif c2v[ss[0]] == 0 and c2v[ss[1]] == 1:
            ans.append(ss[0])
        elif c2v[ss[0]] == 1 and c2v[ss[1]] == 0:
            ans.append(ss[1])
    print('Yes')
    for ans_i in ans:
        print(ans_i)

if sum_v >= 2:
    ans = []
    for ss_i,ss in enumerate(s):
        if c2v[ss[0]] == 0 and c2v[ss[1]] == 0:
            print('No')
            exit()
        elif c2v[ss[0]] == 0 and c2v[ss[1]] == 1:
            ans.append(ss[0])
        elif c2v[ss[0]] == 1 and c2v[ss[1]] == 0:
            ans.append(ss[1])
        else: # どっちから引いてもとりあえず大丈夫な場合は次のターンでダメな状態、（0,0）に陥らないように次に出てくる方に加算する。
            if ss_i+1 == n: # 最後だから適当でいい
                ans.append(ss[0])
                continue
            next_ss = s[ss_i+1]
            if ss[0] in next_ss:
                ans.append(ss[0])
            else:
                ans.append(ss[1])
    print('Yes')
    for ans_i in ans:
        print(ans_i)

Submission status: Wrong Answer

Solution code:
from itertools import combinations

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

cnt = {'A': A, 'B': B, 'C': C}

def out(T):
    now = {'A': 0, 'B': 0, 'C': 0}
    for s in T:
        now[s] += 1

    ans = []
    for i, s in enumerate(S):
        u, v = s[0], s[1]
        if now[u] == now[v] == 0:
            return []
        if now[u] > now[v]:
            ans.append(v)
            now[u] -= 1
            now[v] += 1
            continue
        if now[u] < now[v]:
            ans.append(u)
            now[u] += 1
            now[v] -= 1
            continue
        if i == N - 1:
            ans.append(u)
            continue

        nx = S[i + 1]
        if u in nx:
            ans.append(u)
            now[u] += 1
            now[v] -= 1
            continue
        if v in nx:
            ans.append(v)
            now[v] += 1
            now[u] -= 1
            continue

    return ans

for s in combinations(['', '', 'A', 'B', 'C'], r=3):
    s = ''.join(s)
    for t in s:
        if cnt[t] == 0:
            break
    else:
        ans = out(s)
        if len(ans) == 0:
            continue
        print('Yes')
        print(*ans, sep='\n')
        exit()

print('No')

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N,A,B,C=map(int,input().split())
    n=[A,B,C]
    d={'AB':0,'BC':1,'AC':2}
    before=[[],[],[]]
    ans=[-1]*N
    for i in range(N):
        s=input()
        if n[d[s]]==0 and n[(d[s]+1)%3]==0:
            if before[d[s]] and before[(d[s]+1)%3]:
                if before[d[s]][-1][0]>before[(d[s]+1)%3][-1][0]:
                    k,l=before[d[s]].pop()
                    n[d[s]]+=1
                    n[l]-=1
                    ans[k]=d[s]
                else:
                    k,l=before[(d[s]+1)%3].pop()
                    n[(d[s]+1)%3]+=1
                    n[l]-=1
                    ans[k]=(d[s]+1)%3
            elif before[d[s]] or before[(d[s]+1)%3]:
                if before[d[s]]:
                    k,l=before[d[s]].pop()
                    n[d[s]]+=1
                    n[l]-=1
                    ans[k]=d[s]
                elif before[(d[s]+1)%3]:
                    k,l=before[(d[s]+1)%3].pop()
                    n[(d[s]+1)%3]+=1
                    n[l]-=1
                    ans[k]=(d[s]+1)%3
            else:
                print('No')
                exit()
        if n[d[s]]==0:
            ans[i]=d[s]
            n[d[s]]+=1
            n[(d[s]+1)%3]-=1
        elif n[(d[s]+1)%3]==0:
            ans[i]=(d[s]+1)%3
            n[d[s]]-=1
            n[(d[s]+1)%3]+=1
        else:
            if n[d[s]]<n[(d[s]+1)%3]:
                ans[i]=d[s]
                n[d[s]]+=1
                n[(d[s]+1)%3]-=1
                before[(d[s]+1)%3].append((i,d[s]))
            else:
                ans[i]=(d[s]+1)%3
                n[d[s]]-=1
                n[(d[s]+1)%3]+=1
                before[d[s]].append((i,(d[s]+1)%3))
    print('Yes')
    d2=['A','B','C']
    for a in ans:
        print(d2[a])

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n, a, b, c = map(int, input().split())
q = [(0, 1) if si == 'AB' else (1, 2) if si == 'BC' else (0, 2) for si in (input() for _ in range(n))]
ans = []
ch = ['A', 'B', 'C']
d = [a, b, c]

nxt = [[-1] * 3] * n
t = [-1, -1, -1]
for i, (x, y) in reversed(list(enumerate(q))):
    nxt[i] = t.copy()
    t[x], t[y] = y, x
for (x, y), t in zip(q, nxt):
    if d[x] == d[y] == 0:
        print('No')
        break
    if d[y] == 0 or d[x] >= 2 or t[3 - x - y] == y:
            x, y = y, x
    d[x] += 1
    d[y] -= 1
    ans.append(ch[x])
else:
    print('Yes', *ans, sep='\n')

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
import sys
from collections import deque
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
input=lambda: sys.stdin.readline().rstrip()
YesNo=lambda b: bool([print('Yes')] if b else print('No'))
YESNO=lambda b: bool([print('YES')] if b else print('NO'))
int1=lambda x:int(x)-1

def main():
    N,A,B,C=map(int,input().split())
    n=[A,B,C]
    d={'AB':0,'BC':1,'AC':2}
    before=[[],[],[]]
    ans=[-1]*N
    for i in range(N):
        s=input()
        if n[d[s]]==0 and n[(d[s]+1)%3]==0:
            if before[d[s]] and before[(d[s]+1)%3]:
                if before[d[s]][-1]>before[(d[s]+1)%3][-1]:
                    k,l=before[d[s]].pop()
                    n[d[s]]+=1
                    n[l]-=1
                    ans[k]=d[s]
                else:
                    k,l=before[(d[s]+1)%3].pop()
                    n[(d[s]+1)%3]+=1
                    n[l]-=1
                    ans[k]=(d[s]+1)%3
            elif before[d[s]] or before[(d[s]+1)%3]:
                if before[d[s]]:
                    k,l=before[d[s]].pop()
                    n[d[s]]+=1
                    n[l]-=1
                    ans[k]=d[s]
                elif before[(d[s]+1)%3]:
                    k,l=before[(d[s]+1)%3].pop()
                    n[(d[s]+1)%3]+=1
                    n[l]-=1
                    ans[k]=(d[s]+1)%3
            else:
                print('No')
                exit()
        if n[d[s]]==0:
            ans[i]=d[s]
            n[d[s]]+=1
            n[(d[s]+1)%3]-=1
        elif n[(d[s]+1)%3]==0:
            ans[i]=(d[s]+1)%3
            n[d[s]]-=1
            n[(d[s]+1)%3]+=1
        else:
            if n[d[s]]<n[(d[s]+1)%3]:
                ans[i]=d[s]
                n[d[s]]+=1
                n[(d[s]+1)%3]-=1
                before[(d[s]+1)%3].append((i,d[s]))
            else:
                ans[i]=(d[s]+1)%3
                n[d[s]]-=1
                n[(d[s]+1)%3]+=1
                before[d[s]].append((i,(d[s]+1)%3))
    print('Yes')
    d2=['A','B','C']
    for a in ans:
        print(d2[a])

if __name__ == '__main__':
    main()