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: Accepted

Solution code:

MOD = 10 ** 9 + 7
RLIMIT = 1000
DEBUG = 1

def main():
    for _ in inputt(1):
        n, a, b, c = inputi()
        S = inputl(n, input)
        if a == b == 0 and "AB" == S[0]:
            print("No")
            break
        if b == c == 0 and "BC" == S[0]:
            print("No")
            break
        if c == a == 0 and "AC" == S[0]:
            print("No")
            break
        if sum([a, b, c]) > 2:
            print("Yes")
            for z in S:
                if z == "AB":
                    if a < b:
                        print("A")
                        a += 1
                        b -= 1
                    else:
                        print("B")
                        a -= 1
                        b += 1
                elif z == "BC":
                    if b < c:
                        print("B")
                        b += 1
                        c -= 1
                    else:
                        print("C")
                        b -= 1
                        c += 1

                else:
                    if a < c:
                        print("A")
                        a += 1
                        c -= 1
                    else:
                        print("C")
                        a -= 1
                        c += 1
            break
        R = []
        if sum([a, b, c]) == 1:
            for z in S:
                if z == "AB":
                    if a == b == 0:
                        break
                    if a < b:
                        R.append("A")
                        a += 1
                        b -= 1
                    else:
                        R.append("B")
                        a -= 1
                        b += 1
                elif z == "BC":
                    if c == b == 0:
                        break
                    if b < c:
                        R.append("B")
                        b += 1
                        c -= 1
                    else:
                        R.append("C")
                        b -= 1
                        c += 1
                else:
                    if a == c == 0:
                        break
                    if a < c:
                        R.append("A")
                        a += 1
                        c -= 1
                    else:
                        R.append("C")
                        a -= 1
                        c += 1
            else:
                print("Yes")
                print(*R, split = "\n")
                break
            print("No")
            break

        print("Yes")
        for i, z in enumerate(S):
            if z == "AB":
                if a == 0:
                    print("A")
                    a += 1
                    b -= 1
                elif b == 0:
                    print("B")
                    a -= 1
                    b += 1
                else:
                    if i + 1 < n and "A" in S[i + 1]:
                        print("A")
                        a += 1
                        b -= 1
                    else:
                        print("B")
                        a -= 1
                        b += 1

            elif z == "BC":
                if c == 0:
                    print("C")
                    c += 1
                    b -= 1
                elif b == 0:
                    print("B")
                    c -= 1
                    b += 1
                else:
                    if i + 1 < n and "C" in S[i + 1]:
                        print("C")
                        c += 1
                        b -= 1
                    else:
                        print("B")
                        c -= 1
                        b += 1

            else:
                if a == 0:
                    print("A")
                    a += 1
                    c -= 1
                elif c == 0:
                    print("C")
                    a -= 1
                    c += 1
                else:
                    if i + 1 < n and "A" in S[i + 1]:
                        print("A")
                        a += 1
                        c -= 1
                    else:
                        print("C")
                        a -= 1
                        c += 1



# region M


# region import

from math import *
from heapq import *
from itertools import *
from functools import reduce, lru_cache, partial
from collections import Counter, defaultdict
import re, copy, operator, cmath
import sys, io, os, builtins
sys.setrecursionlimit(RLIMIT)

# endregion

# region fastio

BUFSIZE = 8192
class FastIO(io.IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = io.BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(io.IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
    if args:
        sys.stdout.write(str(args[0]))
        split = kwargs.pop("split", " ")
        for arg in args[1:]:
            sys.stdout.write(split)
            sys.stdout.write(str(arg))
    sys.stdout.write(kwargs.pop("end", "\n"))
def debug(*args, **kwargs):
    if DEBUG and not __debug__:
        print("debug", *args, **kwargs)
        sys.stdout.flush()
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip()
inputt = lambda t = 0: range(t) if t else range(int(input()))
inputs = lambda: input().split()
inputi = lambda k = int: map(k, inputs())
inputl = lambda t = 0, k = lambda: list(inputi()): [k() for _ in range(t)] if t else list(k())

# endregion

# region bisect

def len(a):
    if isinstance(a, range):
        return -((a.start - a.stop) // a.step)
    return builtins.len(a)
def bisect_left(a, x, key = None, lo = 0, hi = None):
    if lo < 0: lo = 0
    if hi == None: hi = len(a)
    if key == None: key = do_nothing
    while lo < hi:
        mid = (lo + hi) // 2
        if key(a[mid]) < x: lo = mid + 1
        else: hi = mid
    return lo
def bisect_right(a, x, key = None, lo = 0, hi = None):
    if lo < 0: lo = 0
    if hi == None: hi = len(a)
    if key == None: key = do_nothing
    while lo < hi:
        mid = (lo + hi) // 2
        if x < key(a[mid]): hi = mid
        else: lo = mid + 1
    return lo
def insort_left(a, x, key = None, lo = 0, hi = None):
    lo = bisect_left(a, x, key, lo, hi)
    a.insert(lo, x)
def insort_right(a, x, key = None, lo = 0, hi = None):
    lo = bisect_right(a, x, key, lo, hi)
    a.insert(lo, x)
do_nothing = lambda x: x
bisect = bisect_right
insort = insort_right
def index(a, x, default = None, key = None, lo = 0, hi = None):
    if lo < 0: lo = 0
    if hi == None: hi = len(a)
    if key == None: key = do_nothing
    i = bisect_left(a, x, key, lo, hi)
    if lo <= i < hi and key(a[i]) == x: return a[i]
    if default != None: return default
    raise ValueError
def find_lt(a, x, default = None, key = None, lo = 0, hi = None):
    if lo < 0: lo = 0
    if hi == None: hi = len(a)
    i = bisect_left(a, x, key, lo, hi)
    if lo < i <= hi: return a[i - 1]
    if default != None: return default
    raise ValueError
def find_le(a, x, default = None, key = None, lo = 0, hi = None):
    if lo < 0: lo = 0
    if hi == None: hi = len(a)
    i = bisect_right(a, x, key, lo, hi)
    if lo < i <= hi: return a[i - 1]
    if default != None: return default
    raise ValueError
def find_gt(a, x, default = None, key = None, lo = 0, hi = None):
    if lo < 0: lo = 0
    if hi == None: hi = len(a)
    i = bisect_right(a, x, key, lo, hi)
    if lo <= i < hi: return a[i]
    if default != None: return default
    raise ValueError
def find_ge(a, x, default = None, key = None, lo = 0, hi = None):
    if lo < 0: lo = 0
    if hi == None: hi = len(a)
    i = bisect_left(a, x, key, lo, hi)
    if lo <= i < hi: return a[i]
    if default != None: return default
    raise ValueError

# endregion

# region csgraph
# TODO

class Tree:
    def __init__(n):
        self._n = n
        self._conn = [[] for _ in range(n)]
        self._list = [0] * n
    def connect(a, b):
        pass

# endregion

# region ntheory

class Sieve:
    def __init__(self):
        self._n = 6
        self._list = [2, 3, 5, 7, 11, 13]
    def extend(self, n):
        if n <= self._list[-1]: return
        maxbase = int(n ** 0.5) + 1
        self.extend(maxbase)
        begin = self._list[-1] + 1
        newsieve = [i for i in range(begin, n + 1)]
        for p in self.primerange(2, maxbase):
            for i in range(-begin % p, len(newsieve), p):
                newsieve[i] = 0
        self._list.extend([x for x in newsieve if x])
    def extend_to_no(self, i):
        while len(self._list) < i: 
            self.extend(int(self._list[-1] * 1.5))
    def primerange(self, a, b):
        a = max(2, a)
        if a >= b: return
        self.extend(b)
        i = self.search(a)[1]
        maxi = len(self._list) + 1
        while i < maxi:
            p = self._list[i - 1]
            if p < b:
                yield p
                i += 1
            else: return
    def search(self, n):
        if n < 2: raise ValueError
        if n > self._list[-1]: self.extend(n)
        b = bisect(self._list, n)
        if self._list[b - 1] == n: return b, b
        else: return b, b + 1
    def __contains__(self, n):
        if n < 2: raise ValueError
        if not n % 2: return n == 2
        a, b = self.search(n)
        return a == b
    def __getitem__(self, n):
        if isinstance(n, slice):
            self.extend_to_no(n.stop + 1)
            return self._list[n.start: n.stop: n.step]
        else:
            self.extend_to_no(n + 1)
            return self._list[n]
sieve = Sieve()
def isprime(n):
    if n <= sieve._list[-1]:
        return n in sieve
    for i in sieve:
        if not n % i: return False
        if n < i * i: return True
prime = sieve.__getitem__
primerange = lambda a, b = 0: sieve.primerange(a, b) if b else sieve.primerange(2, a)
def factorint(n):
    factors = []
    for i in sieve:
        if n < i * i: break
        while not n % i:
            factors.append(i)
            n //= i
    if n != 1: factors.append(n)
    return factors
factordict = lambda n: Counter(factorint(n))

# endregion

# region main

if __name__ == "__main__":
    main()

# endregion


# endregion

Submission status: Accepted

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

ans = []
arr = {}
arr['A'] = A
arr['B'] = B
arr['C'] = C
for i, s in enumerate(Ss):
    v1 = s[0]
    v2 = s[1]
    if arr[v1] == arr[v2] == 0:
        print('No')
        exit()
    if i < N-1 and arr[v1] == arr[v2] == 1:
        if s == Ss[i+1]:
            ans.append(v1)
            arr[v1] += 1
            arr[v2] -= 1
        elif v1 in Ss[i+1]:
            ans.append(v1)
            arr[v1] += 1
            arr[v2] -= 1
        else:
            ans.append(v2)
            arr[v1] -= 1
            arr[v2] += 1
    elif arr[v1] < arr[v2]:
        ans.append(v1)
        arr[v1] += 1
        arr[v2] -= 1
    else:
        ans.append(v2)
        arr[v1] -= 1
        arr[v2] += 1
print('Yes')
for a in ans:
    print(a)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(700000)

def s_in():
    return input()

def n_in():
    return int(input())

def l_in():
    return list(map(int, input().split()))

n,a,b,c=l_in()
S=[s_in() for _ in range(n)]
current = [a,b,c]

def add_a():
    current[0]+=1
    res.append('A')

res = []

for i, s in enumerate(S):
    if s == 'AB':
        if a == 0 and b == 0:
            break
        if a > b:
            a -= 1
            b += 1
            res.append('B')
        elif a < b or i == n-1:
            a += 1
            b -= 1
            res.append('A')
        else:
            if 'A' in S[i+1]:
                a += 1
                b -= 1
                res.append('A')
            else:
                a -= 1
                b += 1
                res.append('B')
                
                
    if s == 'AC':
        if a == 0 and c == 0:
            break
        if a > c:
            a -= 1
            c += 1
            res.append('C')
        elif a<c  or i == n-1:
            a += 1
            c -= 1
            res.append('A')
        else:
            if 'A' in S[i+1]:
                a += 1
                c -= 1
                res.append('A')
            else:
                a -= 1
                c += 1
                res.append('C')
            
    if s == 'BC':
        if c == 0 and b == 0:
            break
        if b > c:
            b -= 1
            c += 1
            res.append('C')
            
        elif b<c  or i == n-1:
            b += 1
            c -= 1
            res.append('B')
        else:
            if 'B' in S[i+1]:
                b += 1
                c -= 1
                res.append('B')
            else:
                b -= 1
                c += 1
                res.append('C')
            
else:
    print('Yes')
    [print(r) for r in res]
    exit()

print('No')

Submission status: Accepted

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

import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))

n, a, b, c = LI()
s = [input() for _ in range(n)]
if a == 0 and b == 0 and c == 0:
    print('No')
    quit()
if a == 0 and b == 0 and c == 2:
    if s[0] == 'AB':
        print('No')
        quit()
if a == 0 and b == 2 and c == 0:
    if s[0] == 'AC':
        print('No')
        quit()
if a == 2 and b == 0 and c == 0:
    if s[0] == 'BC':
        print('No')
        quit()

ans = []
for i in range(n):
    if s[i] == 'AB':
        if a < b:
            a += 1
            b -= 1
            ans.append('A')
        elif a == b:
            if a == 0:
                print('No')
                quit()
            elif a == 1:
                if i < n-1:
                    if s[i+1] == 'AC':
                        a += 1
                        b -= 1
                        ans.append('A')
                    else:
                        b += 1
                        a -= 1
                        ans.append('B')
                else:
                    b += 1
                    a -= 1
                    ans.append('B')
            else:
                b += 1
                a -= 1
                ans.append('B')
        else:
            a -= 1
            b += 1
            ans.append('B')
    elif s[i] == 'AC':
        if a < c:
            a += 1
            c -= 1
            ans.append('A')
        elif a == c:
            if a == 0:
                print('No')
                quit()
            elif a == 1:
                if i < n-1:
                    if s[i+1] == 'BC':
                        c += 1
                        a -= 1
                        ans.append('C')
                    else:
                        a += 1
                        c -= 1
                        ans.append('A')
                else:
                    a += 1
                    c -= 1
                    ans.append('A')
            else:
                a += 1
                c -= 1
                ans.append('A')
        else:
            a -= 1
            c += 1
            ans.append('C')
    elif s[i] == 'BC':
        if b < c:
            b += 1
            c -= 1
            ans.append('B')
        elif b == c:
            if b == 0:
                print('No')
                quit()
            elif b == 1:
                if i < n-1:
                    if s[i+1] == 'AC':
                        c += 1
                        b -= 1
                        ans.append('C')
                    else:
                        b += 1
                        c -= 1
                        ans.append('B')
                else:
                    b += 1
                    c -= 1
                    ans.append('B')
            else:
                b += 1
                c -= 1
                ans.append('B')
        else:
            b -= 1
            c += 1
            ans.append('C')
print('Yes')
for i in ans:
    print(i)

Submission status: Accepted

Solution code:
n, a, b, c = map(int, input().split())
d = {'A':a, 'B':b, 'C':c}
ns = []
for i in range(n):
    ns.append(input())
path = []
flag = True
for i, j in enumerate(ns):
    x, y = j
    if d[x] > d[y]:
        d[x] -= 1
        d[y] += 1
        path.append(y)
    elif d[x] < d[y]:
        d[x] += 1
        d[y] -= 1
        path.append(x)
    else:
        if d[x] == 0:
            flag = False
            print('No')
            break
        if i + 1 < n:
            if x in ns[i + 1]:
                d[x] += 1
                d[y] -= 1
                path.append(x)
            else:
                d[y] += 1
                d[x] -= 1
                path.append(y)
        else:
            path.append(x)
if flag:
    print('Yes')
    for i in path:
        print(i)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

n,a,b,c = map(int,input().split())
ans = []
abc = [a,b,c]

d = {'AB\n':(0,1),'AC\n':(0,2),'BC\n':(1,2)}

if(a+b+c==0):
    print('No')
    exit()

if(a+b+c >= 3)|(a+b+c==1):
    for _ in range(n):
        s = input()
        x,y = d[s]
        if(abc[x]==0)&(abc[y]==0):
            print('No')
            exit()
        if(abc[x] < abc[y]):
            x,y = y,x
        abc[x] -= 1
        abc[y] += 1
        ans.append(y)

elif(a+b+c==2):
    ss = [input() for _ in range(n)]
    if(max(abc)==2):
        #(2,0,0)
        case = True
    else:
        case = False

    for i in range(n):
        s = ss[i]
        x,y = d[s]
        if(case)|(i==n-1):
            if(abc[x]==0)&(abc[y]==0):
                print('No')
                exit()
            if(abc[x] < abc[y]):
                x,y = y,x
            abc[x] -= 1
            abc[y] += 1
            case = False
        else:
            if(abc[x]!=abc[y]):
                if(abc[x] < abc[y]):
                    x,y = y,x
                abc[x] -= 1
                abc[y] += 1
                case = False
            else:
                sn = ss[i+1]
                if(x in d[sn]):
                    x,y = y,x
                abc[x] -= 1
                abc[y] += 1
                case = True
        ans.append(y)

print('Yes')
for i in ans:
    print(chr(i+ord('A')))

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

def select_a(a, b):
    nums[a] += 1
    nums[b] -= 1
    choices.append(a)

n, a, b, c = map(int, input().split())
nums = [a, b, c]
queries = []
for i in range(n):
    s = input()
    if 'AB' in s:
        queries.append((0, 1))
    elif 'AC' in s:
        queries.append((0, 2))
    else:
        queries.append((1, 2))

choices = []
for i in range(n):
    p, q = queries[i]
    if nums[p] > nums[q]:
        select_a(q, p)
        if min(nums) < 0:
            break
    elif nums[p] < nums[q]:
        select_a(p, q)
        if min(nums) < 0:
            break
    else:
        if i == n-1:
            select_a(p, q)
            if min(nums) < 0:
                break
        else:
            v, w = queries[i+1]
            if p in {v, w}:
                select_a(p, q)
                if min(nums) < 0:
                    break
            else:
                select_a(q, p)
                if min(nums) < 0:
                    break

if min(nums) < 0:
    print('No')
else:
    print('Yes')
    for choice in choices:
        print('ABC'[choice])

Submission status: Accepted

Solution code:
from collections import defaultdict

def getlist():
	return list(map(int, input().split()))

#処理内容
def main():
	N, A, B, C = getlist()
	ans = []
	Q = []
	cnt = 0
	for i in range(N):
		s = input()
		Q.append(s)

	#s1シミュレーﾄ
	if A + B + C == 1:
		for i in range(N):
			if Q[i] == "AB":
				if A == 1:
					ans.append("B")
					A -= 1; B += 1
				elif B == 1:
					ans.append("A")
					B -= 1; A += 1
				else:
					print("No")
					return
			elif Q[i] == "AC":
				if A == 1:
					ans.append("C")
					A -= 1; C += 1
				elif C == 1:
					ans.append("A")
					C -= 1; A += 1
				else:
					print("No")
					return
			else:
				if B == 1:
					ans.append("C")
					B -= 1; C += 1
				elif C == 1:
					ans.append("B")
					C -= 1; B += 1
				else:
					print("No")
					return
		print("Yes")
		for i in range(N):
			print(ans[i])
		return

	#初期化事故
	if Q[0] == "AB" and A == 0 and B == 0:
		print("No")
		return
	if Q[0] == "AC" and A == 0 and C == 0:
		print("No")
		return
	if Q[0] == "BC" and B == 0 and C == 0:
		print("No")
		return

	for i in range(N - 1):
		if Q[i] == "AB":
			if A == 1 and B == 0:
				ans.append("B")
				A -= 1; B += 1
			elif A == 0 and B == 1:
				ans.append("A")
				A += 1; B -= 1

			elif A >= 2:
				ans.append("B")
				A -= 1; B += 1
			elif B >= 2:
				ans.append("A")
				A += 1; B -= 1
			else:
				if Q[i + 1] == "AC":
					ans.append("A")
					A += 1; B -= 1
				else:
					ans.append("B")
					A -= 1; B += 1

		elif Q[i] == "AC":
			if A == 1 and C == 0:
				ans.append("C")
				A -= 1; C += 1
			elif A == 0 and C == 1:
				ans.append("A")
				A += 1; C -= 1

			elif A >= 2:
				ans.append("C")
				A -= 1; C += 1
			elif C >= 2:
				ans.append("A")
				A += 1; C -= 1
			else:
				if Q[i + 1] == "AB":
					ans.append("A")
					A += 1; C -= 1
				else:
					ans.append("C")
					A -= 1; C += 1

		else:
			if B == 1 and C == 0:
				ans.append("C")
				B -= 1; C += 1
			elif B == 0 and C == 1:
				ans.append("B")
				B += 1; C -= 1

			elif B >= 2:
				ans.append("C")
				B -= 1; C += 1
			elif C >= 2:
				ans.append("B")
				B += 1; C -= 1
			else:
				if Q[i + 1] == "AB":
					ans.append("B")
					B += 1; C -= 1
				else:
					ans.append("C")
					B -= 1; C += 1

	#最後
	if Q[N - 1] == "AB":
		if A >= 1:
			ans.append("B")
		else:
			ans.append("A")
	elif Q[N - 1] == "AC":
		if A >= 1:
			ans.append("C")
		else:
			ans.append("A")
	else:
		if B >= 1:
			ans.append("C")
		else:
			ans.append("B")

	print("Yes")
	for i in range(N):
		print(ans[i])


if __name__ == '__main__':
	main()

Submission status: Accepted

Solution code:
import sys

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

abc = {"A":a,"B":b,"C":c}

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

ans = [None]*n
i = 0
while i <n:
    x = s[i][0]
    y = s[i][1]
    if abc[x] == 0 and abc[y] ==0:
        print("No")
        sys.exit()
    elif abc[x] == 1 and abc[y] ==1 and i<n-1:
        if s[i] == s[i+1]:
            ans[i] = x
            ans[i+1] = y
            i += 1
        elif x in s[i+1]:
            ans[i] = x
            abc[x] += 1
            abc[y] -= 1
        else:
            ans[i] = y
            abc[x] -= 1
            abc[y] += 1
    else:
        if abc[x]<=abc[y]:
            ans[i] = x
            abc[x] += 1
            abc[y] -= 1
        else:
            ans[i] = y
            abc[x] -= 1
            abc[y] += 1
    i += 1
    
print("Yes")
print("\n".join(ans))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
n, a, b, c = map(int, input().split())
s = [input() for _ in range(n)]
ans = []
for i in range(n):
    if s[i] == "AB":
        if a < b:
            ans.append("A")
            a += 1
            b -= 1
        elif a > b:
            ans.append("B")
            a -= 1
            b += 1
        else:
            if i + 1 < n and s[i + 1] == "AC":
                ans.append("A")
                a += 1
                b -= 1
            else:
                ans.append("B")
                a -= 1
                b += 1
    if s[i] == "AC":
        if a < c:
            ans.append("A")
            a += 1
            c -= 1
        elif a > c:
            ans.append("C")
            a -= 1
            c += 1
        else:
            if i + 1 < n and s[i + 1] == "AB":
                ans.append("A")
                a += 1
                c -= 1
            else:
                ans.append("C")
                a -= 1
                c += 1
    if s[i] == "BC":
        if b < c:
            ans.append("B")
            b += 1
            c -= 1
        elif b > c:
            ans.append("C")
            b -= 1
            c += 1
        else:
            if i + 1 < n and s[i + 1] == "AB":
                ans.append("B")
                b += 1
                c -= 1
            else:
                ans.append("C")
                b -= 1
                c += 1
    if a < 0 or b < 0 or c < 0:
        print("No")
        exit()
print("Yes")
print(*ans, sep="\n")

Submission status: Accepted

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

is_possible = True
choice = []
ab = a + b
ac = a + c
bc = b + c

for i in range(n):
    if s[i] == 'AB':
        if ab == 0:
            is_possible = False
            break
        else:
            if ac > bc:
                choice.append('B')
                ac -= 1
                bc += 1
            elif ac == bc == 1 and i + 1 < n:
                if s[i + 1] == 'AC':
                    choice.append('A')
                    ac += 1
                    bc -= 1
                elif s[i + 1] == 'BC':
                    choice.append('B')
                    ac -= 1
                    bc += 1
                else:
                    choice.append('B')
                    ac -= 1
                    bc += 1
            else:
                choice.append('A')
                ac += 1
                bc -= 1
    elif s[i] == 'AC':
        if ac == 0:
            is_possible = False
            break
        else:
            if ab > bc:
                choice.append('C')
                ab -= 1
                bc += 1
            elif ab == bc == 1 and i + 1 < n:
                if s[i + 1] == 'AB':
                    choice.append('A')
                    ab += 1
                    bc -= 1
                elif s[i + 1] == 'BC':
                    choice.append('C')
                    ab -= 1
                    bc += 1
                else:
                    choice.append('C')
                    ab -= 1
                    bc += 1
            else:
                choice.append('A')
                ab += 1
                bc -= 1
    else:
        # BC
        if bc == 0:
            is_possible = False
            break
        else:
            if ab > ac:
                choice.append('C')
                ab -= 1
                ac += 1
            elif ab == ac == 1 and i + 1 < n:
                if s[i + 1] == 'AB':
                    choice.append('B')
                    ab += 1
                    ac -= 1
                elif s[i + 1] == 'AC':
                    choice.append('C')
                    ab -= 1
                    ac += 1
                else:
                    choice.append('C')
                    ab -= 1
                    ac += 1
            else:
                choice.append('B')
                ab += 1
                ac -= 1

if is_possible:
    print('Yes')
    print(*choice, sep='\n')
    # print('  ', 0, a, b, c)
    # for i in range(n):
    #     if s[i] == 'AB':
    #         if choice[i] == 'A':
    #             a += 1
    #             b -= 1
    #         else:
    #             a -= 1
    #             b += 1
    #     elif s[i] == 'AC':
    #         if choice[i] == 'A':
    #             a += 1
    #             c -= 1
    #         else:
    #             a -= 1
    #             c += 1
    #     else:
    #         # BC
    #         if choice[i] == 'B':
    #             b += 1
    #             c -= 1
    #         else:
    #             b -= 1
    #             c += 1
    #     print(s[i], choice[i], a, b, c)
else:
    print('No')