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:
n,a,b,c = map(int,input().split())
abc = {'A':a,'B':b,'C':c}
ans = []

if a+b+c==0:
    for _ in range(n):
        s = input()
    print('No')
elif a+b+c==1:
    for _ in range(n):
        s = input()
        x,y = s[0],s[1]
        if abc[x]==abc[y]:
            print('No')
            break
        elif abc[x]==1:
            abc[x] -=1
            abc[y] +=1
            ans.append(y)
        else:
            abc[x] +=1
            abc[y] -=1
            ans.append(x)
elif a+b+c==2:
    s = input()
    x,y = s[0],s[1]
    if abc[x]==0 and abc[y]==0:
        print('No')
    else:
        for _ in range(n-1):
            s_ = input()
            x_,y_ = s_[0],s_[1]
            if abc[x]==abc[y]:
                if x==x_ or (x!=x_ and y!=y_ and x == 'B'):
                    abc[x] +=1
                    abc[y] -=1
                    ans.append(x)
                else:
                    abc[x] -=1
                    abc[y] +=1
                    ans.append(y)
            elif abc[x]>=1:
                abc[x] -=1
                abc[y] +=1
                ans.append(y)
            else:
                abc[x] +=1
                abc[y] -=1
                ans.append(x)
            x,y=x_,y_
        if abc[x]>=abc[y]:
            ans.append(y)
        else:
            ans.append(x)
else:
    s = input()
    x,y = s[0],s[1]
    if abc[x]==0 and abc[y]==0:
        print('No')
    else:
        for _ in range(n-1):
            if abc[x]>=abc[y]:
                abc[x] -=1
                abc[y] +=1
                ans.append(y)
            else:
                abc[x] +=1
                abc[y] -=1
                ans.append(x)
            s = input()
            x,y = s[0],s[1]
        if abc[x]>=abc[y]:
            ans.append(y)
        else:
            ans.append(x)
                
if len(ans)==n:
    print('Yes')
    print('\n'.join(ans))

Submission status: Accepted

Solution code:
import sys
if sys.subversion[0] == "PyPy":
    import io, atexit
    sys.stdout = io.BytesIO()
    atexit.register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))
    
    sys.stdin = io.BytesIO(sys.stdin.read())
    input = lambda: sys.stdin.readline().rstrip()

n, a, b, c = map(int, raw_input().split())
cmds = []

def getidx(c):
    return 'ABC'.index(c)

g = [ [], [], [] ]
for i in xrange(n):
    s = raw_input()
    cmds.append(s)
    g[getidx(s[0])].append(i)
    g[getidx(s[1])].append(i)

def getnext(c, idx):
    v = g[getidx(c)]
    l, r = 0, len(v) - 1
    while l <= r:
        m = (l + r) / 2
        if v[m] <= idx:
            l = m + 1
        else:
            r = m - 1
    if l >= len(v):
        return n
    return v[l]

cnt = [a, b, c]
res = []


for i in xrange(n):
    cmd = cmds[i]
    p1 = ord(cmd[0]) - ord('A')
    p2 = ord(cmd[1]) - ord('A')

    if cnt[p1] > 1 or cnt[p2] > 1 or cnt[p1] == 0 or cnt[p2] == 0:
        if cnt[p1] > cnt[p2]:
            res.append(cmd[1])
            cnt[p1] -= 1
            cnt[p2] += 1
        else:
            res.append(cmd[0])
            cnt[p1] += 1
            cnt[p2] -= 1
        if min(cnt) < 0:
            res = []
            break
    elif i == n - 1:
        res.append(cmd[0])
        cnt[p1] += 1
        cnt[p2] -= 1
    else:
        # print cnt, p1, p2
        assert cnt[p1] == 1 and cnt[p2] == 1
        assert i + 1 < n

        nxt = cmds[i + 1]
        idx1 = getnext(cmd[0], i)
        idx2 = getnext(cmd[1], i)
        assert min(idx1, idx2) > i

        if idx1 < idx2:
            res.append(cmd[0])
            cnt[p1] += 1
            cnt[p2] -= 1
        else:
            res.append(cmd[1])
            cnt[p1] -= 1
            cnt[p2] += 1
    assert min(cnt) >= 0

if not res:
    print 'No'
else:
    print 'Yes'
    print '\n'.join(res)

Submission status: Accepted

Solution code:
n,a,b,c = map(int,input().split())
ss=['' for _ in range(n)]
ans=['' for _ in range(n)]
wa=a+b+c
for i in range(n):
    s=input()
    ss[i]=s
i=0
if wa==0:
    print('No')
    exit()
elif wa==1:
    for s in ss:
        if s=='AB':
            if c:
                print('No')
                exit()
            elif b:
                a+=1
                b-=1
                ans[i]='A'
            elif a:
                b+=1
                a-=1
                ans[i]='B'
        elif s=='AC':
            if b:
                print('No')
                exit()
            elif a:
                c+=1
                a-=1
                ans[i]='C'
            elif c:
                a+=1
                c-=1
                ans[i]='A'
        elif s=='BC':
            if a:
                print('No')
                exit()
            elif b:
                c+=1
                b-=1
                ans[i]='C'
            elif c:
                b+=1
                c-=1
                ans[i]='B'
        i+=1
elif wa==2:
    for s in ss:
        if s=='AB':
            if a==0 and b==0:
                print('No')
                exit()
            elif a==0:
                a+=1
                b-=1
                ans[i]='A'
            elif b==0:
                b+=1
                a-=1
                ans[i]='B'
            elif a==1 and b==1:
                if i==n-1:
                    ans[i]='A'
                else:
                    if ss[i+1]=='AC' or ss[i+1]=='AB':
                        a+=1
                        b-=1
                        ans[i]='A'
                    elif ss[i+1]=='BC':
                        b+=1
                        a-=1
                        ans[i]='B'
        elif s=='AC':
            if a==0 and c==0:
                print('No')
                exit()
            elif a==0:
                a+=1
                c-=1
                ans[i]='A'
            elif c==0:
                c+=1
                a-=1
                ans[i]='C'
            elif a==1 and c==1:
                if i==n-1:
                    ans[i]='A'
                else:
                    if ss[i+1]=='AC' or ss[i+1]=='AB':
                        a+=1
                        c-=1
                        ans[i]='A'
                    elif ss[i+1]=='BC':
                        c+=1
                        a-=1
                        ans[i]='C'
        elif s=='BC':
            if b==0 and c==0:
                print('No')
                exit()
            elif b==0:
                b+=1
                c-=1
                ans[i]='B'
            elif c==0:
                c+=1
                b-=1
                ans[i]='C'
            elif b==1 and c==1:
                if i==n-1:
                    ans[i]='B'
                else:
                    if ss[i+1]=='BC' or ss[i+1]=='AB':
                        b+=1
                        c-=1
                        ans[i]='B'
                    elif ss[i+1]=='AC':
                        c+=1
                        b-=1
                        ans[i]='C'
        i+=1
elif wa>2:
    for i in range(n):
        s=ss[i]
        if s=='AB':
            if a==0 and b==0:
                print('No')
                exit()
            elif a==0:
                a+=1
                b-=1
                ans[i]='A'
            elif b==0:
                b+=1
                a-=1
                ans[i]='B'
            else:
                if i==n-1:
                    ans[i]='A'
                    a+=1
                    b-=1
                else:
                    if b>=a:
                        a+=1
                        b-=1
                        ans[i]='A'
                    else:
                        b+=1
                        a-=1
                        ans[i]='B'
        elif s=='AC':
            if a==0 and c==0:
                print('No')
                exit()
            elif a==0:
                a+=1
                c-=1
                ans[i]='A'
            elif c==0:
                c+=1
                a-=1
                ans[i]='C'
            else:
                if i==n-1:
                    ans[i]='A'
                    a+=1
                    c-=1
                else:
                    if c>=a:
                        a+=1
                        c-=1
                        ans[i]='A'
                    else:
                        c+=1
                        a-=1
                        ans[i]='C'
        elif s=='BC':
            if b==0 and c==0:
                print('No')
                exit()
            elif b==0:
                b+=1
                c-=1
                ans[i]='B'
            elif c==0:
                c+=1
                b-=1
                ans[i]='C'
            else:
                if i==n-1:
                    ans[i]='B'
                    b+=1
                    c-=1
                else:
                    if c>=b:
                        b+=1
                        c-=1
                        ans[i]='B'
                    else:
                        c+=1
                        b-=1
                        ans[i]='C'
        #print(i,a,b,c)
print('Yes')
for x in ans:
    print(x)

Submission status: Accepted

Solution code:
n,*abc=map(int,input().split())
ip=[0]*n
for i in range(n):
	tmp=input()
	if tmp=="AB":
		ip[i]=[0,1]
	elif tmp=="BC":
		ip[i]=[1,2]
	else:
		ip[i]=[0,2]
ans="Yes"
res=[0]*n
s=sum(abc)
if s==0:
	ans="No"
elif s==1:
	for i in range(n):
		i1=ip[i][0]
		i2=ip[i][1]
		if abc[i1]+abc[i2]==0:
			ans="No"
		elif abc[i1]+abc[i2]==1:
			if abc[i1]==0:
				abc[i1]+=1
				abc[i2]-=1
				res[i]=i1
			else:
				abc[i1]-=1
				abc[i2]+=1
				res[i]=i2
else:
	i1=ip[0][0]
	i2=ip[0][1]
	if abc[i1]+abc[i2]==0:
		ans="No"
	else:
		for i in range(n):
			i1=ip[i][0]
			i2=ip[i][1]
			if abc[i1]*abc[i2]==0:
				if abc[i1]==0:
					abc[i1]+=1
					abc[i2]-=1
					res[i]=i1
				else:
					abc[i1]-=1
					abc[i2]+=1
					res[i]=i2
			elif i+1<n and ip[i+1]!=ip[i]:
				c=list(set(ip[i])&set(ip[i+1]))[0]
				if i1==c:
					abc[i1]+=1
					abc[i2]-=1
					res[i]=i1
				else:
					abc[i1]-=1
					abc[i2]+=1
					res[i]=i2
			else:
				if abc[i1]>=abc[i2]:
					abc[i1]+=1
					abc[i2]-=1
					res[i]=i1
				else:
					abc[i1]-=1
					abc[i2]+=1
					res[i]=i2
print(ans)
if ans=="Yes":
	for i in range(n):
		if res[i]==0:
			print("A")
		elif res[i]==1:
			print("B")
		else:
			print("C")

Submission status: Accepted

Solution code:
X = [0, 0, 0]
N, X[0], X[1], X[2] = map(int, input().split())
Q = []
for _ in range(N):
    s = input()
    if s == 'AB':
        Q.append([0, 1])
    elif s == 'AC':
        Q.append([0, 2])
    else:
        Q.append([1, 2])
ans = True
ret = ''
for i in range(N):
    a = Q[i][0]
    b = Q[i][1]
    if X[a] == X[b] == 0:
        ans = False
        break
    elif X[a] < X[b]:
        ret += chr(ord(str(a)) + 17)
        X[a] += 1
        X[b] -= 1
    elif X[a] > X[b] or i == N - 1:
        ret += chr(ord(str(b)) + 17)
        X[a] -= 1
        X[b] += 1
    else:
        s = Q[i + 1][0]
        t = Q[i + 1][1]
        if a == s or a == t:
            ret += chr(ord(str(a)) + 17)
            X[a] += 1
            X[b] -= 1
        else:
            ret += chr(ord(str(b)) + 17)
            X[a] -= 1
            X[b] += 1
    if X[a] < 0 or X[b] < 0:
        ans = False
        break
if ans:
    print('Yes')
    print('\n'.join(ret))
else:
    print('No')

Submission status: Accepted

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

N,A,B,C=input().split()
D=dict()
D["A"]=int(A)
D["B"]=int(B)
D["C"]=int(C)

S=[]
for i in range(int(N)):
    S.append(input())

ans="Yes"
F=[]
for i,s in enumerate(S):
    if D[s[0]]==0 and D[s[1]]==0:
        ans="No"
        break
    if D[s[0]]==1 and D[s[1]]==1:
        if D["A"]+D["B"]+D["C"]==2:
            if i!=int(N)-1:
                if S[i+1] != s:
                    s0=S[i+1][0]
                    s1=S[i+1][1]
                    if s[0]==s0 or s[0]==s1:
                        F.append(s[0])
                    if s[1]==s0 or s[1]==s1:
                        F.append(s[1])
    if len(F)!=i+1:
        if D[s[0]]<D[s[1]]:
            F.append(s[0])
        if D[s[0]]>D[s[1]]:
            F.append(s[1])
        if D[s[0]]==D[s[1]]:
            F.append(s[0])

    D[F[-1]]+=1
    if s[0]==F[-1]: D[s[1]]-=1
    if s[1]==F[-1]: D[s[0]]-=1
    #print(D)
    #print(F)

print(ans)
if ans=="Yes":
    for f in F:
        print(f)

Submission status: Accepted

Solution code:
n, a, b, c = list(map(int, input().split()))
ss = []
for i in range(n):
    ss.append(input())
ans = []
num_dic = {"A": a,"B": b, "C": c}

for i in range(n):
    s = ss[i]
    if num_dic[s[0]] == 0 and num_dic[s[1]] == 0:
        print("No")
        exit()
    elif num_dic[s[0]] > num_dic[s[1]]:
        num_dic[s[0]] -= 1
        num_dic[s[1]] += 1
        ans.append(s[1])
    elif num_dic[s[0]] < num_dic[s[1]]:
        num_dic[s[0]] += 1
        num_dic[s[1]] -= 1
        ans.append(s[0])
    elif i == n -1:
        ans.append(s[0])
        num_dic[s[0]] -= 1
        num_dic[s[1]] += 1
    elif s[0] in ss[i+1]:
        num_dic[s[0]] += 1
        num_dic[s[1]] -= 1
        ans.append(s[0])
    else:
        num_dic[s[0]] -= 1
        num_dic[s[1]] += 1
        ans.append(s[1])
print("Yes")
for a in ans:
    print(a)

Submission status: Accepted

Solution code:
import sys
def input() : return sys.stdin.readline().strip()

def main():
    N, A, B, C = map(int, input().split())
    s = tuple(input() for _ in range(N))
    d = {}
    d["A"] = A
    d["B"] = B
    d["C"] = C
    ans = []
    for i in range(N-1):
        l1, r1 = s[i]
        l2, r2 = s[i+1]

        if d["A"]*d["B"]*d["C"]:
            temp = [d[l1], d[r1]]
            max_val = max(temp)
            max_index = temp.index(max_val)
            
            if max_index == 0:
                ans.append(r1)
                d[l1] -= 1
                d[r1] += 1
            else:
                ans.append(l1)
                d[l1] += 1
                d[r1] -= 1
        else:
            if d[l1] * d[r1]:
                if l1 == l2 and r1 == r2:
                    ans.append(l1)
                    d[l1] += 1
                    d[r1] -= 1
                else:
                    for c in [l1, r1]:
                        if [l1, r1, l2, r2].count(c) == 1:
                            d[c] -= 1
                        else:
                            ans.append(c)
                            d[c] += 1
            else:
                temp = [d[l1], d[r1]]
                max_val = max(temp)
                max_index = temp.index(max_val)
            
                if max_index == 0:
                    ans.append(r1)
                    d[l1] -= 1
                    d[r1] += 1
                else:
                    ans.append(l1)
                    d[l1] += 1
                    d[r1] -= 1
        if any([d[c] < 0 for c in "ABC"]):
            print("No")
            exit()

    l1, r1 = s[N-1]
    temp = [d[l1], d[r1]]
    max_val = max(temp)
    max_index = temp.index(max_val)
            
    if max_index == 0:
        ans.append(r1)
        d[l1] -= 1
        d[r1] += 1
    else:
        ans.append(l1)
        d[l1] += 1
        d[r1] -= 1

    if any([d[c] < 0 for c in "ABC"]):
            print("No")
    else:
        print("Yes")
        print(*ans, sep="\n")

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N,A,B,C = map(int,input().split())
data = {
  "A":A,
  "B":B,
  "C":C
}
select = []
S = list(input() for _ in range(N))
for i in range(N):
  s = S[i]
  if data[s[0]] == data[s[1]] ==0:
    print("No")
    exit(0)
  elif data[s[0]] > data[s[1]]:
    data[s[0]] -= 1
    data[s[1]] += 1
    select.append(s[1])
  elif data[s[0]] < data[s[1]]:
    data[s[0]] += 1
    data[s[1]] -= 1
    select.append(s[0])
  elif i == N-1:
    select.append(s[0])
  elif s[0] in S[i+1]:
    data[s[0]] += 1
    data[s[1]] -= 1
    select.append(s[0])
  else:
    data[s[0]] -= 1
    data[s[1]] += 1
    select.append(s[1])
print("Yes")
for i in select:
  print(i)

Submission status: Accepted

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):
            # print(t_copy)
            com = commands[k]
            i, j = parse(com)
            if t_copy[i] == 0 and t_copy[j] == 0:
                raise RuntimeError
            # 配分後は必ず (1 以上, 1 以上, 0 以上)
            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:
                # 片方はどうしても 0 になってしまう
                if t_copy[i] == 1 and t_copy[j] == 1:
                    if k != size - 1:
                        next_com = commands[k + 1]
                        next_i, next_j = parse(next_com)
                        if not (i == next_i and j == next_j):
                            next_duplicate_one = list(set([i, j]) & set([next_i, next_j]))[0]
                            tmp = [next_i, next_j]
                            tmp.remove(next_duplicate_one)
                            next_not_duplicate = tmp[0]
                            if t_copy[next_not_duplicate] == 0:
                                result.append(s[next_duplicate_one])
                                t_copy[next_duplicate_one] += 1
                                tmp = [i, j]
                                tmp.remove(next_duplicate_one)
                                res = tmp[0]
                                t_copy[res] -= 1
                                continue    # ここを忘れてハマり続けた...
                    # 自由？
                    result.append(s[i])
                    t_copy[i] += 1
                    t_copy[j] -= 1
                # 0 にならないですむ                 
                elif t_copy[i] <= t_copy[j]:
                    result.append(s[i])
                    t_copy[i] += 1
                    t_copy[j] -= 1
                else:
                    result.append(s[j])
                    t_copy[j] += 1
                    t_copy[i] -= 1
        return result
            
    
    n, a, b, c  = mi()
    t = [a, b, c]
    commands = [input() for _ in range(n)]
    i, j = parse(commands[0])
    # (0, 0, 0)
    if sum(t) == 0:
        predicate = False
    # (1, 0, 0)
    elif sum(t) == 1:
        predicate, result = sim_1(t[:], commands)
    # (2 以上, 0, 0) で最初に沈む
    elif t.count(0) == 2 and t[i] == 0 and t[j] == 0:
        predicate = False
    # (2 以上, 0, 0) で最初に沈まない
    # (1 以上, 1 以上, 0)
    # (1 以上, 1 以上, 1 以上)
    # うまく立ち回り続ける
    else:
        predicate = True
        result = sim_2(t[:], commands)
    
    if predicate:
        print('Yes')
        print(*result, sep='\n')
    else:
        print('No')


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys

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


abc = {"A": a, "B": b, "C": c}
ans = []
for i, s in enumerate(S):
    u, v = s[0], s[1]
    if abc[u] == abc[v] == 0:
        print("No")
        sys.exit()
    elif abc[u] > abc[v]:
        abc[u] -= 1
        abc[v] += 1
        ans.append(v)
    elif abc[u] < abc[v]:
        abc[u] += 1
        abc[v] -= 1
        ans.append(u)
    elif i == n-1:
        ans.append(u)
    else:
        if u in S[i+1]:
            abc[u] += 1
            abc[v] -= 1
            ans.append(u)
        elif v in S[i+1]:
            abc[v] += 1
            abc[u] -= 1
            ans.append(v)
print("Yes")
for ans_ in ans: print(ans_)

Submission status: Accepted

Solution code:
from sys import stdin

import time
def dprint(*args):
    #print(*args)
    pass


n, a, b, c = [int(x) for x in stdin.readline().rstrip().split()]
ans = "Yes"

card = []
sentaku = []

for i in range(n):
    s = stdin.readline().rstrip()
    card.append(s)

if a+b+c == 0:
    ans = "No"

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


def judge(i, j, k):
    global ans
    dprint(n, i, j, k, ans, nums, sentaku)
    if nums[j] == 0 and nums[k] == 0:
        ans = "No"
        return

    if nums[j] == 0:
        nums[j] += 1
        nums[k] -= 1
        sentaku.append(j)
        return
    if nums[k] == 0:
        nums[k] += 1
        nums[j] -= 1
        sentaku.append(k)
        return

    total = sum(nums.values())
    if total > 2 or i == n-1:
        if nums[k] > 1:
            nums[j] += 1
            nums[k] -= 1
            sentaku.append(j)
        else:
            nums[k] += 1
            nums[j] -= 1
            sentaku.append(k)
        dprint("tekitou")
        return

    ns = card[i+1]
    if ns[0] == j or ns[1] == j:
        nums[j] += 1
        nums[k] -= 1
        sentaku.append(j)
        return
    else:
        nums[k] += 1
        nums[j] -= 1
        sentaku.append(k)
        return
    pass


for i in range(n):
    s = card[i]
    judge(i, s[0], s[1])

print(ans)

if ans == "Yes":
    for i in range(len(sentaku)):
        print(sentaku[i])

Submission status: Accepted

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

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
from collections import deque
from fractions import gcd
from functools import lru_cache


#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')

#############
# Functions #
#############

######INPUT######
def inputI(): return int(input().strip())
def inputS(): return input().strip()
def inputIL(): return list(map(int,input().split()))
def inputSL(): return list(map(str,input().split()))
def inputILs(n): return list(int(input()) for _ in range(n))
def inputSLs(n): return list(input().strip() for _ in range(n))
def inputILL(n): return [list(map(int, input().split())) for _ in range(n)]
def inputSLL(n): return [list(map(str, input().split())) for _ in range(n)]

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n):
    return kaijo_memo[n]
  if(len(kaijo_memo) == 0):
    kaijo_memo.append(1)
  while(len(kaijo_memo) <= n):
    kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n):
    return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0):
    gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n):
    gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if(n == r):
    return 1
  if(n < r or r < 0):
    return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])
    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])
    return arr

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#############
# Main Code #
#############

N,A,B,C = inputIL()
l = inputSLs(N)

if A+B+C == 0:
  print("No")
  exit()
  
n = len(l)


a = []

if A+B+C == 1:
  for item in l:
    if item == "AB":
      if A==B==0:
        print("No")
        exit()
      elif A==0:
        A += 1
        B -= 1
        a.append("A")
      else:
        A -= 1
        B += 1
        a.append("B")
    if item == "AC":
      if A==C==0:
        print("No")
        exit()
      elif A==0:
        A += 1
        C -= 1
        a.append("A")
      else:
        A -= 1
        C += 1
        a.append("C")
    if item == "BC":
      if B==C==0:
        print("No")
        exit()
      elif B==0:
        B += 1
        C -= 1
        a.append("B")
      else:
        B -= 1
        C += 1
        a.append("C")

if A+B+C >= 2:
  for i in range(n):
    item = l[i]
    if item == "AB":
      if A==B==0:
        print("No")
        exit()
      elif A==0:
        A += 1
        B -= 1
        a.append("A")
      elif B==0:
        A -= 1
        B += 1
        a.append("B")
      elif C==0 and i!=n-1:
        nitem = l[i+1]
        if nitem == "AB":
          A += 1
          B -= 1
          a.append("A")
        if nitem == "AC":
          A += 1
          B -= 1
          a.append("A")
        if nitem == "BC":
          A -= 1
          B += 1
          a.append("B")
      else:
        A += 1
        B -= 1
        a.append("A")
        
    if item == "AC":
      if A==C==0:
        print("No")
        exit()
      elif A==0:
        A += 1
        C -= 1
        a.append("A")
      elif C==0:
        A -= 1
        C += 1
        a.append("C")
      elif B==0 and i!=n-1:
        nitem = l[i+1]
        if nitem == "AC":
          A += 1
          C -= 1
          a.append("A")
        if nitem == "AB":
          A += 1
          C -= 1
          a.append("A")
        if nitem == "BC":
          A -= 1
          C += 1
          a.append("C")
      else:
        A += 1
        C -= 1
        a.append("A")

        
    if item == "BC":
      if B==C==0:
        print("No")
        exit()
      elif B==0:
        B += 1
        C -= 1
        a.append("B")
      elif C==0:
        B -= 1
        C += 1
        a.append("C")
      elif A==0 and i!=n-1:
        nitem = l[i+1]
        if nitem == "BC":
          B += 1
          C -= 1
          a.append("B")
        if nitem == "AB":
          B += 1
          C -= 1
          a.append("B")
        if nitem == "AC":
          B -= 1
          C += 1
          a.append("C")
      else:
        B += 1
        C -= 1
        a.append("B")

        
print("Yes")
for item in a:
  print(item)