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: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**5)

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

for i in range(n):
    s.append(input())

ans = []
# ngMap = {}
ngMap = set()

def solve(idx, x, y, z, cur):
    text = ''.join(cur)

    if text in ngMap:
        return

    if x < 0 or y < 0 or z < 0:
        ngMap.add(text)
        return
    if idx == n:
        if x >= 0 and y >= 0 and z >= 0:
            print('Yes')
            for i in range(n):
                print(cur[i])
            exit()
        #     ans.append(cur)
        # return

    if s[idx] == 'AB':
        solve(idx + 1, x + 1, y - 1, z, cur + ['A'])
        solve(idx + 1, x - 1, y + 1, z, cur + ['B'])
    elif s[idx] == 'AC':
        solve(idx + 1, x + 1, y, z - 1, cur + ['A'])
        solve(idx + 1, x - 1, y, z + 1, cur + ['C'])
    elif s[idx] == 'BC':
        solve(idx + 1, x, y + 1, z - 1, cur + ['B'])
        solve(idx + 1, x, y - 1, z + 1, cur + ['C'])

solve(0, a, b, c, [])

# print(ans)
print('No')

Submission status: Time Limit Exceeded

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)] >= 4:
      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:])
      kT,kpath = search(ABC_k,path[i:])
      
      if jT:
        return jT,res + jpath
      elif kT:
        return kT,res + kpath
      else:
        return False, ""
  else:
    return True,res
res, p = search(tup,S)
if res:
  print("Yes")
  for c in p:
    print(c)
else:
  print("No")

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
YES = "Yes"  # type: str
NO = "No"  # type: str

def solve(n: int, A: int, B: int, C: int, s: "List[str]"):
    S = {}
    S[(A,B,C)] = ""
    for i in range(n):
        N = {}
        d = s[i]
        for a,b,c in S:
            path = S[(a,b,c)]
            if d == "AB":
                if b >= n-i:
                    N[(a+1,b-1,c)] = path + "A"
                    continue
                if a >= n-i:
                    N[(a-1,b+1,c)] = path + "B"
                    continue
                if b > 0:
                    # A+1,B-1
                    N[(min(n,a+1),b-1,c)] = path + "A"
                if a > 0:
                    N[(a-1,min(n,b+1),c)] = path + "B"
            elif d == "BC":
                if b >= n - i:
                    N[(a, b - 1, c + 1)] = path + "C"
                    continue
                if c >= n - i:
                    N[(a, b+1, c-1)] = path + "B"
                    continue
                if c > 0:
                    # b +1,c -1
                    N[(a, min(n,b + 1), c-1)] = path + "B"
                if b > 0:
                    N[(a, b -1, min(n,c+1))] = path + "C"
            else:
                if c >= n - i:
                    N[(a + 1, b, c-1)] = path + "A"
                    continue
                if a >= n - i:
                    N[(a - 1, b, c+1)] = path + "C"
                    continue
                if c > 0:
                    N[(min(n,a+1),b,c-1)] = path + "A"
                if a > 0:
                    N[(a-1,b,min(n,c+1))] = path + "C"
        if len(N) == 0:
            print(NO)
            exit()
        S = N
    print(YES)
    for a,b,c in S:
        p = S[(a,b,c)]
        for i in p:
            print(i)
        break

    return


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = int(next(tokens))  # type: int
    B = int(next(tokens))  # type: int
    C = int(next(tokens))  # type: int
    s = [next(tokens) for _ in range(N)]  # type: "List[str]"
    solve(N, A, B, C, s)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**9)

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

def game(i,A,B,C):
    if i==N:
        if A>=0 and B>=0 and C>=0:
            return True,[]
        else:
            return False,[]
    cmd=cmds[i]
    if cmd=="AB":

        if A==0 and B==0:
            return False,[]
        g1= game(i+1,A-1,B+1,C)
        if g1[0]:
            return g1[0],g1[1]+["B"]
        g2=game(i+1,A+1,B-1,C)
        if g2[0]:
            return g2[0],g2[1]+["A"]
        else:
            return False,[]

    elif cmd=="AC":
            if A==0 and C==0:
                return False,[]
            g1= game(i+1,A-1,B,C+1)
            if g1[0]:
                return g1[0],g1[1]+["C"]
            g2=game(i+1,A+1,B,C-1)
            if g2[0]:
                return g2[0],g2[1]+["A"]
            else:
                return False,[]
    else:
            if C==0 and B==0:
                return False,[]
            g1= game(i+1,A,B+1,C-1)
            if g1[0]:
                return g1[0],g1[1]+["B"]
            g2=game(i+1,A,B-1,C+1)
            if g2[0]:
                return g2[0],g2[1]+["C"]
            else:
                return False,[]



suc,his=game(0,A,B,C)
if suc:
    print("Yes")
    for h in his[::-1]:
        print(h)
else:
    print("No")

Submission status: Time Limit Exceeded

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)] > 4:
      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:])
      kT,kpath = search(ABC_k,path[i:])
      
      if jT:
        return jT,res + jpath
      elif kT:
        return kT,res + kpath
      else:
        return False, ""
  else:
    return True,res
res, p = search(tup,S)
if res:
  print("Yes")
  for c in p:
    print(c)
else:
  print("No")

Submission status: Time Limit Exceeded

Solution code:
import sys
from math import ceil, floor, sqrt, sin, cos, pi
from itertools import accumulate, permutations, combinations
from fractions import gcd # 最大公約数
from collections import deque, Counter
from operator import itemgetter
from heapq import heappop,heappush
sys.setrecursionlimit(10**7)
def lcm(x, y): return ((x * y) // gcd(x, y)) # 最小公倍数
# list(map(int, input().split()))
n, a, b, c = map(int, input().split())
ans = [[a, b, c]]
cnt = ['']
cnt_ab = 0
cnt_ac = 0
cnt_bc = 0
for _ in range(n):
    s = input()
    new = []
    cen = []
    if s == 'AB':
        for i in range(len(ans)):
            t = cnt[i]
            now = ans[i]
            if now[1] > 0:
                cen.append(t + 'A')
                new.append([now[0]+1, now[1]-1, now[2]])
            if now[0] > 0:
                cen.append(t + 'B')
                new.append([now[0]-1, now[1]+1, now[2]])
    elif s == 'AC':
        for i in range(len(ans)):
            now = ans[i]
            t = cnt[i]
            if now[2] > 0:
                cen.append(t + 'A')
                new.append([now[0]+1, now[1], now[2]-1])
            if now[0] > 0:
                cen.append(t + 'C')
                new.append([now[0]-1, now[1], now[2]+1])
    else:
        for i in range(len(ans)):
            now = ans[i]
            t = cnt[i]
            if now[2] > 0:
                cen.append(t + 'B')
                new.append([now[0], now[1]+1, now[2]-1])
            if now[1] > 0:
                cen.append(t + 'C')
                new.append([now[0], now[1]-1, now[2]+1])
    ans = new
    cnt = cen
for i in range(len(ans)):
    if ans[i][0] >= 0 and ans[i][1] >= 0 and ans[i][2] >= 0:
        print('Yes')
        for x in cnt[i]:
            print(x)
        sys.exit()
print('No')

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
YES = "Yes"  # type: str
NO = "No"  # type: str

def solve(n: int, A: int, B: int, C: int, s: "List[str]"):
    S = {}
    S[(A,B,C)] = ""
    for i in range(n):
        N = {}
        d = s[i]
        for a,b,c in S:
            path = S[(a,b,c)]
            if d == "AB":
                if b > 0:
                    # A+1,B-1
                    N[(min(n,a+1),b-1,c)] = path + "A"
                if a > 0:
                    N[(a-1,min(n,b+1),c)] = path + "B"
            elif d == "BC":
                if c > 0:
                    # b +1,c -1
                    N[(a, min(n,b + 1), c-1)] = path + "B"
                if b > 0:
                    N[(a, b -1, min(n,c+1))] = path + "C"
            else:
                if c > 0:
                    N[(min(n,a+1),b,c-1)] = path + "A"
                if a > 0:
                    N[(a-1,b,min(n,c+1))] = path + "C"
        if len(N) == 0:
            print(NO)
            exit()
        S = N
    print(YES)
    for a,b,c in S:
        p = S[(a,b,c)]
        for i in p:
            print(i)
        break

    return


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = int(next(tokens))  # type: int
    B = int(next(tokens))  # type: int
    C = int(next(tokens))  # type: int
    s = [next(tokens) for _ in range(N)]  # type: "List[str]"
    solve(N, A, B, C, s)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    from collections import deque
    import sys
    input = sys.stdin.readline

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

    dq = deque()
    dq.append((a, b, c, '', 0))

    ans = []
    while dq:
        A, B, C, ops, cur = dq.popleft()
        # print(f'{A=},{B=},{C=},{ops=},{cur=}')
        
        if cur == n:
            ans = list(ops)
            break

        op = s[cur]
        if op == 'AB':
            if A == B == 0:
                continue
            if A >= B:
                dq.append((A - 1, B + 1, C, ops + 'B', cur + 1))
            if A <= B:
                dq.append((A + 1, B - 1, C, ops + 'A', cur + 1))

        elif op == 'AC':
            if A == C == 0:
                continue
            if A >= C:
                dq.append((A - 1, B, C + 1, ops + 'C', cur + 1))
            if A <= C:
                dq.append((A + 1, B, C - 1, ops + 'A', cur + 1))

        else:
            if B == C == 0:
                continue
            if B >= C:
                dq.append((A, B - 1, C + 1, ops + 'C', cur + 1))
            if B <= C:
                dq.append((A, B + 1, C - 1, ops + 'B', cur + 1))

    if ans:
        print('Yes')
        print(*ans, sep='\n')
    else:
        print('No')


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys
YES = "Yes"  # type: str
NO = "No"  # type: str

def solve(n: int, A: int, B: int, C: int, s: "List[str]"):
    S = {}
    S[(A,B,C)] = ""
    for i in range(n):
        N = {}
        d = s[i]
        for a,b,c in S:
            path = S[(a,b,c)]
            if d == "AB":
                if b > 0:
                    # A+1,B-1
                    N[(a+1,b-1,c)] = path + "A"
                if a > 0:
                    N[(a-1,b+1,c)] = path + "B"
            elif d == "BC":
                if c > 0:
                    # b +1,c -1
                    N[(a, b + 1, c-1)] = path + "B"
                if b > 0:
                    N[(a, b -1, c+1)] = path + "C"
            else:
                if c > 0:
                    N[(a+1,b,c-1)] = path + "A"
                if a > 0:
                    N[(a-1,b,c+1)] = path + "C"
        if len(N) == 0:
            print(NO)
            exit()
        S = N
    print(YES)
    for a,b,c in S:
        p = S[(a,b,c)]
        for i in p:
            print(i)
        break

    return


# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = int(next(tokens))  # type: int
    B = int(next(tokens))  # type: int
    C = int(next(tokens))  # type: int
    s = [next(tokens) for _ in range(N)]  # type: "List[str]"
    solve(N, A, B, C, s)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
mod = 1000000007
eps = 10**-9


def main():
    import sys
    input = sys.stdin.readline

    N, A, B, C = map(int, input().split())
    ans = []
    S = []
    for _ in range(N):
        S.append(input().rstrip('\n'))

    j_AB = 0
    j_BC = 0
    j_AC = 0
    for i in range(N):
        s = S[i]
        if s == "AB":
            if A == B == 0:
                print("No")
                exit()
            if A > B:
                A -= 1
                B += 1
                ans.append("B")
            elif A < B:
                A += 1
                B -= 1
                ans.append("A")
            else:
                if A > 1 or C > 0:
                    A += 1
                    B -= 1
                    ans.append("A")
                else:
                    if j_AB > i:
                        if j_AB == N:
                            A -= 1
                            B += 1
                            ans.append("B")
                        elif S[j_AB] == "BC":
                            A -= 1
                            B += 1
                            ans.append("B")
                        else:
                            A += 1
                            B -= 1
                            ans.append("A")
                    else:
                        j_AB = i+1
                        while True:
                            if S[j_AB] == "AB":
                                continue
                            j_AB += 1
                            if j_AB == N:
                                break
                        if j_AB > i:
                            if j_AB == N:
                                A -= 1
                                B += 1
                                ans.append("B")
                            elif S[j_AB] == "BC":
                                A -= 1
                                B += 1
                                ans.append("B")
                            else:
                                A += 1
                                B -= 1
                                ans.append("A")
        elif s == "BC":
            if B == C == 0:
                print("No")
                exit()
            if B > C:
                B -= 1
                C += 1
                ans.append("C")
            elif B < C:
                B += 1
                C -= 1
                ans.append("B")
            else:
                if B > 1 or A > 0:
                    B += 1
                    C -= 1
                    ans.append("B")
                else:
                    if j_BC > i:
                        if j_BC == N:
                            B -= 1
                            C += 1
                            ans.append("C")
                        elif S[j_BC] == "AC":
                            B -= 1
                            C += 1
                            ans.append("C")
                        else:
                            B += 1
                            C -= 1
                            ans.append("B")
                    else:
                        j_BC = i+1
                        while True:
                            if S[j_BC] == "BC":
                                continue
                            j_BC += 1
                            if j_BC == N:
                                break
                        if j_BC > i:
                            if j_BC == N:
                                B -= 1
                                C += 1
                                ans.append("C")
                            elif S[j_BC] == "AC":
                                B -= 1
                                C += 1
                                ans.append("C")
                            else:
                                B += 1
                                C -= 1
                                ans.append("B")
        elif s == "AC":
            if A == C == 0:
                print("No")
                exit()
            if A > C:
                A -= 1
                C += 1
                ans.append("C")
            elif A < C:
                A += 1
                C -= 1
                ans.append("A")
            else:
                if A > 1 or B > 0:
                    A += 1
                    C -= 1
                    ans.append("A")
                else:
                    if j_AC > i:
                        if j_AC == N:
                            A -= 1
                            C += 1
                            ans.append("C")
                        elif S[j_AC] == "BC":
                            A -= 1
                            C += 1
                            ans.append("C")
                        else:
                            A += 1
                            C -= 1
                            ans.append("A")
                    else:
                        j_AC = i+1
                        while True:
                            if S[j_AC] == "AC":
                                continue
                            j_AC += 1
                            if j_AC == N:
                                break
                        if j_AC > i:
                            if j_AC == N:
                                A -= 1
                                C += 1
                                ans.append("C")
                            elif S[j_AC] == "BC":
                                A -= 1
                                C += 1
                                ans.append("C")
                            else:
                                A += 1
                                C -= 1
                                ans.append("A")
    print("Yes")
    for a in ans:
        print(a)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(10**6)
buff_readline = sys.stdin.buffer.readline
readline = sys.stdin.readline

INF = 2**62-1


def read_int():
    return int(buff_readline())


def read_int_n():
    return list(map(int, buff_readline().split()))


def read_float():
    return float(buff_readline())


def read_float_n():
    return list(map(float, buff_readline().split()))


def read_str():
    return readline().strip()


def read_str_n():
    return readline().strip().split()

def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, A, B, C, S):
    dp = {}
    dp[(A, B, C)] = []
    for s in S:
        t = []
        if 'A' in s:
            t.append(0)
        if 'B' in s:
            t.append(1)
        if 'C' in s:
            t.append(2)
        ndp = {}
        for k in dp:
            for i, j in permutations(t, r=2):
                a = [0] * 3
                a[i] += 1
                a[j] -= 1
                if k[j] > 0:
                    l = dp[k][:]
                    l.append(i)
                    ndp[(k[0]+a[0], k[1]+a[1], k[2]+a[2])] = l
        dp = ndp
        if not dp:
            print('No')
            return
    print('Yes')
    for v in dp.values():
        for i in v:
            if i == 0:
                print('A')
            elif i == 1:
                print('B')
            else:
                print('C')
        return


def main():
    N, A, B, C = read_int_n()
    S = [read_str() for _ in range(N)]
    (slv(N, A, B, C, S))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

N, A, B, C = mapint()
costs = {'A': A, 'B': B, 'C': C}
old_a, old_b = list(input())

if costs[old_a]==0 and costs[old_b]==0:
    print('No')
    exit()

commands = []
for _ in range(N-1):
    nx_a, nx_b = list(input())
    if costs[old_a]==0 and costs[old_b]==0:
        print('No')
        exit()
    elif costs[old_a]==0:
        costs[old_a] += 1
        costs[old_b] -= 1
        commands.append(old_a)
        
    elif costs[old_b]==0:
        costs[old_b] += 1
        costs[old_a] -= 1
        commands.append(old_b)

    else:
        if old_a==nx_a or old_a==nx_b:
            commands.append(old_a)
            costs[old_a] += 1
            costs[old_b] -= 1
        else:
            commands.append(old_b)
            costs[old_b] += 1
            costs[old_a] -= 1
    old_a, old_b = nx_a, nx_b

if costs[old_a]==0 and costs[old_b]==0:
    print('No')
    exit()
elif costs[old_a]==0:
    costs[old_a] += 1
    costs[old_b] -= 1
    commands.append(old_a)
    
else:
    costs[old_b] += 1
    costs[old_a] -= 1
    commands.append(old_b)

print('Yes')
print('\n'.join(commands))

Submission status: Accepted

Solution code:
N,A,B,C = map(int,input().split())
valid = True
array = []
for i in range(N):
    s = input()
    array.append(s)
array2 = []
for i in range(N):
    if array[i] == "AB":
        if A == B == 0:
            valid = False
            break
        elif i != N-1 and A == B and array[i+1] == "AC":
            A += 1
            B -= 1
            array2.append("A")
        elif i != N-1 and A == B and array[i+1] == "BC":
            A -= 1
            B += 1
            array2.append("B")
        elif A <= B:
            A += 1
            B -= 1
            array2.append("A")
        else:
            A -= 1
            B += 1
            array2.append("B")
    elif array[i] == "AC":
        if A == C == 0:
            valid = False
            break
        elif i != N-1 and A == C and array[i+1] == "BC":
            A -= 1
            C += 1
            array2.append("C")
        elif i != N-1 and A == C and array[i+1] == "AC":
            A += 1
            C -= 1
            array2.append("A")
        elif A <= C:
            A += 1
            C -= 1
            array2.append("A")
        else:
            A -= 1
            C += 1
            array2.append("C")
    else:
        if B == C == 0:
            valid = False
            break
        elif i != N-1 and B == C and array[i+1] == "AC":
            B -= 1
            C += 1
            array2.append("C")
        elif i != N-1 and B == C and array[i+1] == "AB":
            B += 1
            C -= 1
            array2.append("B")
        elif B <= C:
            B += 1
            C -= 1
            array2.append("B")
        else:
            B -= 1
            C += 1
            array2.append("C")
if valid:
    print("Yes")
    for i in range(len(array2)):
        print(array2[i])
else:
    print("No")

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
n, a, b, c = map(int, input().split())
S = [input().rstrip().replace("AC", "CA") for _ in range(n)]
D = ["AB", "BC", "CA"]
X = [a+b, b+c, c+a]
L = []
for i, s in enumerate(S):
  k = D.index(s)
  if X[k] == 0:
    print("No")
    exit()
  if X[(k+1)%3] == 1 and X[(k+2)%3] == 1 and i < n-1:
    l = D.index(S[i+1])
    if l == (k+1)%3:
      X[(k+1)%3] += 1
      X[(k+2)%3] -= 1
      L.append(s[1])
    else:
      X[(k+2)%3] += 1
      X[(k+1)%3] -= 1
      L.append(s[0])
  else:
    if X[(k+1)%3] < X[(k+2)%3]:
      X[(k+1)%3] += 1
      X[(k+2)%3] -= 1
      L.append(s[1])
    else:
      X[(k+2)%3] += 1
      X[(k+1)%3] -= 1
      L.append(s[0])
print("Yes")
print(*L, sep="\n")

Submission status: Accepted

Solution code:
n, a, b, c = (int(x) for x in input().split())
d = {"A": a, "B": b, "C": c}
S = [input() for _ in range(n)]
ANS = []

for i, s in enumerate(S):
    if d[s[0]] == 0 and d[s[1]] == 0:
        print("No")
        exit()
    else:
        if d[s[0]] > d[s[1]] or (d[s[0]] == d[s[1]] == 1 and i < n - 1 and s[1] in S[i + 1]):
            d[s[1]] += 1
            d[s[0]] -= 1
            ANS.append(s[1])
        else:
            d[s[0]] += 1
            d[s[1]] -= 1
            ANS.append(s[0])
print("Yes")
for ans in ANS:
    print(ans)

Submission status: Accepted

Solution code:
n,a,b,c=map(int,input().split())
s=[input() for _ in range(n)]
abc=[a,b,c]
d={'A':0,'B':1,'C':2}
dr={0:'A',1:'B',2:'C'}
ans=[]
for i,x in enumerate(s):
  x=[d[y] for y in list(x)]
  if abc[x[0]]==abc[x[1]]==1 and i<n-1:
    nx=[d[y] for y in list(s[i+1])]
    for j,y in enumerate(x):
      if y in nx:
        abc[y]+=1
        abc[x[(j+1)%2]]-=1
        ans.append(dr[y])
        break
  elif abc[x[0]]>abc[x[1]]:
    abc[x[1]]+=1
    abc[x[0]]-=1
    ans.append(dr[x[1]])
  else:
    abc[x[0]]+=1
    abc[x[1]]-=1
    ans.append(dr[x[0]])
  for y in abc:
    if y<0:
      print('No')
      exit()
  
print('Yes')
print(*ans,sep='\n')

Submission status: Accepted

Solution code:
N, A, B, C = map(int, input().split())
SS, res = [], []
for _ in range(N):
    SS.append(input().rstrip())
SS += ["#"]
for i in range(N):
    S = SS[i]
    if S=="AB":
        if A==B==1:
            if SS[i+1]=="BC": A, B = A-1, B+1; res.append("B")
            else: A, B = A+1, B-1; res.append("A")
        elif A>B: A, B = A-1, B+1; res.append("B")
        else: A, B = A+1, B-1; res.append("A")
    if S=="AC":
        if A==C==1:
            if SS[i+1]=="BC": A, C = A-1, C+1; res.append("C")
            else: A, C = A+1, C-1; res.append("A")
        elif A>C: A, C = A-1, C+1; res.append("C")
        else: A, C = A+1, C-1; res.append("A")
    if S=="BC":
        if B==C==1:
            if SS[i+1]=="AC": B, C = B-1, C+1; res.append("C")
            else: B, C = B+1, C-1; res.append("B")
        elif B>C: B, C = B-1, C+1; res.append("C")
        else: B, C = B+1, C-1; res.append("B")
    if A<0 or B<0 or C<0:
        print("No")
        exit()
print("Yes")
print(*res, sep="\n")