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: Runtime Error

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

def main():
    N,A,B,C=map(int,input().split())
    n=[A,B,C]
    d={'AB':0,'BC':1,'AC':2}
    c=[deque() for _ in range(3)]
    ans=[-1]*N
    sousa=[]
    for i in range(N):
        s=input()
        sousa.append(d[s])
        if n[d[s]]==0 and n[(d[s]+1)%3]==0:
            print('No')
            exit()
        elif n[d[s]]==0:
            ans[i]=d[s]
            n[d[s]]+=1
            n[(d[s]+1)%3]-=1
        elif n[(d[s]+1)%3]==0:
            ans[i]=(d[s]+1)%3
            n[d[s]]-=1
            n[(d[s]+1)%3]+=1
        else:
            c[d[s]].append(i)
        if len(c[d[s]])>=2:
            if n[(d[s]+2)%3]>=1:
                if n[d[s]]>=1:
                    k=c[d[s]].popleft()
                    ans[k]=(d[s]+1)%3
                    k=c[d[s]].popleft()
                    ans[k]=d[s]%3
                else:
                    k=c[d[s]].popleft()
                    ans[k]=d[s]%3
                    k=c[d[s]].popleft()
                    ans[k]=(d[s]+1)%3
        if len(c[0])>=1 and len(c[1])>=1 and len(c[2])>=1:
            for j in range(3):
                if n[j]>=1:
                    start=j
                    break
            for j in range(start,3+start):
                j%=3
                k=c[j].popleft()
                ans[k]=(j+1)%3
    n=[A,B,C]
    print('Yes')
    d2=['A','B','C']
    raise Exception
    for x,y in zip(ans,sousa):
        if x!=-1:
            n[x]+=1
            if x==y:
                n[(x+1)%3]-=1
            else:
                n[(x+2)%3]-=1
            print(d2[x])
        else:
            if n[y]>=n[(y+1)%3]:
                n[y]-=1
                n[(y+1)%3]+=1
                print(d2[(y+1)%3])
            elif n[(y+1)%3]>=1:
                n[y]+=1
                n[(y+1)%3]-=1
                print(d2[y])
            else:
                raise Exception
                
                    

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys, bisect, math, itertools, string, queue, copy
# import numpy as np
# import scipy
from collections import Counter,defaultdict,deque
from itertools import permutations, combinations
from heapq import heappop, heappush
from fractions import gcd
# input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(input())
def inpm(): return map(int,input().split())
def inpl(): return list(map(int, input().split()))
def inpls(): return list(input().split())
def inplm(n): return list(int(input()) for _ in range(n))
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return [list(map(int, input().split())) for _ in range(n)]
def inplls(n): return sorted([list(map(int, input().split())) for _ in range(n)])

def main():
    n,a,b,c = inpm()
    aa = copy.copy(a)
    bb = copy.copy(b)
    cc = copy.copy(c)
    ans = ['p' for _ in range(n)]
    AB = deque()
    AC = deque()
    BC = deque()
    S = []
    for i in range(n):
        s = input()
        S.append(s)
        if s == 'AB':
            if a <= 0 and b <= 0:
                if AC and BC:
                    j = AC.popleft()
                    ans[j] = 'A'
                    k = BC.popleft()
                    ans[k] = 'B'
                else:
                    a -= 1
                    b -= 1
                    AB.append(i)
            else:
                a -= 1
                b -= 1
                AB.append(i)
        if s == 'AC':
            if a <= 0 and c <= 0:
                if AB and BC:
                    j = AB.popleft()
                    ans[j] = 'A'
                    k = BC.popleft()
                    ans[k] = 'C'
                else:
                    a -= 1
                    c -= 1
                    AC.append(i)
            else:
                a -= 1
                c -= 1
                AC.append(i)
        if s == 'BC':
            if c <= 0 and b <= 0:
                if AB and AC:
                    j = AB.popleft()
                    ans[j] = 'B'
                    k = AC.popleft()
                    ans[k] = 'C'
                else:
                    c -= 1
                    b -= 1
                    BC.append(i)
            else:
                c -= 1
                b -= 1
                BC.append(i)

    if a >= 0 and b >= 0 and c < 0:
        if c + len(AC) + len(BC) < 0:
            print('No')
            return
        while AC:
            i = AC.popleft()
            ans[i] = 'C'
        while BC:
            i = BC.popleft()
            ans[i] = 'C'
        while AB:
            i = AB.popleft()
            ans[i] = 'A'
    if a >= 0 and b < 0 and c >= 0:
        if b + len(AB) + len(BC) < 0:
            print('No')
            return
        while AB:
            i = AB.popleft()
            ans[i] = 'B'
        while BC:
            i = BC.popleft()
            ans[i] = 'B'
        while AC:
            i = AC.popleft()
            ans[i] = 'A'
    if a < 0 and b >= 0 and c >= 0:
        if c + len(AC) + len(BC) < 0:
            print('No')
            return
        while AC:
            i = AC.popleft()
            ans[i] = 'A'
        while BC:
            i = BC.popleft()
            ans[i] = 'A'
        while AB:
            i = AB.popleft()
            ans[i] = 'C'

    if a < 0 and b >= 0 and c < 0:
        while BC:
            i = BC.popleft()
            ans[i] = 'C'
            c += 1
        while AB:
            i = AB.popleft()
            ans[i] = 'A'
            a += 1
        while AC:
            while c < 0:
                if not AC:
                    break
                i = AC.popleft()
                ans[i] = 'C'
                c += 1
            while a < 0:
                if not AC:
                    break
                i = AC.popleft()
                ans[i] = 'A'
                a += 1
            i = AC.popleft()
            ans[i] = 'A'
    if a >= 0 and b < 0 and c < 0:
        while AC:
            i = AC.popleft()
            ans[i] = 'C'
            c += 1
        while AB:
            i = AB.popleft()
            ans[i] = 'B'
            b += 1
        while BC:
            while c < 0:
                if not BC:
                    break
                i = BC.popleft()
                ans[i] = 'C'
                c += 1
            while b < 0:
                if not BC:
                    break
                i = BC.popleft()
                ans[i] = 'B'
                b += 1
            i = BC.popleft()
            ans[i] = 'B'
            

    if a < 0 and b < 0 and c >= 0:
        while BC:
            i = BC.popleft()
            ans[i] = 'B'
            b += 1
        while AC:
            i = AC.popleft()
            ans[i] = 'A'
            a += 1
        while AB:
            while b < 0:
                if not AB:
                    break
                i = AB.popleft()
                ans[i] = 'B'
                b += 1
            while a < 0:
                if not AC:
                    break
                i = AC.popleft()
                ans[i] = 'A'
                a += 1
            i = AB.popleft()
            ans[i] = 'A'

    if a >= 0 and b >= 0 and c >= 0:
        while AC:
            i = AC.popleft()
            ans[i] = 'A'
            a += 1
        while AB:
            i = AB.popleft()
            ans[i] = 'A'
            a += 1
        while BC:
            i = BC.popleft()
            ans[i] = 'C'
            a += 1

    for i in range(n):
        t = S[i]
        if t == 'AC':
            if ans[i] == 'A':
                aa += 1
                cc -= 1
            else:
                aa -= 1
                cc += 1
        if t == 'BC':
            if ans[i] == 'B':
                bb += 1
                cc -= 1
            else:
                bb -= 1
                cc += 1
        if t == 'AB':
            if ans[i] == 'A':
                aa += 1
                bb -= 1
            else:
                aa -= 1
                bb += 1
        if aa<0 or bb<0 or cc<0:
            print('No')
            return


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

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
s = [0,0,0]
n,s[0],s[1],s[2] = map(int,input().split())
T = [0]*n
ABC = 'ABC'
for i in range(n):
    t = input()
    if t == 'AB':T[i] = 2
    if t == 'BC':T[i] = 0
    if t == 'AC':T[i] = 1
ans = ['' for _ in range(n)]
# if s.count(0) <= 1 and sum(s) >= 3:
#     for i,t in enumerate(T):
#         nxt = [0,1,2]
#         nxt.remove(t)
#         if s[nxt[0]] < s[nxt[1]]:
#             ans[i] = ABC[nxt[0]]
#             s[nxt[0]] += 1
#             s[nxt[1]] -= 1
#         else:
#             ans[i] = ABC[nxt[1]]
#             s[nxt[0]] -= 1
#             s[nxt[1]] += 1
#     print('Yes')
#     print('\n'.join(ans))
if s.count(0) == 1 and s.count(1) == 2:
    s[3] = 0
    now = s.index(0)
    i = 0
    while i < n-1:
        if T[i] == T[i+1]:
            if T[i] == now:
                ans[i] = ABC[(now-1)%3]
                ans[i+1] = ABC[(now-2)%3]
            else:
                for j in range(3):
                    if j not in [T[i],now]:
                        ans[i+1] = ABC[j]
                ans[i] = ABC[now]
            i += 2
        elif T[i] == now:
            for j in range(3):
                if j not in [T[i+1],now]:ans[i] = ABC[j]
            ans[i+1] = ABC[T[i]]
            now = T[i+1]
            i += 2
        else:
            ans[i] = ABC[now]
            for j in range(3):
                if j not in [T[i],now]:
                    now = j
                    break
            i += 1
    if i == n-1:
        if T[i] == now:
            for j in range(3):
                if j not in [now,T[i]]:ans[i] = ABC[j]
        else:
            ans[i] = ABC[now]
    print('Yes')
    print('\n'.join(ans))
else:
    for i,t in enumerate(T):
        nxt = [0,1,2]
        nxt.remove(t)
        if s[nxt[0]] < s[nxt[1]]:
            ans[i] = ABC[nxt[0]]
            s[nxt[0]] += 1
            s[nxt[1]] -= 1
        else:
            ans[i] = ABC[nxt[1]]
            s[nxt[0]] -= 1
            s[nxt[1]] += 1
        if -1 in s:
            print('No')
            break
    else:
        print('Yes')
        print('\n'.join(ans))

Submission status: Runtime Error

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

DP = [[0] * 3 for _ in range(N + 1)]
DP[0] = [A, B, C]

L = [""] * N
R = {}
R[0] = "A"
R[1] = "B"
R[2] = "C"
A = []
B = []
for i in range(N):
  t = s[i]
  if t == "AB":
    x = 0
    y = 1
  if t == "BC":
    x = 1
    y = 2
  if t == "AC":
    x = 0
    y = 2
  if DP[i][y] != 0:
    DP[i + 1] = DP[i]
    DP[i + 1][x] += 1
    DP[i + 1][y] -= 1
    L[i] = R[x]
    if x == 0:
      A.append([i, y])
    else:
      B.append([i, y])
  elif DP[i][x] != 0:
    DP[i + 1] = DP[i]
    DP[i + 1][x] -= 1
    DP[i + 1][y] += 1
    L[i] = R[y]
  else:
    if x == 0:
      if len(B) == 0:
        print("No")
        exit()
      z = 1
      k, n = pop(B)
    if x == 1:
      if len(A) == 0:
        print("No")
        exit()
      z = 0
      k, n = pop(A)
    DP[i + 1] = DP[i]
    DP[i + 1][z] -= 2
    DP[i + 1][n] += 2
    if n == x:
      x, y = y, x
    DP[i + 1][x] += 1
    DP[i + 1][y] -= 1
    if DP[i + 1][z] < 0:
      print("No")
      exit()
    L[i] = R[x]
    L[t] = R[y]


print("Yes")
for i in L:
  print(i)

Submission status: Runtime Error

Solution code:
N, A, B, C = map(int, input().split())
v = [A, B, C]
id_d = {'A':0, 'B':1, 'C':2}
ans = [0] * N
temp = []
temp_idx = {('A', 'B'):[], ('A', 'C'):[], ('B', 'C'):[]}
for i in range(N):
  s1, s2 = list(input())
  id1, id2 = id_d[s1], id_d[s2]
  v1, v2 = v[id1], v[id2]
  if v1 == v2 == 0:
    if sorted([s1, s2]) == ['A', 'B']:
      s3 = 'C'
    if sorted([s1, s2]) == ['A', 'C']:
      s3 = 'B'
    else:
      s3 = 'A'
    if temp_idx[tuple(sorted((s1, s3)))]:
      idx = temp_idx[tuple(sorted((s1, s3)))].pop()
      _i, _s1, _s2 = temp[idx]
      ans[_i] = s1
      v[id1] = 1
      v[id2] = 1
    elif temp_idx[tuple(sorted((s2, s3)))]:
      idx = temp_idx[tuple(sorted((s2, s3)))].pop()
      _i, _s1, _s2 = temp[idx]
      ans[_i] = s2
      v[id1] = 1
      v[id2] = 1
    else:
      print('No')
      quit()
  else:
    if v1 > v2:
      ans[i] = s2
      v[id_d[s1]] -= 1
      v[id_d[s2]] += 1
    elif v1 < v2:
      ans[i] = s1
      v[id_d[s2]] -= 1
      v[id_d[s1]] += 1
    else: # v1 == v2
      v[id_d[s1]] -= 1
      v[id_d[s2]] -= 1
      temp.append([i, s1, s2])
      temp_idx[tuple(sorted((s1, s2)))].append(i)

for i, s1, s2 in temp:
  if ans[i] == 0:
    ans[i] = s1

print('Yes')
print(*ans, sep='\n')

Submission status: Runtime Error

Solution code:
from collections import deque
n, a, b, c = map(int, input().split())
s = [input() for _ in range(n)]
ans = []
if (a==0 and  b==0 and c==1) or (a==0 and  b==1 and c==0) or (a==1 and  b==0 and c==0):
    for i in range(n):
        if s[i] == "AB":
            if a >= 1:
                a -= 1
                b += 1
                ans.append("B")
            elif b >= 1:
                a += 1
                b -= 1
                ans.append("A")
            else:
                print("No")
                exit()
        elif s[i] == "AC":
            if a >= 1:
                a -= 1
                c += 1
                ans.append("C")
            elif c >= 1:
                a += 1
                c -= 1
                ans.append("A")
            else:
                print("No")
                exit()
        else:
            if b >= 1:
                b -= 1
                c += 1
                ans.append("C")
            elif c >= 1:
                b += 1
                c -= 1
                ans.append("B")
            else:
                print("No")
                exit()
    print("Yes")
    for i in ans:
        print(i)
    exit()

if (a==0 and  b==1 and c==1) or (a==1 and  b==0 and c==1) or (a==1 and  b==1 and c==0):
    que = deque([[a, b, c, []]])
    for i in range(n):
        if not que:
            print("No")
            exit()
        len_que = len(que)
        for _ in range(len_que):
            a, b, c, ans = que.popleft()
            if s[i] == "AB":
                if a>=1 and b==0:
                    a -= 1
                    b += 1
                    ans.append("B")
                elif b>=1 and a==0:
                    a += 1
                    b -= 1
                    ans.append("A")
                elif a==0 and b==0: continue
                else:
                    ans1 = ans.append("A")
                    ans2 = ans.append("B")
                    que.append([a+1, b-1, c, ans1])
                    que.append([a-1, b+1, c, ans2])
                    continue
            elif s[i] == "AC":
                if a>=1 and c==0:
                    a -= 1
                    c += 1
                    ans.append("C")
                elif c>=1and a==0:
                    a += 1
                    c -= 1
                    ans.append("A")
                elif a==0 and c==0: continue
                else:
                    ans1 = ans.append("A")
                    ans2 = ans.append("C")
                    que.append([a+1, b, c-1, ans1])
                    que.append([a-1, b, c+1, ans2])
                    continue
            else:
                if b >= 1 and c==0:
                    b -= 1
                    c += 1
                    ans.append("C")
                elif c >= 1and b==0:
                    b += 1
                    c -= 1
                    ans.append("B")
                elif b==0 and c==0: continue  
                else:
                    ans1 = ans.append("B")
                    ans2 = ans.append("C")
                    que.append([a, b+1, c-1, ans1])
                    que.append([a, b-1, c+1, ans2])
                    continue
            que.append([a, b, c, ans])
    a, b, c, ans = que.popleft()
    for i in ans:
        print(i)
    exit()

if a==0 and  b==0:
    if s[0] == "AB":
        print("No")
        exit()
elif a==0 and  c==0:
    if s[0] == "AC":
        print("No")
        exit()
elif b==0 and  c==0:
    if s[0] == "BC":
        print("No")
        exit()

print("Yes")
for i in range(n):
    if s[i] == "AB":
        if a >= b:
            a -= 1
            b += 1
            print("B")
        else:
            a += 1
            b -= 1
            print("A")
    elif s[i] == "AC":
        if a >= c:
            a -= 1
            c += 1
            print("C")
        else:
            a += 1
            c -= 1
            print("A")
    else:
        if b >= c:
            b -= 1
            c += 1
            print("C")
        else:
            b += 1
            c -= 1
            print("B")

Submission status: Runtime Error

Solution code:
N,A,B,C = list(map(int,input().split()))
import sys
input = sys.stdin.readline
S = tuple(input().strip() for i in range(N))
tup = [A,B,C]

def idx(ch):
  return "ABC".index(ch)

def search(ABC,path):
  res = ""
  for i,(l1,l2) in enumerate(path):
    if ABC[idx(l1)] > ABC[idx(l2)]:
      ABC[idx(l1)] -= 1
      ABC[idx(l2)] += 1
      res += l2
    elif ABC[idx(l1)] < ABC[idx(l2)]:
      ABC[idx(l1)] += 1
      ABC[idx(l2)] -= 1
      res += l1
    elif ABC[idx(l1)] + ABC[idx(l2)]== 0:
      return False,""
    elif ABC[idx(l1)] + ABC[idx(l2)] > 2:
      ABC[idx(l1)] += 1
      res += l1
      ABC[idx(l2)] -= 1
    else:
      # 両方のpathを探索する
      ABC_j = [i for i in ABC]
      ABC_j[idx(l1)] += 1
      ABC_j[idx(l2)] -= 1
      
      ABC_k = [i for i in ABC]
      ABC_k[idx(l1)] -= 1
      ABC_k[idx(l2)] += 1
      
      jT,jpath = search(ABC_j,path[i:])
      if jT:
        return jT,res + jpath
      
      kT,kpath = search(ABC_k,path[i:])
      if kT:
        return kT,res + kpath
      return False, ""
  else:
    return True,res
  
if len(S) > 100:
  res, p = search(tup,S[:100])
  # simulate:
  if res:
    ## 結果がokならその先まで考慮してみる
    a,b,c = tup
    for q,ch in zip(S[:100],p):
      qset = {qq for qq in q}
      tup[idx(ch)] += 1
      tup[list(qset-ch)[0]] -= 0
    
    res, p2 = search(tup,S[100:])
    if res:
      print("Yes")
      for c in p:
        print(c)
      for c in p2:
        print(c)
    else:
      print("No")
    
  else:
    print("No")
  
else:
  res, p = search(tup,S)
  if res:
    print("Yes")
    for c in p:
      print(c)
  else:
    print("No")

Submission status: Runtime Error

Solution code:
n,a,b,c=map(int,input().split())
arr=[input() for _ in range(n)]
if (a==0 and b==0) or (a==0 and c==0) or (b==0 and c==0):
  ans=[]
  for i in range(n):
    if arr[i]=='AB':
      if a==0 and b==0:
        print('No')
        break
      else:
        if a>b:
          a-=1
          b+=1
          ans.append('B')
        elif a<b:
          a+=1
          b-=1
          ans.append('A')
        elif a==b:
          if i==n-1:
            a+=1
            b-=1
            ans.append('A')
          else:
            if arr[i+1]=='AB':
              a+=1
              b-=1
              ans.append('A')
            elif arr[i+1]=='AC':
              a+=1
              b-=1
              ans.append('A')
            elif arr[i+1]=='BC':
              a-=1
              b+=1
              ans.append('B')
    elif arr[i]=='AC':
      if a==0 and c==0:
        print('No')
        break
      else:
        if a>c:
          a-=1
          c+=1
          ans.append('C')
        elif a<c:
          a+=1
          c-=1
          ans.append('A')
        elif a==c:
          if i==n-1:
            a+=1
            c-=1
            ans.append('A')
          else:
            if arr[i+1]=='AC':
              a+=1
              c-=1
              ans.append('A')
            elif arr[i+1]=='AB':
              a+=1
              c-=1
              ans.append('A')
            elif arr[i+1]=='BC':
              a-=1
              c+=1
              ans.append('C')
    elif arr[i]=='BC':
      if b==0 and c==0:
        print('No')
        break
      else:
        if b>c:
          b-=1
          c+=1
          ans.append('C')
        elif b<c:
          b+=1
          c-=1
          ans.append('B')
        elif a==c:
          if i==n-1:
            b+=1
            c-=1
            ans.append('B')
          else:
            if arr[i+1]=='BC':
              b+=1
              c-=1
              ans.append('B')
            elif arr[i+1]=='AB':
              b+=1
              c-=1
              ans.append('B')
            elif arr[i+1]=='AC':
              b-=1
              c+=1
              ans.append('C')
  else:
    print('Yes')
    for i in range(n):
      print(ans[i])
else:
  print('Yes')
  ans=[]
  for i in range(n):
    if arr[i]=='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 i==n-1:
          a+=1
          b-=1
          ans.append('A')
        else:
          if arr[i+1]=='AB':
            a+=1
            b-=1
            ans.append('A')
          elif arr[i+1]=='AC':
            a+=1
            b-=1
            ans.append('A')
          elif arr[i+1]=='BC':
            a-=1
            b+=1
            ans.append('B')
    elif arr[i]=='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 i==n-1:
          a+=1
          c-=1
          ans.append('A')
        else:
          if arr[i+1]=='AC':
            a+=1
            c-=1
            ans.append('A')
          elif arr[i+1]=='AB':
            a+=1
            c-=1
            ans.append('A')
          elif arr[i+1]=='BC':
            a-=1
            c+=1
            ans.append('C')
    elif arr[i]=='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 i==n-1:
          b+=1
          c-=1
          ans.append('B')
        else:
          if arr[i+1]=='BC':
            b+=1
            c-=1
            ans.append('B')
          elif arr[i+1]=='AB':
            b+=1
            c-=1
            ans.append('B')
          elif arr[i+1]=='AC':
            b-=1
            c+=1
            ans.append('C')
  for i in range(n):
    print(ans[i])

Submission status: Runtime Error

Solution code:


n, a, b, c = map(int, input().split())
ss = [None] * n
for i in range(n):
    ss[i] = input()

abc = {"A": a, "B": b, "C": c}
ans = [None] * n
# 3つある→ aをなくしにかかる
# 2つある→ bを1にしにかかる
# 0, 1, c→ c>=2のとき、
No = False
for i,s in enumerate(ss):
    zero = [i for i, item in abc.items() if item==0]
    one = [i for i, item in abc.items() if item==1]
    two = [i for i, item in abc.items() if item>=2]
#     print(s)
#     print(zero, one, two)
    if len(zero)==0:
        if s in ["AB", "AC"]:
            ans[i] = "A"
            abc["A"] += 1
            abc[s[1]] -= 1
        else:
            ans[i] = "C"
            abc["C"] += 1
            abc["B"] -= 1
    elif len(zero)==1 and len(two)>=1:
        z = zero[0]
        t = two[0]
        if z in s:
            # zに加える
            ans[i] = z
            abc[z] += 1
            abc[s.replace(z, "")] -= 1
        else:
            # twoから引く
            tmp = s.replace(t, "")
            ans[i] = tmp
            abc[tmp] += 1
            abc[t] -= 1
    elif len(zero)==1 and len(one)==2:
        z = zero[0]
        if s[0] in one and s[1] in one:
            # １手先を見て、
            ns = ss[i+1] if i+1<=n-1 else None
            if (z not in ns) or ns is None:
                # 次も同じなのでどちらでもよい
                ans[i] = one[0]
                abc[one[0]] += 1
                abc[one[1]] -= 1
            else:
                # nsのzでないほうに加える
                tmp = ns.replace(z, "")
                ans[i] = tmp
                abc[tmp] += 1
                abc[s.replace(tmp, "")] -= 1
        else:
            # 0に加える
            z = zero[0]
            ans[i] = z
            abc[z] += 1
            abc[s.replace(z, "")] -= 1
    else:
        # 0が２つ以上
        assert len(zero) >= 2
        if len(zero)==3:
            No = True
            break
        elif s[0] in zero and s[1] in zero:
            No = True
            break
        else:
            # zに加える
            z = (set(s) & set(zero)).pop()
            ans[i] = z
            abc[z] += 1
            abc[s.replace(z, "")] -= 1
            
if No:
    print("No")
else:
    print("Yes")
    print("\n".join(ans))

Submission status: Runtime Error

Solution code:
N, A, B, C = map(int, input().split(" "))
commands = []
data = {
    'A': A,
    'B': B,
    'C': C
}
ans = [] 

if A >=1 and B >= 1 and C >= 1 :
    print("Yes")
    for _ in range(N) :
        command = input()
        if data[command[0]] > data[command[1]] :
            data[command[0]] -= 1
            data[command[1]] += 1
            print(command[1])
        else :
            data[command[0]] += 1
            data[command[1]] -= 1
            print(command[0]) 
else :
    safe = []
    commands = []
    for _ in range(N) :
        commands.append(input())

    fail = False
    i = 0 
    ans = []
    
    while i < N : 
        if data[commands[i][0]] == 0 and data[commands[i][1]] == 0 :
            if safe == [] :
                fail = True
                break
            else : 
                data, i, ans = safe.pop()
        elif data[commands[i][0]] == 1 and data[commands[i][1]] == 1 :
            _data = { 'A' :data['A'], 'B' :data['B'], 'C' :data['C'] }
            _i = i
            _ans = list(ans)
        
            _data[commands[i][1]] += 1
            _data[commands[i][0]] -= 1
            _ans.append( commands[i][1] )
            safe.append( [_data, _i. _ans] ) 

            data[commands[i][0]] += 1
            data[commands[i][1]] -= 1
            ans.append( commands[i][0] )
        else :
            if data[commands[i][0]] > data[commands[i][1]] :
                x = commands[i][0] 
                y = commands[i][1] 
            else :
                x = commands[i][1] 
                y = commands[i][0]

            data[x] -= 1 
            data[y] += 1
            ans.append(y)

        i += 1

    if fail :
        print("No")
    else :
        print("Yes")
        for c in ans :
            print(c)