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:
#!/usr/bin/env python3
# vim: set fileencoding=utf-8

# pylint: disable=unused-import, invalid-name, missing-docstring, bad-continuation


"""Module docstring
"""

import functools
import heapq
import itertools
import logging
import math
import random
import string
import sys
from argparse import ArgumentParser
from collections import defaultdict, deque
from copy import deepcopy
from typing import Dict, List, Optional, Set, Tuple


def solve(values: List[str], a: int, b: int, c: int) -> Optional[List[str]]:
    state = [a, b, c]
    names = ["A", "B", "C"]
    result = []
    for i, turn in enumerate(values):
        indexes = []
        if "A" in turn:
            indexes.append(0)
        if "B" in turn:
            indexes.append(1)
        if "C" in turn:
            indexes.append(2)
        f, s = indexes[0], indexes[1]
        if state[f] < state[s]:
            f, s = s, f
        if state[f] == state[s] == 1 and i < len(values) - 1:
            if names[s] in values[i + 1]:
                # need to increment s
                s, f = f, s
        # f is the index of largest value
        state[f] -= 1
        if state[f] < 0:
            return None
        result.append(names[f])
        state[s] += 1
        LOG.debug((state))
    return result


def do_job():
    "Do the work"
    LOG.debug("Start working")
    # first line is number of test cases
    N, A, B, C = list(map(int, input().split()))
    values = []
    for _ in range(N):
        values.append(input().strip())
    result = solve(values, A, B, C)
    print_output(result)


def print_output(result) -> None:
    "Formats and print result"
    if result is None:
        print("No")
    else:
        print("Yes")
        for c in result:
            print(c)
    # 6 digits float precision {:.6f} (6 is the default value)
    # print("Case #{}: {:f}".format(testcase + 1, result))


def configure_log() -> None:
    "Configure the log output"
    log_formatter = logging.Formatter("%(lineno)d - " "%(message)s")
    handler = logging.StreamHandler(sys.stdout)
    handler.setFormatter(log_formatter)
    LOG.addHandler(handler)


LOG = None
# for interactive call: do not add multiple times the handler
if not LOG:
    LOG = logging.getLogger("template")
    configure_log()


def main(argv=None):
    "Program wrapper."
    if argv is None:
        argv = sys.argv[1:]
    parser = ArgumentParser()
    parser.add_argument(
        "-v",
        "--verbose",
        dest="verbose",
        action="store_true",
        default=False,
        help="run as verbose mode",
    )
    args = parser.parse_args(argv)
    if args.verbose:
        LOG.setLevel(logging.DEBUG)
    do_job()
    return 0


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    sys.exit(main())


class memoized:
    """Decorator that caches a function's return value each time it is called.
    If called later with the same arguments, the cached value is returned, and
    not re-evaluated.
    """

    def __init__(self, func):
        self.func = func
        self.cache = {}

    def __call__(self, *args):
        try:
            return self.cache[args]
        except KeyError:
            value = self.func(*args)
            self.cache[args] = value
            return value
        except TypeError:
            # uncachable -- for instance, passing a list as an argument.
            # Better to not cache than to blow up entirely.
            return self.func(*args)

    def __repr__(self):
        """Return the function's docstring."""
        return self.func.__doc__

    def __get__(self, obj, objtype):
        """Support instance methods."""
        return functools.partial(self.__call__, obj)

Submission status: Wrong Answer

Solution code:
import copy
import sys
from typing import Callable, Dict, List, NoReturn, Tuple


def choices(a: int, b: int, c: int, order: str) -> List[Tuple[int, ...]]:
    state: Dict[str, int] = {"a":a, "b":b, "c": c}
    results: List[Tuple[int, ...]] = []

    state[order[0]] += 1
    state[order[1]] -= 1
    results.append(tuple(state.values()))

    state: Dict[str, int] = {"a":a, "b":b, "c": c}

    state[order[1]] += 1
    state[order[0]] -= 1
    results.append(tuple(state.values()))

    return results


def dfs(a: int, b: int, c: int, n:int, s: List[str]) -> List[str]:
    path: List[str] = []
    state: Dict[str, int] = {"A": a, "B": b, "C": c, "depth": 0}
    nodes: List[Dict[str, int]] = [state]

    while nodes:
        next_node = nodes.pop()

        if min(next_node["A"], next_node["B"], next_node["C"]) >= 0:
            if next_node["depth"] == n:
                return path
            else:
                node_1 = copy.deepcopy(next_node)
                node_1[s[next_node["depth"]][1]] += 1
                node_1[s[next_node["depth"]][0]] -= 1
                node_1["depth"] += 1
                nodes.append(node_1)

                node_0 = copy.deepcopy(next_node)
                node_0[s[next_node["depth"]][0]] += 1
                node_0[s[next_node["depth"]][1]] -= 1
                node_0["depth"] += 1
                nodes.append(node_0)
                path.append(s[next_node["depth"]][0])

        else:
            path.pop()
            path.append(s[next_node["depth"] - 1][1])

    return []


def main() -> NoReturn:
    scan: Callable[[], str] = sys.stdin.readline

    n, a, b, c = map(int, scan().rstrip().split())  #type: int, int, int, int
    s: List[str] = [scan().rstrip() for _ in range(n)]

    answer: List[str] = dfs(a, b, c, n, s)

    if answer:
        print("Yes")
        for node in answer:
            print(node)

    else:
        print("No")


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))

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

def plus_minus(s,t):
    for c in ['A','B','C']:
        if (c in s) and (c in t):
            plus = c
    if s[0] == c:
        minus = s[1]
    else:
        minus = s[0]
    return plus, minus 

N,A,B,C = LI()
s = ['0']*N
for i in range(N):
    s[i] = str(input())

d = defaultdict(int)
d['A'] = A
d['B'] = B
d['C'] = C

if A+B+C == 0:
    print('No')
elif A+B+C == 1:
    ans = []
    for i in range(N):
        if d[s[i][0]] == d[s[i][1]] == 0:
            print('No')
            exit()
        else:
            if d[s[i][0]]:
                d[s[i][0]] -= 1
                d[s[i][1]] += 1
                ans.append(s[i][1])
            else:
                d[s[i][1]] -= 1
                d[s[i][0]] += 1
                ans.append(s[i][0])
    print('Yes')
    for a in ans:
        print(a)
else:
    if d[s[0][0]] == d[s[0][1]] == 0:
        print('No')
    else:
        print('Yes')
        for i in range(N):
            if d[s[i][0]] == 0:
                d[s[i][0]] += 1
                d[s[i][1]] -= 1
                print(s[i][0])
            elif d[s[i][1]] == 0:
                d[s[i][1]] += 1
                d[s[i][0]] -= 1
                print(s[i][1])
            elif d[s[i][0]] == d[s[i][1]] == 1:
                if i != N-1:
                    p,m = plus_minus(s[i],s[i+1])
                    d[p] += 1
                    d[m] -= 1
                    print(p)
                else:
                    d[s[i][0]] += 1
                    d[s[i][1]] -= 1
                    print(s[i][0])
            else:
                d[s[i][0]] += 1
                d[s[i][1]] -= 1
                print(s[i][0])

Submission status: Wrong Answer

Solution code:
if __name__ == '__main__':
    from sys import stdin
    # from collections import defaultdict
    # from collections import deque
    # from collections import Counter
    import math
    # import random
    input = stdin.readline


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

    count_ss = {'AB':0, 'AC':0, 'BC':0}
    ss = ['']*n
    for i in range(n):
        ss[i] = input()[:-1]
        count_ss[ss[i]] += 1

    need_a = math.ceil(-1*((a-n+count_ss['BC']))/2)
    need_b = math.ceil(-1*((b-n+count_ss['AC']))/2)
    need_c = math.ceil(-1*((c-n+count_ss['AB']))/2)
    if need_a < 0:
        need_a = 0
    if need_b < 0:
        need_b = 0
    if need_c < 0:
        need_c = 0
    # print(need_a, need_b, need_c)
    for i in range(count_ss['AB']+1):
        ac_a = max([need_a-i, 0])
        if ac_a > count_ss['AC']:
            continue
        ac_c = count_ss['AC']-ac_a
        bc_c = max([need_c-ac_c, 0])
        if bc_c > count_ss['BC']:
            continue
        if count_ss['BC'] - bc_c + count_ss['AB'] - i >= need_b:
            break
    else:
        print('No')
        exit()
    bc_b = count_ss['BC']-bc_c
    ab_a = i
    print('Yes')
    for s in ss:
        if s == 'AB':
            if ab_a > 0:
                print('A')
                ab_a -= 1
            else:
                print('B')
        if s == 'BC':
            if bc_b > 0:
                print('B')
                bc_b -= 1
            else:
                print('C')
        if s == 'AC':
            if ac_a > 0:
                print('A')
                ac_a -= 1
            else:
                print('C')

Submission status: Wrong Answer

Solution code:
N, A, B, C = map(int, input().split())
s = []
for i in range(N):
    s.append(input())

if A == 0 and B == 0 and C == 0:
    print("No")
elif A == 0 and B == 0 and C == 1 \
    or A == 0 and B == 1 and C == 0 \
    or A == 1 and B == 0 and C == 0:
    flag = True
    ans = []
    for i in range(N):
        if s[i] == "AB":
            if A == 0 and B == 0:
                flag = False
                break
            elif A < B:
                A += 1
                B -= 1
                ans.append("A")
            else:
                A -= 1
                B += 1
                ans.append("B")
        elif s[i] == "BC":
            if B == 0 and C == 0:
                flag = False
                break
            elif B < C:
                B += 1
                C -= 1
                ans.append("B")
            else:
                B -= 1
                C += 1
                ans.append("C")
        else:
            if C == 0 and A == 0:
                flag = False
                break
            elif C < A:
                C += 1
                A -= 1
                ans.append("C")
            else:
                C -= 1
                A += 1
                ans.append("A")
    if flag:
        print("Yes")
        print(*ans)
    else:
        print("No")
elif A == 0 and B == 0 and C > 1 and s[0] == "AB" \
        or A == 0 and B > 1 and C == 0 and s[0] == "AC" \
        or A > 1 and B == 0 and C == 0 and s[0] == "BC":
        print("No")
else:
    print("Yes")
    flag = 0
    ans = []
    for i in range(N):
        if flag > 0:
            if flag == 1:
                if s[i] == "AB":
                    ans.append("A")
                    ans.append("B")
                    continue
                elif s[i] == "BC":
                    A -= 1
                    C += 1
                    ans.append("B")
                    ans.append("C")
                else:
                    B -= 1
                    C += 1
                    ans.append("A")
                    ans.append("C")
            elif flag == 2:
                if s[i] == "BC":
                    ans.append("B")
                    ans.append("C")
                    continue
                elif s[i] == "AC":
                    B -= 1
                    A += 1
                    ans.append("C")
                    ans.append("A")
                else:
                    C -= 1
                    A += 1
                    ans.append("B")
                    ans.append("A")
            elif flag == 3:
                if s[i] == "AC":
                    ans.append("A")
                    ans.append("C")
                    continue
                elif s[i] == "AB":
                    C -= 1
                    B += 1
                    ans.append("A")
                    ans.append("B")
                else:
                    A -= 1
                    B += 1
                    ans.append("C")
                    ans.append("B")
            flag = 0
        else:
            if s[i] == "AB":
                if A < B:
                    A += 1
                    B -= 1
                    ans.append("A")
                elif A == 1 and B ==1 and C == 0:
                    flag = 1
                else:
                    A -= 1
                    B += 1
                    ans.append("B")
            elif s[i] == "BC":
                if B < C:
                    B += 1
                    C -= 1
                    ans.append("B")
                elif A == 0 and B == 1 and C ==1:
                    flag = 2
                else:
                    B -= 1
                    C += 1
                    ans.append("C")
            else:
                if C < A:
                    C += 1
                    A -= 1
                    ans.append("C")
                elif C == 1 and A ==1 and B == 0:
                    flag = 3
                else:
                    C -= 1
                    A += 1
                    ans.append("A")
    if flag == 1:
        ans.append("A")
    elif flag == 2:
        ans.append("B")
    elif flag == 3:
        ans.append("C")
    print(*ans)

Submission status: Wrong Answer

Solution code:
import sys
def input():
	return sys.stdin.readline()[:-1]

def included(x):
	if x == "AB":
		return 0, 1
	elif x == "BC":
		return 1, 2
	else:
		return 0, 2

def ans(x):
	l = ["A", "B", "C"]
	return l[x]

n, a, b, c = map(int, input().split())
nums = [a, b, c]
s = [input() for _ in range(n)]
res = []
for i, x in enumerate(s):
	y, z = included(x)
	if nums[y] == nums[z] == 0:
		print("No")
		break
	if i == n-1:
		if nums[y] >= nums[z]:
			res.append(ans(z))
		elif nums[z] > nums[y]:
			res.append(ans(y))
	else:
		if nums[y] > nums[z]:
			res.append(ans(z))
			nums[y] -= 1
			nums[z] += 1
		elif nums[z] > nums[y]:
			res.append(ans(y))
			nums[z] -= 1
			nums[y] += 1
		elif z in included(s[i+1]):
			res.append(ans(z))
			nums[y] -= 1
			nums[z] += 1
		else:
			res.append(ans(y))
			nums[z] -= 1
			nums[y] += 1

Submission status: Wrong Answer

Solution code:
n, a, b, c = map(int, input().split())
s = []
cnt = {
    "A": 0,
    "B": 0,
    "C": 0,
}
p = {
    "A": a,
    "B": b,
    "C": c,
}


def func(plus, minus) -> bool:
    global history, p
    p[plus] += 1
    p[minus] -= 1
    if (p[minus] < 0):
        return False
    else:
        history.append(plus)
        return True


for i in range(n):
    sl = input()
    s.append(sl)
    cnt[sl[0]] += 1
    cnt[sl[1]] += 1

history = []
f = True
for i in range(n):
    st = s[i]
    if (p[st[0]] > p[st[1]]):
        f &= func(st[1], st[0])
    elif (p[st[0]] < p[st[1]]):
        f &= func(st[0], st[1])
    else:
        if (cnt[st[0]] > cnt[st[1]]):
            f &= func(st[1], st[0])
        else:
            f &= func(st[0], st[1])
    cnt[st[0]] -= 1
    cnt[st[1]] -= 1

if (f):
    print("Yes")
    for i in history:
        print(i)
else:
    print("No")

Submission status: Wrong Answer

Solution code:
import sys
import math
from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN
from collections import deque
def I(): 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 S(): return sys.stdin.readline().rstrip()
def LS(): return sys.stdin.readline().split()
def LS2(N): return [sys.stdin.readline().split() for i in range(N)]
def FILL(i,h): return [i for j in range(h)]
def FILL2(i,h,w): return [FILL(i,w) for j in range(h)]
def FILL3(i,h,w,d): return [FILL2(i,w,d) for j in range(h)]
def FILL4(i,h,w,d,d2): return [FILL3(i,w,d,d2) for j in range(h)]
def sisha(num,digit): return Decimal(str(num)).quantize(Decimal(digit),rounding=ROUND_HALF_UP)
#'0.01'や'1E1'などで指定、整数に戻すならintをかます
MOD = 1000000007
INF = float("inf")
sys.setrecursionlimit(10**5+10)
#input = sys.stdin.readline
N,A,B,C = MI()
s = LS2(N)
abc = [A,B,C]
dic = {'A':0,'B':1,'C':2}
redic = {0:'A',1:'B',2:'C'}
f=0
select = []
for i in range(N):
    order = s[i][0]
    x = dic[order[0]]
    y = dic[order[1]]
    xnum=abc[x]
    ynum=abc[y]
    if xnum>ynum:
        select.append(y)
        abc[x] -= 1
        abc[y] += 1
    elif xnum==ynum:
        if i<N-1:
            next = s[i+1][0]
            nextx = dic[next[0]]
            nexty = dic[next[1]]
            if x==nextx or x==nexty:
                select.append(x)
                abc[x] += 1
                abc[y] -= 1
            else:
                select.append(y)
                abc[y] += 1
                abc[x] -= 1
    else:
        select.append(x)
        abc[x] += 1
        abc[y] -= 1
    for i in abc:
        if i<0:
            print('No')
            f=1
            break
    if f==1:
        break
else:
    print('Yes')
    [print(redic[x]) for x in select]

Submission status: Wrong Answer

Solution code:
def tvg(n, a, b, c):
    arr = [a, b, c]
    tab = ["A", "B", "C"]
    lkp = {"AB": 0, "BC": 1, "AC": 2}
    plk = ((0,1), (1,2), (0,2))
    lkc = {"A": 0, "B": 1, "C": 2}
    req, rec, stp = [0, 0, 0], [-1] * n, [None] * n
    for i in range(n):
        choice = input()
        rec[i] = lkp[choice]
        req[lkc[choice[0]]] += 1
        req[lkc[choice[1]]] += 1

    for i in range(n):
        j, k = plk[rec[i]]
        
        if arr[j] > arr[k]:
            arr[j] -= 1
            arr[k] += 1
            stp[i] = tab[k]
        elif arr[j] <= arr[k] and arr[k] != 1:
            arr[k] -= 1
            arr[j] += 1
            stp[i] = tab[j]
        else:
            if req[j] > req[k]:
                arr[k] -= 1
                arr[j] += 1
                stp[i] = tab[j]
            else:
                arr[j] -= 1
                arr[k] += 1
                stp[i] = tab[k]
        if arr[j] < 0 or arr[k] < 0:
            print("No")
            return
        req[j] -= 1
        req[k] -= 1
    print("Yes")
    for c in stp:
        print(c)


if __name__ == "__main__":
    import sys
    n, a, b, c = [int(_) for _ in input().split()]
    tvg(n, a, b, c)

Submission status: Wrong Answer

Solution code:
N, A, B, C = map(int, input().split())
s = []
for i in range(N):
    s.append(input())

if A == 0 and B == 0 and C == 0:
    print("No")
elif A+B+C == 1:
    flag = True
    ans = []
    for i in range(N):
        if s[i] == "AB":
            if A == 0 and B == 0:
                flag = False
                break
            elif A == 0:
                A = 1
                B = 0
                ans.append("A")
            else:
                A = 0
                B = 1
                ans.append("B")
        if s[i] == "BC":
            if B == 0 and C == 0:
                flag = False
                break
            elif B == 0:
                B = 1
                C = 0
                ans.append("B")
            else:
                B = 0
                C = 1
                ans.append("C")
        if s[i] == "AC":
            if A == 0 and C == 0:
                flag = False
                break
            elif A == 0:
                A = 1
                C = 0
                ans.append("A")
            else:
                A = 0
                C = 1
                ans.append("C")
    if flag:
        print("Yes")
        print(*ans)
    else:
        print("No")
elif A == 0 and B == 0 and s[0] == "AB" \
    or B == 0 and C == 0 and s[0] == "BC" \
    or A == 0 and C == 0 and s[0] == "AC":
    print("No")
elif A+B+C == 2:
    flag = False
    ans = []
    for i in range(N):
        if flag:
            if s[i-1] == "AB":
                if s[i] == "AB":
                    ans.append("A")
                    ans.append("B")
                elif s[i] == "BC":
                    A, B, C = 0, 1, 1
                    ans.append("B")
                    ans.append("C")
                elif s[i] == "AC":
                    A, B, C = 1, 0, 1
                    ans.append("A")
                    ans.append("C")
            if s[i-1] == "BC":
                if s[i] == "BC":
                    ans.append("B")
                    ans.append("C")
                elif s[i] == "AB":
                    A, B, C = 1, 0, 1
                    ans.append("B")
                    ans.append("A")
                elif s[i] == "AC":
                    A, B, C = 1, 0, 1
                    ans.append("C")
                    ans.append("A")
            if s[i-1] == "AC":
                if s[i] == "AC":
                    ans.append("A")
                    ans.append("C")
                elif s[i] == "AB":
                    A, B, C = 1, 1, 0
                    ans.append("A")
                    ans.append("B")
                elif s[i] == "BC":
                    A, B, C = 0, 1, 1
                    ans.append("C")
                    ans.append("B")
            flag = False
        else:
            if s[i] == "AB":
                if A == 1 and B == 1:
                    flag = True
                    continue
                elif A == 0:
                    A = 1
                    B = 0
                    ans.append("A")
                else:
                    A = 0
                    B = 1
                    ans.append("B")
            if s[i] == "BC":
                if B == 1 and C == 1:
                    flag = True
                    continue
                elif B == 0:
                    B = 1
                    C = 0
                    ans.append("B")
                else:
                    B = 0
                    C = 1
                    ans.append("C")
            if s[i] == "AC":
                if A == 1 and C == 1:
                    flag = True
                    continue
                elif A == 0:
                    A = 1
                    C = 0
                    ans.append("A")
                else:
                    A = 0
                    C = 1
                    ans.append("C")
    if flag:
        if s[i-1] == "AB" or s[i-1] == "AC":
            ans.append("A")
        else:
            ans.append("B")
        print("Yes")
        print(*ans)
else:
    ans = []
    for i in range(N):
        if s[i] == "AB":
            if A < B:
                A += 1
                B -= 1
                ans.append("A")
            else:
                A -= 1
                B += 1
                ans.append("B")
        if s[i] == "BC":
            if B < C:
                B += 1
                C -= 1
                ans.append("B")
            else:
                B -= 1
                C += 1
                ans.append("C")
        if s[i] == "AC":
            if A < C:
                A += 1
                C -= 1
                ans.append("A")
            else:
                A -= 1
                C += 1
                ans.append("C")
    print("Yes")
    print(*ans)

Submission status: Wrong Answer

Solution code:
import sys
def input():
	return sys.stdin.readline()[:-1]

def included(x):
	if x == "AB":
		return 0, 1
	elif x == "BC":
		return 1, 2
	else:
		return 0, 2

def ans(x):
	l = ["A", "B", "C"]
	return l[x]

n, a, b, c = map(int, input().split())
nums = [a, b, c]
s = [input() for _ in range(n)]
x, y = included(s[0])
if nums[x] == nums[y] == 0:
	print("No")
	sys.exit()
else:
	print("Yes")
	for i, x in enumerate(s):
		y, z = included(x)
		if i == n-1:
			if nums[y] >= nums[z]:
				print(ans(z))
			elif nums[z] > nums[y]:
				print(ans(y))
		else:
			if nums[y] > nums[z]:
				print(ans(z))
				nums[y] -= 1
				nums[z] += 1
			elif nums[z] > nums[y]:
				print(ans(y))
				nums[z] -= 1
				nums[y] += 1
			elif z in included(s[i+1]):
				print(ans(z))
				nums[y] -= 1
				nums[z] += 1
			else:
				print(ans(y))
				nums[z] -= 1
				nums[y] += 1

Submission status: Wrong Answer

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

S=[input() for i in range(N)]
AB=S.count("AB")
BC=S.count("BC")
AC=S.count("AC")
ans=[]
ab=0
bc=0
ac=0
for s in S:
    if s=="AB":
        ab+=1
        if A==0 and B==0:
            print("No")
            exit()
        if A>B:
            A-=1
            B+=1
            ans.append("B")
        elif B>A:
            A+=1
            B-=1
            ans.append("A")
        else:
            if (AB+AC-ab-ac)>=(AB+BC-ab-bc):
                A+=1
                B-=1
                ans.append("A")
            else:
                A-=1
                B+=1
                ans.append("B")
    elif s=="BC":
        bc+=1
        if B==0 and C==0:
            print("No")
            exit()
        if B>C:
            B-=1
            C+=1
            ans.append("C")
        elif C>B:
            B+=1
            C-=1
            ans.append("B")
        else:
            if (AB+BC-ab-bc)>=(BC+AC-bc-ac):
                B+=1
                C-=1
                ans.append("B")
            else:
                B-=1
                C+=1
                ans.append("C")
    else:
        ac+=1
        if A==0 and C==0:
            print("No")
            exit()
        if A>C:
            A-=1
            C+=1
            ans.append("C")
        elif C>A:
            A+=1
            C-=1
            ans.append("A")
        else:
            if (BC+AC-bc-ac)>=(AB+AC-ab-ac):
                A+=1
                C-=1
                ans.append("A")
            else:
                A-=1
                C+=1
                ans.append("C")
print("Yes")
for i in range(N):
    print(ans[i])

Submission status: Wrong Answer

Solution code:
N,A,B,C = map(int,(input().split()))
s = [[] for _ in range(N+1)]
for i in range(N):
    s[i] = input()
s[N] = "NOTHING"

flag = 0
ans = []
S = A+B+C

if S >= 3:
    for i in range(N):
        if s[i] == "AB":
            if A+B <= 0:
                flag = 1
                break
            if A >= B:
                ans.append("B")
                B += 1
                A -= 1
            else:
                ans.append("A")
                A += 1
                B -= 1

        if s[i] == "AC":
            if A+C <= 0:
                flag = 1
                break
            if A >= C:
                ans.append("C")
                C += 1
                A -= 1
            else:
                ans.append("A")
                A += 1
                C -= 1

        if s[i] == "BC":
            if B+C <= 0:
                flag = 1
                break
            if B >= C:
                ans.append("C")
                C += 1
                B -= 1
            else:
                ans.append("B")
                B += 1
                C -= 1
    if flag == 1:
        print("No")
    else:
        print("Yes")
        for i in ans:
            print(i)

else:
    
    for i in range(N):
        #print(A,B,C)
        if s[i] == "AB":
            if A+B <= 0:
                flag = 1
                break
            if B == 0:
                ans.append("B")
                B += 1
                A -= 1
            elif A == 0:
                ans.append("A")
                A += 1
                B -= 1
            else:
                if s[i+1] == "AC":
                    ans.append("A")
                    A += 1
                    B -= 1
                else:
                    ans.append("A")
                    B += 1
                    A -= 1

        if s[i] == "AC":
            if A+C <= 0:
                flag = 1
                break
            if C == 0:
                ans.append("C")
                C += 1
                A -= 1
            elif A == 0:
                ans.append("A")
                A += 1
                C -= 1
            else:
                if s[i+1] == "BC":
                    ans.append("C")
                    C += 1
                    A -= 1
                else:
                    ans.append("A")
                    A += 1
                    C -= 1

        if s[i] == "BC":
            if B+C <= 0:
                flag = 1
                break
            if C == 0:
                ans.append("C")
                C += 1
                B -= 1
            elif B == 0:
                ans.append("B")
                B += 1
                C -= 1
            else:
                if s[i+1] == "AC":
                    ans.append("C")
                    C += 1
                    B -= 1
                else:
                    ans.append("B")
                    B += 1
                    C -= 1

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