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:
## coding: UTF-8

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

#s = A + B + C
num = [A, B, C]


def step():
    ans = []

    for i in range(N):
        if(ans == 'No'):
            break
        choice = S[i]
        if(i+1 == N):
            next_choice = choice
        else:
            next_choice = S[i+1]
        if(choice == 'AB'):
            if(num[0] == 0):
                #A == 0
                if(num[1] == 0):
                    ans = 'No' #どちらも0なら終わり
                else:
                    #Bだけ正の数なので
                    ans.append('A')
                    num[0] += 1
                    num[1] -= 1
            else:
                # A > 0
                if(num[0] < num[1]):
                    #Aの方が小さいならAを足す
                    ans.append('A')
                    num[0] += 1
                    num[1] -= 1
                elif(num[0] > num[1]):
                    #Bの方が小さいならBを足す
                    #B == 0の場合も含んでいます
                    ans.append('B')
                    num[0] -= 1
                    num[1] += 1
                else:
                    # A == B
                    if(next_choice == 'BC'):
                        #次がBCならBに供給
                        ans.append('B')
                        num[0] -= 1
                        num[1] += 1
                    else:
                        #次がAB,ACならAに供給
                        ans.append('A')
                        num[0] += 1
                        num[1] -= 1
        elif(choice == 'AC'):
            if(num[0] == 0):
                #A == 0
                if(num[2] == 0):
                    ans = 'No' #どちらも0なら終わり
                else:
                    #Cだけ正の数なので
                    ans.append('A')
                    num[0] += 1
                    num[2] -= 1
            else:
                # A > 0
                if(num[0] < num[2]):
                    #Aの方が小さいならAを足す
                    ans.append('A')
                    num[0] += 1
                    num[2] -= 1
                elif(num[0] > num[2]):
                    #Cの方が小さいならCを足す
                    #C == 0の場合も含んでいます
                    ans.append('C')
                    num[0] -= 1
                    num[2] += 1
                else:
                    # A == C
                    if(next_choice == 'BC'):
                        #次がBCならCに供給
                        ans.append('C')
                        num[0] -= 1
                        num[2] += 1
                    else:
                        #次がAB,ACならAに供給
                        ans.append('A')
                        num[0] += 1
                        num[2] -= 1
        else:
            #choice == 'BC'
            if(num[1] == 0):
                #B == 0
                if(num[2] == 0):
                    ans = 'No' #どちらも0なら終わり
                else:
                    #Cだけ正の数なので
                    ans.append('B')
                    num[1] += 1
                    num[2] -= 1
            else:
                #B > 0
                if(num[1] < num[2]):
                    #Bの方が小さいならBを足す
                    ans.append('B')
                    num[1] += 1
                    num[2] -= 1
                elif(num[1] > num[2]):
                    #Cの方が小さいならCを足す
                    #C == 0の場合も含んでいます
                    ans.append('C')
                    num[1] -= 1
                    num[2] += 1
                else:
                    # B == C
                    if(next_choice == 'AB'):
                        #次がABならBに供給
                        ans.append('B')
                        num[1] += 1
                        num[2] -= 1
                    else:
                        #次がAC,BCならCに供給
                        ans.append('C')
                        num[1] -= 1
                        num[2] += 1
        #print('i:{}, choice:{}, next:{}, ans.append:{}, num:{}, ans:{}'.format(i, choice, next_choice, ans[-1], num, ans))
    return ans

answer = step()
#print(type(answer))
if(type(answer) == list):
    print('Yes')
    for i in range(len(answer)):
        print(answer[i])
else:
    print('No')

Submission status: Accepted

Solution code:
from bisect import bisect_left, bisect_right

INF = float("inf")
n, *s = map(int, input().split())
toidx = {"AB": (0, 1), "BC": (1, 2), "AC": (0, 2)}
toalp = lambda x: chr(ord("A") + x)
m = sum(s)
q = [toidx[input()] for _ in range(n)]

def solve():
    res = []
    if m == 0 or (not s[q[0][0]] and not s[q[0][1]]):
        print("No")
        return
    elif m == 1:
        for i, j in q:
            if not s[i] and not s[j]:
                print("No")
                return
            elif s[i]:
                s[j] += 1; s[i] -= 1
                res.append(toalp(j))
            elif s[j]:
                s[i] += 1; s[j] -= 1
                res.append(toalp(i))
    elif m == 2:
        d = {(0, 1): [], (0, 2): [], (1, 2): []}
        for i in range(n): d[q[i]].append(i)
        for key in d.keys(): d[key].append(INF)
        for idx, (i, j) in enumerate(q):
            if s[i] and s[j]:
                k = [x for x in range(3) if i != x and j != x][0]
                key1 = tuple(sorted([i, k]))
                key2 = tuple(sorted([j, k]))
                nik = d[key1][bisect_left(d[key1], idx)]
                njk = d[key2][bisect_left(d[key2], idx)]
                if nik <= njk:
                    s[i] += 1; s[j] -= 1
                    res.append(toalp(i))
                else: 
                    s[j] += 1; s[i] -= 1
                    res.append(toalp(j))
            elif s[i]:
                s[j] += 1; s[i] -= 1
                res.append(toalp(j))
            elif s[j]:
                s[i] += 1; s[j] -= 1
                res.append(toalp(i))
    else:
        for i, j in q:
            if s[i] >= s[j]:
                s[j] += 1; s[i] -= 1
                res.append(toalp(j))
            else:
                s[i] += 1; s[j] -= 1
                res.append(toalp(i))
    print("Yes")
    print(*res, sep="\n")

solve()

Submission status: Accepted

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

n, a, b, c = map(int, input().split())
s = []
ans = []
for i in range(n):
    s.append(input().rstrip("\n"))
def check(x, y):
    if x + y == 0:
        print("No")
        sys.exit()

for i, si in enumerate(s):
    if si == "AB":
        check(a, b)
        if a == 1 and b == 1 and i < n - 1:
            if s[i+1] == "BC":
                ans.append('B')
                a -= 1
                b += 1
                continue
            if s[i+1] == "AC":
                ans.append('A')
                b -= 1
                a += 1
                continue
        if a > b:
            ans.append('B')
            a -= 1
            b += 1
        else:
            ans.append('A')
            b -= 1
            a += 1
    if si == "AC":
        check(a, c)
        if a == 1 and c == 1 and i < n - 1:
            if s[i+1] == "BC":
                ans.append('C') 
                a -= 1
                c += 1
                continue
            if s[i+1] == "AB":
                ans.append('A')
                c -= 1
                a += 1
                continue
        if a > c:
            ans.append('C')
            a -= 1
            c += 1
        else:
            ans.append('A')
            c -= 1
            a += 1
    if si == "BC":
        check(b, c)
        if b == 1 and c == 1 and i < n - 1:
            if s[i+1] == "AB":
                ans.append('B') 
                c -= 1
                b += 1
                continue
            if s[i+1] == "AC":
                ans.append('C')
                b -= 1
                c += 1
                continue
        if b > c:
            ans.append('C')
            b -= 1
            c += 1
        else:
            ans.append('B')
            c -= 1
            b += 1
print("Yes")
for item in ans:
    print(item)

Submission status: Accepted

Solution code:
import sys
from collections import deque

def main():
    N, A, B, C = map(int, input().split())
    s_list = [input() for i in range(N)]

    select_list = deque()
    select_list.append('Yes')
    for i, i_s in enumerate(s_list):
        if i_s == 'AB':
            if A == 0 and B == 0:
                select_list = ['No']
                break
            elif A == 1 and B == 1:
                if i+1 >= N:
                    A -= 1
                    B += 1
                    select_list.append('B')
                    continue
                if s_list[i+1] == 'AC':
                    A += 1
                    B -= 1
                    select_list.append('A')
                else:
                    A -= 1
                    B += 1
                    select_list.append('B')
            elif A > B:
                A -= 1
                B += 1
                select_list.append('B')
            else:
                A += 1
                B -= 1
                select_list.append('A')
        elif i_s == 'AC':
            if A == 0 and C == 0:
                select_list = ['No']
                break
            elif A == 1 and C == 1:
                if i+1 >= N:
                    A -= 1
                    C += 1
                    select_list.append('C')
                    continue
                if s_list[i+1] == 'AB':
                    A += 1
                    C -= 1
                    select_list.append('A')
                else:
                    A -= 1
                    C += 1
                    select_list.append('C')
            elif A > C:
                A -= 1
                C += 1
                select_list.append('C')
            else:
                A += 1
                C -= 1
                select_list.append('A')
        else:
            if B == 0 and C == 0:
                select_list = ['No']
                break
            elif B == 1 and C == 1:
                if i+1 >= N:
                    B -= 1
                    C += 1
                    select_list.append('C')
                    continue
                if s_list[i+1] == 'AB':
                    B += 1
                    C -= 1
                    select_list.append('B')
                else:
                    B -= 1
                    C += 1
                    select_list.append('C')
            elif B > C:
                B -= 1
                C += 1
                select_list.append('C')
            else:
                B += 1
                C -= 1
                select_list.append('B')

    for i in select_list:
        print(i)

    return

if __name__ == '__main__':
    main()
    sys.exit(0)

Submission status: Accepted

Solution code:
n,a,b,c=map(int,input().split())
s=[input() for _ in range(n)]
if a+b+c==0:
	print("No")
elif a+b+c==1:
	ans=[]
	for x in s:
		if x=="AB":
			if a==b==0:
				print("No")
				exit()
			elif a==0:
				a+=1
				b-=1
				ans.append("A")
			else:
				b+=1
				a-=1
				ans.append("B")
		elif x=="BC":
			if b==c==0:
				print("No")
				exit()
			elif b==0:
				b+=1
				c-=1
				ans.append("B")
			else:
				c+=1
				b-=1
				ans.append("C")
		else:
			if c==a==0:
				print("No")
				exit()
			elif c==0:
				c+=1
				a-=1
				ans.append("C")
			else:
				a+=1
				c-=1
				ans.append("A")
	print("Yes")
	for x in ans:
		print(x)
else:
	ans=[]
	if s[0]=="AB":
		if a==b==0:
			print("No")
			exit()
		else:
			print("Yes")
	elif s[0]=="BC":
		if b==c==0:
			print("No")
			exit()
		else:
			print("Yes")
	else:
		if c==a==0:
			print("No")
			exit()
		else:
			print("Yes")
	s.append("AB")
	for i in range(len(s)-1):
		x=s[i]
		if x=="AB":
			if a<b:
				a+=1
				b-=1
				ans.append("A")
			elif a>b:
				b+=1
				a-=1
				ans.append("B")
			else:
				if "A" not in s[i+1]:
					b+=1
					a-=1
					ans.append("B")
				else:
					a+=1
					b-=1
					ans.append("A")
		elif x=="BC":
			if b<c:
				b+=1
				c-=1
				ans.append("B")
			elif b>c:
				c+=1
				b-=1
				ans.append("C")
			else:
				if "B" not in s[i+1]:
					c+=1
					b-=1
					ans.append("C")
				else:
					b+=1
					c-=1
					ans.append("B")
		else:
			if c<a:
				c+=1
				a-=1
				ans.append("C")
			elif c>a:
				a+=1
				c-=1
				ans.append("A")
			else:
				if "C" not in s[i+1]:
					a+=1
					c-=1
					ans.append("A")
				else:
					c+=1
					a-=1
					ans.append("C")
	for x in ans:
		print(x)

Submission status: Accepted

Solution code:
import dataclasses
n, a, b, c = list(map(int, input().split(" ")))
m = {"A": a, "B": b, "C": c}
h = ""
if sum(m.values()) == 0:
    print("No")
elif sum(m.values()) == 1:
    for i in range(n):
        x, y = input()
        if m[x] == 0 and m[y] == 0:
            print("No")
            break
        elif m[x] == 0:
            m[x] += 1
            m[y] -= 1
            h += x
        else:
            m[x] -= 1
            m[y] += 1
            h += y
    else:
        print("Yes")
        [print(i) for i in h]
else:
    inp = input()
    x, y = inp
    if m[x] == 0 and m[y] == 0:
        print("No")
    else:
        for i in range(n-1):
            next_inp = input()
            x, y = inp
            if m[x] == 0:
                m[x] += 1
                m[y] -= 1
                h += x
            elif m[y] == 0:
                m[x] -= 1
                m[y] += 1
                h += y
            elif m[x] == 1 and m[y] == 1:
                if x in next_inp:
                    m[x] += 1
                    m[y] -= 1
                    h += x
                else:
                    m[x] -= 1
                    m[y] += 1
                    h += y
            else:
                if m[x] < m[y]:
                    m[x] += 1
                    m[y] -= 1
                    h += x
                else:
                    m[x] -= 1
                    m[y] += 1
                    h += y
            inp = next_inp
        x, y = inp
        h += x if m[x] == 0 else y
        print("Yes")
        [print(i) for i in h]

Submission status: Accepted

Solution code:
import sys


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

s = [input().rstrip('\n') for _ in range(N)]
sum_num = sum(list([A, B, C]))
to_char = ["A","B","C"]

target = []
for i in range(N):
    if s[i] == "AB":
        target.append([0,1])
    elif s[i] == "BC":
        target.append([1,2])
    else:
        target.append([0,2])
if sum_num == 0:
    print("No")
    sys.exit()
elif sum_num == 1:
    answer = []
    for i in range(N):
        if stock[target[i][0]] == 1:
            stock[target[i][0]] -= 1
            stock[target[i][1]] += 1
            answer.append(target[i][1])
        elif stock[target[i][1]] == 1:
            stock[target[i][1]] -= 1
            stock[target[i][0]] += 1
            answer.append(target[i][0])
        else :
            print("No")
            sys.exit()
    print("Yes")
    for i in range(N):
        print(to_char[answer[i]])
elif sum_num >= 2:
    if stock[target[0][0]] == 0 and stock[target[0][1]] == 0:
        print("No")
        sys.exit()
    else:
        print("Yes")
        for i in range(N-1):
            if target[i][0] in target[i+1] and stock[target[i][1]] >= 1:
                stock[target[i][0]] += 1
                stock[target[i][1]] -= 1
                print(to_char[target[i][0]])
            elif stock[target[i][0]] >= 1:
                stock[target[i][1]] += 1
                stock[target[i][0]] -= 1
                print(to_char[target[i][1]])
            else:
                stock[target[i][0]] += 1
                stock[target[i][1]] -= 1
                print(to_char[target[i][0]])
        if stock[target[-1][0]] == 0:
            print(to_char[target[-1][0]])
        else:
            print(to_char[target[-1][1]])

Submission status: Accepted

Solution code:
import sys
N,A,B,C = map(int,input().split())
S = [input() for _ in range(N)]
s = S[0]
if (s == 'AB' and A+B == 0) or (s=='AC' and A+C==0) or (s=='BC' and B+C==0):
  print('No')
  sys.exit()

if A+B+C == 1:
  answer = ['Yes']
  for s in S:
    if (s == 'AB' and A+B == 0) or (s=='AC' and A+C==0) or (s=='BC' and B+C==0):
      print('No')
      sys.exit()
    if 'A' in s:
      if A == 0:
        A+=1
        answer.append('A')
      else:
        A-=1
    if 'B' in s:
      if B == 0:
        B+=1
        answer.append('B')
      else:
        B-=1
    if 'C' in s:
      if C == 0:
        C+=1
        answer.append('C')
      else:
        C-=1
  print('\n'.join(answer))
  sys.exit()

#A+B+C>=2のとき
answer = ['Yes']
for i in range(len(S)):
  s = S[i]
  lastlen = len(answer)
  if 'A' in s and A == 0:
    A+=1
    answer.append('A')
  elif 'B' in s and B == 0:
    B+=1
    answer.append('B')
  elif 'C' in s and C==0:
    C+=1
    answer.append('C')
  if lastlen < len(answer):
    ac = answer[-1]
    if 'A' in s and ac != 'A':
      A-=1
    elif 'B' in s and ac != 'B':
      B-=1
    elif 'C' in s and ac != 'C':
      C-=1
    continue
  
  if i == len(S)-1:
    if 'A' in s: answer.append('A')
    elif 'B' in s: answer.append('B')
    continue
  
  s1 = S[i+1]
  if s != s1:
    if 'A' in s and 'A' in s1:
      answer.append('A')
      A+=1
    elif 'B' in s and 'B' in s1:
      answer.append('B')
      B+=1
    elif 'C' in s and 'C' in s1:
      answer.append('C')
      C+=1
    
    if 'A' in s and answer[-1] != 'A':
      A-=1
    elif 'B' in s and answer[-1] != 'B':
      B-=1
    elif 'C' in s and answer[-1] != 'C':
      C-=1
    continue
  if s == 'AB':
    A,B=A+1,B-1
    answer.append('A')
  elif s =='AC':
    A,C=A+1,C-1
    answer.append('A')
  else:
    B,C=B+1,C-1
    answer.append('B')
print('\n'.join(answer))

Submission status: Accepted

Solution code:

def NextEnforcement(enfo1,enfo2):
    if(enfo1 == "AB") and (enfo2 == "AC"):
        return "1"
    elif (enfo1 == "AB") and (enfo2 == "BC"):
        return "2"
    elif (enfo1 == "BC") and (enfo2 == "AC"):
        return "2"
    elif (enfo1 == "BC") and (enfo2 == "AB"):
        return "1"
    elif (enfo1 == "AC") and (enfo2 == "AB"):
        return "1"
    elif (enfo1 == "AC") and (enfo2 == "BC"):
        return "2"
    else:
        return "0"


def Calculation(num1,num2,nextInfo):
    if num1 == num2 == 0:
        print("No")
        exit()
    elif num1 == 0:
        num1 += 1
        num2 -= 1
    elif num2 == 0:
        num1 -= 1
        num2 += 1
    elif nextInfo == "0":
        if num1 > num2:
            num1 -= 1
            num2 += 1
        elif num1 <= num2:
            num1 += 1
            num2 -= 1
    elif nextInfo == "1":
        num1 += 1
        num2 -= 1
    elif nextInfo == "2":
        num1 -= 1
        num2 += 1

    return num1,num2


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

enforcement = ["NULL"]*n

for i in range(n):
    enforcement[i] = input()

ans = ["NULL"]*n

for i in range(n):
    tmpA = a
    tmpB = b
    tmpC = c
    if i != n-1:
        nextInfo = NextEnforcement(enforcement[i], enforcement[i + 1])
    else:
        nextInfo = "0"

    if enforcement[i] == "AC":
        a,c = Calculation(a,c,nextInfo)
        if tmpA < a :
            ans[i] = "A"
        else:
            ans[i] = "C"
    if enforcement[i] == "AB":
        a,b = Calculation(a,b,nextInfo)
        if tmpA < a :
            ans[i] = "A"
        else:
            ans[i] = "B"
    if enforcement[i] == "BC":
        b,c = Calculation(b,c,nextInfo)
        if tmpB < b :
            ans[i] = "B"
        else:
            ans[i] = "C"

print("Yes")

for i in range(n):
    print(ans[i])

Submission status: Accepted

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

d = {'A': 0, 'B': 0, 'C': 0}
ans = []
S = []

def distribute(s):
    if d[s[0]] < d[s[1]]:
        d[s[0]] += 1
        d[s[1]] -= 1
        ans.append(s[0])
    else:
        d[s[0]] -= 1
        d[s[1]] += 1
        ans.append(s[1])

def main():
    N, A, B, C = map(int, input().split())
    summation = A + B + C
    d['A'], d['B'], d['C'] = A, B, C

    """
    最低3個は実験しないといけんですわ。。。
    まずA+B+Cが不変量なことに気づく（これはよし）
    そしたらA+B+C=0,1,2の場合に実験してみる。
    和が0の場合は明らかにアウト。和が1の場合は実際にN回通してみれば良い。

    和が2の場合は（これを試さなかったのが敗因！！！！！！）
        (A, B, C) = (2, 0, 0) or (1, 1, 0)
    の２パターン（ただし順不問）があるが、前者はBCの指示がきたらアウト。
    それ以外は後者に変化する。
    一方後者の場合はBC, CAの指示では変化なし、ABの指示で前者になる。
    このとき次の一手でドボンしないようにABのどちらを2にするか考えれば、
    再び後者に戻ってくる。

    つまり後者の安定型に初手でなれれば勝ち。このロジックはN>=3でも通じる。
    """

    if summation == 0:
        print("No")
        return

    if summation == 1:
        for _ in range(N):
            s = input()
            distribute(s)
            if d['A'] < 0 or d['B'] < 0 or d['C'] < 0:
                print("No")
                return
        print("Yes")
        for s in ans: print(s)

    if summation >= 2:
        for _ in range(N): S.append(input())
        S.append("AB") # sentry
        if d[S[0][0]] == 0 and d[S[0][1]] == 0:
            print("No")
            return
        print("Yes")

        for i in range(N):
            if d[S[i][0]] > 1 or d[S[i][1]] > 1:
                distribute(S[i])
            elif d[S[i][0]] == 0 or d[S[i][1]] == 0:
                distribute(S[i])
            else: # both are 1
                char_list = [S[i][0], S[i][1], S[i + 1][0], S[i + 1][1]]
                if S[i] == S[i + 1]:
                    distribute(S[i])
                elif char_list.count('A') == 2:
                    d['A'] += 1
                    d[S[i][1]] -= 1
                    ans.append('A')
                elif char_list.count('C') == 2:
                    d['C'] += 1
                    d[S[i][0]] -= 1
                    ans.append('C')
                else:
                    d['B'] += 1
                    if S[i] == "AB":
                        d['A'] -= 1
                    else:
                        d['C'] -= 1
                    ans.append('B')

        for s in ans: print(s)






if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
n,a,b,c=map(int,input().split())
def d(x):
	if x=="AB":
		return 0
	elif x=="BC":
		return 1
	else:
		return 2
L=[d(input().rsplit()[0]) for _ in range(n)]
ABC=[a,b,c]
ans=[]
w="ABC"
append=ans.append
sha={1:1,3:2,2:0}
for i,x in enumerate(L):
	y=(x+1)%3
	if ABC[x]==ABC[y]==0:
		print("No")
		exit()
	elif ABC[x]==ABC[y]:
		if i<n-1:
			xx=L[i+1]
			if x==xx:
				append(w[x])
				ABC[x]+=1
				ABC[y]-=1
			else:
				ss=sha[x^xx]
				if x==ss:
					append(w[x])
					ABC[x]+=1
					ABC[y]-=1
				else:
					append(w[y])
					ABC[x]-=1
					ABC[y]+=1
		else:
			append(w[x])
	else:
		if ABC[x]>ABC[y]:
			x,y=y,x
		append(w[x])
		ABC[x]+=1
		ABC[y]-=1
print("Yes")
print("\n".join(ans))

Submission status: Accepted

Solution code:
#coding:utf-8

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

solve = []
p = A+B+C
s = str(input())

for i in range(N):

    if p == 0:
        print('No')
        break

    if i != N-1:
        nex = str(input())
    elif i == N-1:
        nex = s

    if p == 2 and nex != s:
        if A == 1 and B == 1 and C == 0 and s == 'AB':
            if nex == 'BC':
                B += 1
                A -= 1
                solve.append('B')
            elif nex == 'AC':
                A += 1
                B -= 1
                solve.append('A')
            s = nex
            continue
        elif A == 0 and B == 1 and C == 1 and s == 'BC':
            if nex == 'AB':
                B += 1
                C -= 1
                solve.append('B')
            elif nex == 'AC':
                C += 1
                B -= 1
                solve.append('C')
            s = nex
            continue
        elif A == 1 and B == 0 and C == 1 and s == 'AC':
            if nex == 'BC':
                C += 1
                A -= 1
                solve.append('C')
            elif nex == 'AB':
                A += 1
                C -= 1
                solve.append('A')
            s = nex
            continue
    
    if s == 'AB':
        if A == 0 and B == 0:
            print('No')
            break
        if A >= B:
            A -= 1
            B += 1
            solve.append('B')
        else:
            A += 1
            B -= 1
            solve.append('A')
    elif s == 'BC':
        if B == 0 and C == 0:
            print('No')
            break
        if B >= C:
            B -= 1
            C += 1
            solve.append('C')
        else:
            B += 1
            C -= 1
            solve.append('B')
    elif s == 'AC':
        if C == 0 and A == 0:
            print('No')
            break
        if C >= A:
            C -= 1
            A += 1
            solve.append('A')
        else:
            C += 1
            A -= 1
            solve.append('C')

    s = nex
            
    if i == N-1:
        print('Yes')
        for t in solve:
            print(t)

Submission status: Accepted

Solution code:
# F - Three Variables Game

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

def decode(c):
    return ord(c) - ord('A')

state = [a, b, c]
choice = []
for i in range(n):
    # 'AC' -> (0, 2)
    j, k = map(decode, s[i])

    # 失敗
    if state[j] == state[k] == 0:
        print('No')
        exit()

    # state[j] <= state[k] にする
    if state[j] > state[k]:
        j, k = k, j

    # 1手先読み
    if state[j] == state[k] == 1 and i < n - 1:
        xj, xk = map(decode, s[i + 1])
        if state[xj] + state[xk] == 1 and k in {xj, xk}:
            j, k = k, j

    # jを選択
    state[j] += 1
    state[k] -= 1
    choice.append('ABC'[j])

print('Yes')
for c in choice:
    print(c)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1000000)

input = sys.stdin.readline
N, A, B, C = map(int, input().split())
S = [input().strip("\n") for _ in range(N)]
Ans = ["Yes"]
Sn = {"A": 0, "B": 0, "C": 0}

def dfs(i, a, b, c):
    if i == N:
        if min([a, b, c]) >= 0: return True
        else: return False
    if min([a, b, c]) < 0: return False
    
    f, s = S[i][0], S[i][1]
    Ans.append(f)
    if f == "A":
        if s == "B":
            if dfs(i + 1, a + 1, b - 1, c): return True
            else: Ans.pop()

        else:
            if dfs(i + 1, a + 1, b, c - 1): return True
            else: Ans.pop()

    elif f == "B":
        if dfs(i + 1, a, b + 1, c - 1): return True
        else: Ans.pop()

    Ans.append(s)
    if f == "A":
        if s == "B":
            if dfs(i + 1, a - 1, b + 1, c): return True
            else: Ans.pop()

        else:
            if dfs(i + 1, a - 1, b, c + 1): return True
            else: Ans.pop()

    elif f == "B":
        if dfs(i + 1, a, b - 1, c + 1): return True
        else: Ans.pop()

    return False

def solve():
    if dfs(0, A, B, C): print("\n".join(map(str, Ans)))
    else: print("No")

    return 0

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
n,a,b,c = map(int,input().split())
ans = []
S = []
for i in range(n):S.append(input())
for i in range(n):
    s = S[i]
    id = (i+1)%n
    if s=="AB":
        if a>b:
            a-=1
            b+=1
            ans.append("B")
        elif a<b:
            a+=1
            b-=1
            ans.append("A")
        elif a==b:
            if S[id] =="AC":
                a+=1
                b-=1
                ans.append("A")
            else:
                a-=1
                b+=1
                ans.append("B")

    if s=="AC":
        if a>c:
            a-=1
            c+=1
            ans.append("C")
        elif a<c:
            a+=1
            c-=1
            ans.append("A")
        elif a==c:
            if S[id] =="AB":
                a+=1
                c-=1
                ans.append("A")
            else:
                a-=1
                c+=1
                ans.append("C")

    if s=="BC":
        if b>c:
            b-=1
            c+=1
            ans.append("C")
        elif b<c:
            b+=1
            c-=1
            ans.append("B")
        elif b==c:
            if S[id] =="AC":
                c+=1
                b-=1
                ans.append("C")
            else:
                c-=1
                b+=1
                ans.append("B")

    if b<0 or c<0 or a<0:
        print("No")
        exit()
print("Yes")
for an in ans:print(an)

Submission status: Accepted

Solution code:
N,A,B,C=map(int,input().split())
S=['']*(N+1)
for a in range(N):
    S[a]=input()

ans='Yes'
L_ans=['']*(N+1)
i=0
while i<N:
    if S[i]=='AB':
        if A>B:
            B+=1
            A-=1
            L_ans[i]='B'
        elif A<B:
            A+=1
            B-=1
            L_ans[i]='A'
        elif A==B and S[i+1]=='BC':
            B+=1
            A-=1
            L_ans[i]='B'
        else:
            A+=1
            B-=1
            L_ans[i]='A'
    elif S[i]=='AC':
        if A>C:
            C+=1
            A-=1
            L_ans[i]='C'
        elif A<C:
            A+=1
            C-=1
            L_ans[i]='A'
        elif A==C and S[i+1]=='BC':
            C+=1
            A-=1
            L_ans[i]='C'
        else:
            A+=1
            C-=1
            L_ans[i]='A'
    elif S[i]=='BC':
        if C>B:
            B+=1
            C-=1
            L_ans[i]='B'
        elif C<B:
            C+=1
            B-=1
            L_ans[i]='C'
        elif B==C and S[i+1]=='AB':
            B+=1
            C-=1
            L_ans[i]='B'
        else:
            C+=1
            B-=1
            L_ans[i]='C'
    i+=1
    if any([A<0,B<0,C<0]):
        ans='No'
        break

print(ans)
if ans=='Yes':
    j=0
    while j<N:
        print(L_ans[j])
        j+=1