We are given a string of length n (1 ≤ n ≤ 100) with characters 'C', 'M', 'Y', or '?'. We need to determine if there exist at least two valid colorings of the entire string (by replacing '?' with any of three colors) such that no two adjacent segments have the same color. Also the colorings must be different (at least one segment colored differently). If there are at least two such colorings, output "Yes", else "No".
If the initial string already violates adjacency condition (i.e., there is an adjacent pair with same color and both are not '?'), then no valid coloring exists, so answer is No (since zero valid ways). Otherwise, we need to check if there are at least two valid completions.
Brute force over all possibilities would be 3^(#?): max n=100, so too many. We need to compute the number of valid completions (or at least check if >=2). This is a typical DP counting colorings of a line with constraints, with some fixed colors. But we just need to know if count >=2.
We can think about constraints: three colors, adjacency must differ. It's essentially counting proper 3-colorings of a path with precolored vertices. The number of completions can be computed via DP: For each position i, keep the number of ways to color up to i with the last color being specific. Then multiply over ? positions.
But we only need to know if the count is at least 2. However, there might be cases where count is exactly 1, and we need to output No, else Yes if count >=2. But careful: we must output Yes if at least two ways; else No.
So we can compute the exact count (since n <= 100, #? up to 100, count can be huge but we can use big integers or mod? But we only need to compare with 2, we could compute exactly using Python's arbitrary integers; that is fine. But we can also early exit when count >=2.
But we also need to check if there is any valid coloring at all. So DP that counts number of valid completions is straightforward.
Alternatively, we could look for conditions that guarantee multiple completions. But easier to compute DP.
Let's design DP:
Let dp[i][c] = number of ways to color first i segments (0-indexed, i from 0 to n-1) such that segment i gets color c (if fixed, only that c is allowed; if '?' then all three). But we also need to handle adjacency constraints: for i>0, dp[i][c] = sum over dp[i-1][d] for d != c, if segment i can be c. Initialize: For i=0: if s[0] is fixed color c, dp[0][c]=1 else if '?', dp[0][c]=1 for each c.
Then total ways = sum over colors for dp[n-1].
We need to ensure no invalid fixed adjacent pairs: But DP will automatically produce 0 ways if there is an impossible adjacent pair? Actually, if s[i] fixed to c and s[i-1] fixed to same c, then when computing dp[i][c], we need dp[i-1][d] for d != c. But if s[i-1] is fixed to c, then dp[i-1][c] = something, but other colors may be 0. However, dp[i-1][c] is not allowed because d != c, so we sum only d != c. If s[i-1] fixed to c, then dp[i-1][d] for d != c might be zero if those colors are not allowed for position i-1? Wait, position i-1 if fixed to c, then only dp[i-1][c] is non-zero. But then for dp[i][c], we sum dp[i-1][d] for d != c; dp[i-1][c] is excluded, and other dp[i-1][d] are zero because fixed to c only. So dp[i][c] = 0. So total ways may become zero. So DP correctly handles invalid adjacency.
Thus we can compute count and check >=2. However, note: The number could be very large, but Python's integers can handle.
But there is nuance: The problem asks "at least two ways" so count >=2. However, we must also consider that there might be exactly one valid coloring even if there are many '?'? For instance, if the string is all '?'? Then number of proper 3-colorings of a path of length n: first vertex 3 choices, each subsequent 2 choices (since can't be same as previous) => 3 * 2^(n-1). For n>=2, that's >=2. For n=1, it's 3 choices, so >=2? Actually for n=1, there are 3 ways, so >=2. So all '?' yields Yes for n>=1? 3 >=2 => Yes. But maybe there is a case with exactly one: if the constraints force a unique coloring. Example: "C?C" perhaps? Let's test: n=3, s = "C?C". Colors: first fixed C, last fixed C. The middle must be not equal to C and not equal to C? Actually adjacent to both: middle must be not C (from left) and not C (from right) => can be M or Y? But two possibilities => count=2. So not unique. Another: "C?M": left C, right M. Middle must be not C and not M => only Y => unique (1 way). So count=1. So "C?M" yields exactly one. So answer No. Check: n=3, string "C?M". We need to see if at least two ways: middle only Y. So only one coloring: CYM. So No. But check adjacency: C and Y differ, Y and M differ, valid. So answer No. So there exist cases with exactly one.
What about "C?Y"? left C, right Y => middle cannot be C or Y => only M => 1 way => No. Similarly "M?C" etc. Also "C?C?C"? Actually could be forced? Need to check.
Thus DP is appropriate.
But we might also reason about conditions for uniqueness. However, implementing DP is trivial.
One more nuance: The string may contain two consecutive '?' that could yield multiple possibilities. But DP will compute.
Edge Cases:
-
n=1: If '?', there are 3 ways => Yes. If fixed, there is exactly 1 way? Actually if fixed color, say 'C', then only that color, but is it considered a valid coloring? Yes, it's already colored. But we are to color unpainted segments. If there are no '?' and the existing coloring is valid (it always is for a single segment, adjacency condition vacuously true), then there is exactly one way: the existing coloring itself. That's because we can't change the painted segments. So total ways = 1. So output No. Wait, but problem: "You are to determine whether there are at least two ways of colouring all the unpainted segments so that no two adjacent segments are of the same colour." If there are no unpainted segments, then the only way is the given coloring (assuming it's valid). So there is exactly 1 way. So answer should be No. So for n=1 and fixed color, answer No. If '?', answer Yes because at least two ways (3 > 2). So DP will give that.
-
If initial string already has adjacent same colors (like "CC"), then no valid completions: count=0 => No.
-
If there is a segment fixed and adjacent to '?' that might be forced, etc.
Thus DP works.
Now about performance: O(n * 3 * 3) = O(n) fine.
Implementation details:
Map colors: 0,1,2 for C,M,Y or any order.
Let s = input string.
Initialize dp as list of length 3 with zeros.
For i=0:
if s[0]=='?': dp = [1,1,1]
else: dp = [0,0,0]; set dp[color_index] = 1.
Then iterate i from 1 to n-1:
new_dp = [0,0,0]
For each color c that is allowed at i:
allowed = if s[i]=='?' then all three, else only that color.
For each allowed c:
new_dp[c] = sum(dp[d] for d in range(3) if d != c)
(But careful: dp[d] might be large, but ok)
After loop, dp = new_dp.
At end, total = sum(dp). If total >= 2: print("Yes") else print("No").
Check examples:
-
5, "CY??Y". Let's compute? But it should yield Yes.
-
5 "C?C?Y" => Yes.
-
"?CYC?" => Yes.
-
"C??MM" => No.
-
"MMY" => No (because adjacent M and M? Actually "MMY": indices 0 M,1 M => adjacent same => invalid => count=0 => No.)
Alright.
But wait: Are there any pitfalls? In the DP, we consider adjacency only between consecutive segments. That's correct.
Now consider if the count is huge; we only compare with 2, but we can stop early if total >=2. However, DP computes step by step; we can break early if we detect that the number of completions is already >=2? But we need final total, but we can compute and if at some point total ways for all completions exceed 1? Actually we cannot conclude until we finish because later constraints may reduce to 0. But we can early exit if we know that no matter what, the count will be >=2? But it's simpler to compute full DP; n is small.
Alternative approach: count number of completions using combinatorics: for each maximal contiguous block of '?' bounded by fixed colors or ends. The number of completions for a block can be computed via matrix exponentiation? But DP is fine.
Nevertheless, we must consider that the count might be 0, 1, or >1. The DP approach yields exact count; we only need to compare to 2.
Edge case: n=0? Not possible because n>=1.
Now verify example 3: "?CYC?" length 5. Let's compute manually: positions: 0:?,1:C,2:Y,3:C,4:?. We expect 4 ways.
Our DP: i=0: '?' => dp = [1,1,1]
i=1: fixed C (index 0). allowed c=0 only. new_dp[0] = sum(dp[d] for d !=0) = dp[1]+dp[2] = 1+1=2. So dp = [2,0,0]
i=2: fixed Y (index 2). allowed c=2. new_dp[2] = sum(dp[d] for d !=2) = dp[0]+dp[1] = 2+0=2. So dp=[0,0,2]
i=3: fixed C (index 0). allowed c=0. new_dp[0] = sum(dp[d] for d !=0) = dp[1]+dp[2] = 0+2=2. dp=[2,0,0]
i=4: '?' allowed all. For each c:
c=0: sum(dp[d] for d !=0) = dp[1]+dp[2]=0+0=0
c=1: sum(dp[d] for d !=1) = dp[0]+dp[2]=2+0=2
c=2: sum(dp[d] for d !=2) = dp[0]+dp[1]=2+0=2
Thus new_dp = [0,2,2], total = 4. Yes.
Now example 4: "C??MM". Length 5: 0:C,1:?,2:?,3:M,4:M. Adjacent M-M at positions 3,4 fixed same => invalid? Actually positions 3 and 4 are both M, so adjacency violation. So DP should yield 0. Let's test: i=0: fixed C => dp=[1,0,0]
i=1: '?' allowed all:
c=0: sum(dp[d] for d!=0)=dp[1]+dp[2]=0+0=0
c=1: sum(dp[d] for d!=1)=dp[0]+dp[2]=1+0=1
c=2: sum(dp[d] for d!=2)=dp[0]+dp[1]=1+0=1
So dp=[0,1,1]
i=2: '?' allowed all:
c=0: sum(dp[d] for d!=0)=dp[1]+dp[2]=1+1=2
c=1: sum(dp[d] for d!=1)=dp[0]+dp[2]=0+1=1
c=2: sum(dp[d] for d!=2)=dp[0]+dp[1]=0+1=1
So dp=[2,1,1]
i=3: fixed M (index 1). allowed c=1 only.
new_dp[1] = sum(dp[d] for d !=1) = dp[0]+dp[2] = 2+1=3. So dp=[0,3,0]
i=4: fixed M (index 1). allowed c=1 only.
new_dp[1] = sum(dp[d] for d !=1) = dp[0]+dp[2] = 0+0=0. So dp=[0,0,0], total=0. So No.
Works.
Now check example 2: "C?C?Y": length5.
i0: C -> dp[0]=1
i1: '?' -> allowed all:
c0: sum(dp[d]!=0)=dp1+dp2=0 ->0
c1: sum!=1=dp0+dp2=1->1
c2: sum!=2=dp0+dp1=1->1 => dp=[0,1,1]
i2: fixed C (0):
new_dp0 = sum(dp[d]!=0)=dp1+dp2=1+1=2 => dp=[2,0,0]
i3: '?':
c0: sum!=0=dp1+dp2=0 =>0
c1: sum!=1=dp0+dp2=2+0=2
c2: sum!=2=dp0+dp1=2+0=2 => dp=[0,2,2]
i4: fixed Y (2):
new_dp2 = sum!=2=dp0+dp1=0+2=2 => total=2 => Yes.
Now example 1: "CY??Y": length5.
i0: C -> dp0=1
i1: Y -> fixed Y (2):
new_dp2 = sum!=2 = dp0+dp1 = 1+0=1 => dp=[0,0,1]
i2: '?':
c0: sum!=0=dp1+dp2=0+1=1
c1: sum!=1=dp0+dp2=0+1=1
c2: sum!=2=dp0+dp1=0+0=0 => dp=[1,1,0]
i3: '?':
c0: sum!=0=dp1+dp2=1+0=1
c1: sum!=1=dp0+dp2=1+0=1
c2: sum!=2=dp0+dp1=1+1=2 => dp=[1,1,2]
i4: fixed Y (2):
new_dp2 = sum!=2 = dp0+dp1 = 1+1 =2 => total=2 => Yes.
All match.
Now we should also consider the case where count might be huge but DP will handle big ints.
Thus solution: read n, read s, run DP.
However, there is nuance: The problem says "You are to determine whether there are at least two ways of colouring all the unpainted segments so that no two adjacent segments are of the same colour." It doesn't require that the initial painted segments are valid? Actually, if the initial painting already has adjacent same colours, then it's impossible to have any valid coloring because we can't repaint the fixed ones. So count=0 => No. That's correct.
Thus answer = Yes if total >= 2 else No.
But is there any case where total >=2 but the two ways are considered the same because they differ only on positions that are '?'? Actually the problem says: "Two ways are considered different if and only if a segment is painted in different colours in them." So if two assignments differ in at least one '?' segment, they are different. That's exactly what we count.
Therefore DP counts distinct assignments to '?' segments, consistent with fixed colors.
Potential oversight: The DP counts assignments to all segments, but we are not allowed to change fixed ones. That's respected.
Thus implementation straightforward.
However, note: Because n is small, we could also brute-force with backtracking with pruning, but DP is simpler.
Now we should double-check edge cases:
-
n=1, s='?' => DP: i0: dp = [1,1,1] total=3 >=2 => Yes.
-
n=1, s='C' => dp=[1,0,0] total=1 => No.
-
n=2: s='??' => DP: i0: [1,1,1]; i1: '?': for each c: sum of other two: for each c: total ways from previous for other colors: For c=0: dp1+dp2 = 1+1=2; similarly c=1:2; c=2:2 => dp = [2,2,2], total=6. >=2 => Yes.
-
n=2: s='C?' => i0: C -> [1,0,0]; i1: '?': c0: sum !=0 = dp1+dp2 =0; c1: sum!=1= dp0+dp2 =1; c2: sum!=2= dp0+dp1=1 => total=2 => Yes.
-
n=2: s='CM' => i0:C->[1,0,0]; i1: M (index1): new_dp1 = sum!=1 = dp0+dp2 =1+0=1 => total=1 => No. Indeed only one way (the given) but it's valid, so exactly one => No.
-
n=2: s='CC' => i0:C->[1,0,0]; i1: C-> new_dp0 = sum!=0 = dp1+dp2 =0 => total=0 => No.
All good.
Now consider scenario where there are multiple '?' but constraints force uniqueness: e.g., "C?M?C"? Let's compute to see if count=1 or >1. We'll test later.
But DP will handle.
Thus solution: DP.
But maybe we can simplify: The number of completions is either 0, 1, or >=2. Could there be exactly 2? Yes. Could there be exactly 3? Possibly. So DP is fine.
Now consider constraints: n up to 100, #? up to 100. DP with big integers: each step adds numbers up to 2^something? Actually maximum number of completions for n=100 all '?' is 3 * 2^99, which is about 3 * 10^29, which is huge but Python can handle arbitrary integers fine. So no issue.
Thus solution is trivial.
But wait, there is a subtle point: The DP counts all colorings that satisfy adjacency. But do we need to consider that the already painted segments may be invalid with each other? As we argued, DP yields 0 in that case. Good.
Now let's write code.
Pseudo:
def solve():
import sys
input_data = sys.stdin.read().strip().split()
if not input_data: return
n = int(input_data[0])
s = input_data[1].strip()
# map colors
col_index = {'C':0, 'M':1, 'Y':2}
dp = [0,0,0]
first = s[0]
if first == '?':
dp = [1,1,1]
else:
dp[col_index[first]] = 1
for i in range(1, n):
ch = s[i]
new_dp = [0,0,0]
allowed = [0,1,2] if ch == '?' else [col_index[ch]]
for c in allowed:
# sum over previous colors d != c
total = 0
# could loop over d
for d in range(3):
if d != c:
total += dp[d]
new_dp[c] = total
dp = new_dp
total_ways = sum(dp)
if total_ways >= 2:
print("Yes")
else:
print("No")
Test with given examples. Works.
But wait, one more nuance: What about when n=0? Not possible.
Now potential performance improvements: none needed.
We can also early check if any adjacent two fixed chars are same: then answer No immediately. But DP already handles; however we could early exit for slight efficiency.
But DP is fine.
Now I'm thinking: The DP approach might be overly complex for the problem? But it's okay.
However, some solutions might reason about existence of two completions by checking if there exists a '?' that can be colored in at least two ways given its neighbors. But that is not sufficient because the rest might be forced; but it might be a simpler condition. Actually, we need to count total completions. But perhaps we can determine if count >=2 by analyzing if the graph of constraints allows at least two distinct assignments. This is equivalent to whether the number of proper 3-colorings of a path with precolored vertices is >=2.
In a path, with precolored vertices, the number of completions can be computed as product of possibilities for each segment? Not exactly because constraints propagate. But we can treat each maximal segment of consecutive '?' between two fixed endpoints (or open ends). The number of colorings for that segment can be computed as something like: For a segment of length k of '?' with left fixed color L (or none) and right fixed color R (or none), the number of assignments that satisfy adjacency and end constraints. For the whole path, total number is product of numbers for each such segment (since they are independent if we treat fixed colors as separators? Actually the path is linear; fixed colors break the chain because the constraints only between adjacent positions. So yes, the number of completions for the whole string is product of numbers for each maximal block of consecutive '?' that are separated by fixed colors, but careful: the fixed colors themselves affect the possibilities on both sides. However, because the fixed colors are fixed, the blocks are independent? Let's consider: The path is: [segment of ?'s possibly at start] then fixed color, then ? block, then fixed, etc., and possibly ? block at end. Each block's number of colorings depends on the colors of the fixed neighbors (or no neighbor for ends). Since the fixed colors are determined, the assignments to one block do not affect another block because the blocks are separated by at least one fixed color. Indeed, adjacency constraints only involve immediate neighbors, so the color chosen for a '?' in one block does not directly constrain a '?' in another block if there is a fixed color in between, because that fixed color is constant and acts as a boundary. So the total number of completions is the product of the numbers for each block. Additionally, if there are no '?', product is empty product = 1.
Thus we can compute per block and multiply. If any product >=2, answer Yes. However, we also need to ensure that there is at least one valid coloring overall (product > 0). If any block has 0 possibilities, total is 0.
Thus we could compute each block's count using DP or combinatorial formulas. This might be simpler if we want to check if total >= 2 without large numbers? But DP over whole string is already simple.
Nevertheless, to avoid big integer multiplication, but it's not a concern.
But there may be an insight: For a block of '?' of length L, with left neighbor color (if exists) and right neighbor color (if exists), the number of valid colorings of the block (assigning colors to each ?) that are compatible with the neighbors (and no two adjacent same, including with neighbors) can be computed via recurrence. Specifically, for a block with left fixed color a (or none) and right fixed color b (or none), the number of assignments can be expressed as:
If block length is 0 (no ?), it's trivially 1.
Otherwise, we can think of a DP over the block positions with states being the current color.
Alternatively, there is known formula: For a path of length L (the number of vertices in the block) with possible colors, and with constraints on the ends: if both ends are unspecified (i.e., block at ends with no fixed neighbor on that side), then the number is 3 * 2^(L-1) if L>=1? Actually if there is no left neighbor, the first ? can be any of 3, and then each subsequent ? cannot equal previous, so total 3 * 2^(L-1). Similarly, if there is a left neighbor fixed to a, then the first ? must not equal a, so 2 choices, and then subsequent same as before, giving 2 * 2^(L-1) = 2^L? Wait careful: For L ?'s with left neighbor fixed to a, and no right neighbor (i.e., at end) the number of colorings for the L positions: first ? cannot equal a -> 2 choices; for each next, cannot equal previous -> 2 choices; total = 2 * 2^(L-1) = 2^L. But is that correct? Check: Example: L=1, left neighbor fixed a, right free (since it's the end) => the single ? can be any of 2 colors != a, so 2 ways = 2^1=2. Good. For L=2: left fixed a, then two ?'s, and no constraint on last with right (since end). First ?: not a -> 2 choices. Second ?: not the color of first -> 2 choices. Total = 4 = 2^2. That matches.
If there is both left and right neighbors fixed: left = a, right = b, block length L. Then we need number of sequences of length L such that first != a, last != b, and consecutive differ. That's like counting proper colorings of a path with fixed endpoints. This can be computed via DP or matrix exponentiation. There is formula: For L=0, if a != b? Actually if block length 0, then we have direct adjacency of fixed colors a and b; they must be different for overall validity; else 0. For L>=1, the number depends on whether a == b or not.
We can derive: For a path of length L+2 (including the two fixed endpoints), the number of colorings of the internal L vertices with 3 colors, given endpoints colors a and b, subject to adjacency constraints. This is a classic problem: Number of proper colorings of a path with given endpoints.
We can compute using DP: Let f0 = 1 if we are at start? Actually, easier: set dp0[color] = 1 if color allowed for first ? based on left neighbor? But we can compute quickly.
But again DP over whole string is easier than splitting into blocks, as it automatically handles everything.
Thus go with DP.
Now one more nuance: The DP we described counts all assignments, but we need to ensure that the initial painted colors are not changed. Our DP only allows at each position either all colors if '?' or only the fixed color. That's correct.
Thus answer is straightforward.
But wait: The problem might have a twist: It asks "at least two ways". Could there be a scenario where count is 0? Yes. So output No.
Now test some tricky cases:
Case: n=2, s="?C". DP: i0: '?' => [1,1,1]; i1: fixed C (0): new_dp0 = sum!=0 = dp1+dp2 = 1+1=2 => total=2 => Yes.
Intuitively: first ? can be M or Y? Actually first ? cannot be C? Wait, adjacency: first segment ? can be any of 3, second is C. Only restriction: they must be different. So first ? can be M or Y (2 ways). So total 2 => Yes.
Case: n=2, s="C?": as above total=2 => Yes.
Case: n=2, s="??": total=6 => Yes.
Thus for n=2 any string with at least one '?' and no invalid fixed adjacency gives at least 2 ways? Actually "?C" gives 2 ways, "C?" gives 2, "??" gives 6, "?M" similar. Only if both fixed and they are different (like "CM") then exactly 1. If they are same then 0.
Thus answer Yes for many.
But for longer strings, there may be forced uniqueness.
Now I'll implement.
But I also want to consider if there is any scenario where DP yields count=1 but we might erroneously think it's 0 or >1. Double-check with "C?M" we got total=1? Let's compute with DP: n=3, s="C?M". i0:C -> [1,0,0]; i1:? -> compute new: c0: sum!=0 = dp1+dp2 =0; c1: sum!=1 = dp0+dp2 =1; c2: sum!=2 = dp0+dp1 =1 => dp=[0,1,1]; i2: fixed M (index 1) -> new_dp1 = sum!=1 = dp0+dp2 =0+1=1 => total=1. Good.
Now "C?Y": total=1.
Now "C?C?M"? Let's test quickly: n=5, "C?C?M". We suspect maybe 2? Let's compute: i0:C -> [1,0,0]; i1:? -> dp=[0,1,1]; i2:C -> new_dp0 = sum!=0 = dp1+dp2 =1+1=2 => dp=[2,0,0]; i3:? -> allowed all: c0: sum!=0=dp1+dp2=0; c1: sum!=1=dp0+dp2=2+0=2; c2: sum!=2=dp0+dp1=2+0=2 => dp=[0,2,2]; i4:M (index1): new_dp1 = sum!=1 = dp0+dp2 =0+2=2 => total=2 => Yes. So not forced.
Now "C?M?C": n=5. i0:C->[1,0,0]; i1:? -> [0,1,1]; i2:M (1) -> new_dp1 = sum!=1 = dp0+dp2 =0+1=1 => dp=[0,1,0]; i3:? -> allowed all: c0: sum!=0 = dp1+dp2 =1+0=1; c1: sum!=1 = dp0+dp2 =0+0=0; c2: sum!=2 = dp0+dp1 =0+1=1 => dp=[1,0,1]; i4:C (0) -> new_dp0 = sum!=0 = dp1+dp2 =0+1=1 => total=1. So exactly one. Check if that is plausible: The forced assignments: C ? M ? C. We need to fill positions 1 and 3. Constraints: position1 != C and != M? Actually adjacent: pos1 adjacent to C (pos0) and M (pos2). So pos1 cannot be C or M, so must be Y. Then pos3 adjacent to M (pos2) and C (pos4). So pos3 cannot be M or C, so must be Y. So unique: C Y M Y C. So indeed 1 way. So DP gave 1.
Thus DP works.
Now confirm that DP works even when there are multiple '?' and fixed colors leading to exactly one.
Now, we need to output "Yes"/"No" exactly as per samples.
Case sensitivity: They say you can print in any case. So "Yes" or "yes" is fine, but usually output exactly "Yes" or "No" (capitalized). We'll use "Yes"/"No".
Now implement.
But note: input might have newline etc. We'll just use input().
Now code:
def solve():
import sys
data = sys.stdin.read().strip().split()
if not data:
return
n = int(data[0])
s = data[1].strip()
col = {'C':0, 'M':1, 'Y':2}
dp = [0,0,0]
if s[0] == '?':
dp = [1,1,1]
else:
dp[col[s[0]]] = 1
for i in range(1, n):
ch = s[i]
new = [0,0,0]
if ch == '?':
allowed = [0,1,2]
else:
allowed = [col[ch]]
for c in allowed:
# sum over previous colors not equal to c
# we can compute by total_prev - dp[c] but careful if c not in range
total = 0
for d in range(3):
if d != c:
total += dp[d]
new[c] = total
dp = new
total = sum(dp)
if total >= 2:
print("Yes")
else:
print("No")
That should work.
But we can also early check for adjacency conflict: For any i, if s[i]!='?' and s[i-1]!='?' and s[i]==s[i-1], then answer is No (0 ways). However DP will yield 0, but early exit might save a tiny amount. But not necessary.
We also need to be careful about n=0? Not possible.
Now test with provided examples:
1: Yes, 2: Yes, 3: Yes, 4: No, 5: No.
All correct.
Now is there any case where DP might produce overflow? Not in Python.
Thus final solution.
But perhaps we could simplify further by noticing that the number of completions can be derived from the number of forced positions. But DP is safe.
Edge case: if the string contains a '?' that is adjacent to two fixed same colors on both sides? Actually that may force uniqueness? For example "C?C" we saw yields 2 possibilities, not forced. Because for middle ?: cannot be C, but can be M or Y, so 2. So not forced.
Now think about uniqueness condition: For a proper 3-coloring of a path with some vertices precolored, the coloring is unique if and only if for each maximal run of consecutive '?' (including possibly at ends), the number of completions for that run is exactly 1, and the product of all runs is 1. That happens when each run contributes exactly 1. When does a run contribute 1? Let's analyze:
Consider a run of '?' of length L, with left neighbor color a (if exists) and right neighbor color b (if exists). The number of valid assignments to these L positions (with constraints: for the first: if left exists, cannot be a; for internal adjacent differ; for last: if right exists, cannot be b) is:
We can think of it as counting paths of length L+1 (edges) in a complete graph K3 (colors) with constraints on starting and ending colors: start color (first ?) cannot equal a (if left exists) and end color (last ?) cannot equal b (if right exists), and each step must change color (since adjacent cannot be same). Actually the condition that consecutive differ means that we walk on the graph where edges connect distinct colors, i.e., the state graph is a complete graph without self-loops: each state has two possible next states.
If we have left neighbor a, then the first ? can be any color != a, so 2 choices if a is defined; if no left neighbor, first ? has 3 choices.
Similarly, if we have right neighbor b, then the last ? must be != b.
So the number of valid sequences of length L is:
-
For an open end (no left neighbor): first has 3 choices; after that each step can change to either of the two other colors (2 choices each). So total = 3 * 2^(L-1) for L>=1.
-
For left neighbor only (right open): first has 2 choices; each subsequent has 2 choices; total = 2 * 2^(L-1) = 2^L.
-
For both neighbors: we need to count number of sequences of length L with colors from {0,1,2}, such that s1 != a, s_L != b, and s_i != s_{i+1} for i=1..L-1.
We can compute using recurrence or matrix exponentiation.
But we can also derive closed form: For a path with fixed endpoints, the number is:
If a == b: number = (2^L + 2*(-1)^L)/3? Something like that? Actually for proper colorings of a path with 3 colors, with endpoints fixed to specific colors, there is known formula: For a path of length n (number of vertices), the number of proper colorings with 3 colors is 3*2^{n-1} for free endpoints; for fixed endpoints, it's: if endpoints same: 2 * (2^{n-2} + (-1)^{n-1})? Hmm.
But perhaps it's easier to note that for L=1 with both neighbors: the ? must be != a and != b. So:
- if a == b: then ? can be any of the two other colors, so 2 ways.
- if a != b: then ? must be the third color (the one not a nor b), so 1 way.
So for L=1, number = 2 if a==b else 1.
For L=2 with both neighbors: positions ?1, ?2. Constraints: ?1 != a; ?2 != b; ?1 != ?2.
We can enumerate: Let colors be 0,1,2. Suppose a=0, b=0 (same). Then ?1 can be 1 or 2. For each choice of ?1, ?2 must be != ?1 and !=0. If ?1=1, then ?2 cannot be 1 or 0 => ?2=2. If ?1=2, then ?2=1. So exactly 2 ways. If a=0, b=1 (different). Then ?1 !=0, so ?1 can be 1 or 2. But we also need ?2 !=1 and ?2 !=?1.
- If ?1=1, then ?2 !=1 and !=1? Actually ?2 !=1 (b) and !=?1 (1) => ?2 cannot be 1, so ?2 must be 0 or 2? But also ?2 must be not equal to ?1 (1) and not b (1). That leaves 0 and 2, but also need to satisfy adjacency with ?1: ?2 != ?1 (1). So both 0 and 2 are allowed? However check: ?2 cannot be 1 (b) and cannot be ?1=1, same condition, so effectively cannot be 1. But also need to ensure that ?2 != ?1? Already covered (since ?1=1, ?2 can't be 1). So ?2 can be 0 or 2. But also need to satisfy future? Only two positions. So that gives 2 ways? Let's enumerate: a=0, b=1, L=2. Valid sequences of length 2: (?1,?2) such that ?1 !=0, ?2 !=1, and ?1 != ?2. List all possibilities: ?1 ∈ {1,2}. For ?1=1: ?2 can be 0 or 2 (since ?2 !=1 and ?2 !=1? Actually ?2 != b=1, also ?2 != ?1=1; both are same condition; but also must be any color? However adjacency requires ?2 != ?1, which is ?2 !=1, already satisfied. So ?2 can be 0 or 2? But check: ?2 can be 0 (different from 1) and 2 (different from 1). Both satisfy ?2 != ?1? Actually ?2=0 is not equal to 1, ok; ?2=2 is not equal to 1, ok. So both are allowed. That yields two sequences: (1,0) and (1,2). But wait, are these valid? Check adjacency: ?1=1, ?2=0 => 1≠0 ok. Also ?2=0 must be != b=1, ok. And ?1=1 != a=0, ok. So (1,0) valid. (1,2): ?2=2 !=1, ok, 1≠2, ok. So two ways. Now consider ?1=2: ?2 can be 0 or 1? But ?2 != b=1, so cannot be 1; also ?2 != ?1=2. So ?2 can be 0 (since 0≠1 and 0≠2) or maybe also 2? No 2 is equal to ?1, not allowed. So ?2=0 allowed. ?2 could be 1? No, because b=1 forbids. So only 0. Also ?2 could be? The third color is? There are only 3 colors: 0,1,2. So only 0 allowed. That gives (2,0). Check: ?1=2 !=0 ok; ?2=0 !=1 ok; 2≠0 ok. So that's a third? So we have three total? Wait, (1,0), (1,2), (2,0). That's three sequences. But are they all valid? Let's double-check (1,2) with b=1: ?2=2 !=1 ok. So yes. So total 3 ways? Let's systematically compute number of sequences for L=2, a=0, b=1. Use DP: We'll compute number of sequences of length 2 (positions 1 and 2) with constraints: first != a, second != b, and first != second. So count = sum_{c1∈{0,1,2}, c1≠a} sum_{c2∈{0,1,2}, c2≠b, c2≠c1} 1. For a=0, b=1: c1∈{1,2}. For c1=1: c2∈{0,2} (c2≠1 and c2≠1, effectively just c2≠1; also c2≠c1=1, same condition) but we need c2≠b and c2≠c1; both are same (1). So c2 can be 0 or 2. So 2 options. For c1=2: c2 must be ≠b=1 and ≠c1=2. So c2 cannot be 1 or 2, so only 0. So 1 option. Total 3. So indeed 3 ways. So for L=2, a≠b yields 3 ways, not 1. So my earlier speculation that a≠b yields forced sequence is only for L=1. For longer L, there can be multiple.
Thus uniqueness per block only occurs for certain lengths. For a block with both ends fixed, the number of completions may be 1, 2, or more. So DP is needed to compute exact count or at least check if >=2.
But we can compute each block's count using DP on that block only; but DP on whole string is simpler.
Thus we proceed.
Now, are there any pitfalls about very large counts? Python's integers are fine.
Now final solution.
But maybe there is a more clever approach: Since we only need to check if there are at least two ways, we can try to find two distinct valid colorings. We could attempt to construct two different colorings if possible. For example, we could try to find a '?' that can be assigned two different colors while still allowing completion of the rest. That might be easier: If we can find at least one '?' that has at least two possible colors that lead to a valid completion, then answer Yes, provided that there is at least one valid completion overall. However, caution: even if each '?' individually might have only one possible color in some assignments, there could be two overall assignments that differ in multiple positions, not just a single '?'. But if we can show existence of two completions, it's enough. Conversely, if we cannot find two completions, answer No. So we could try to count number of completions via DP but stop when we exceed 1. That's what we can do: run DP but cap the counts at 2, because we only care if >=2. This way we avoid big integers. Because the DP counts may get huge, but we can store min(count, 2) or something, but careful: we need to know if total >=2. However, we must ensure that the DP with capping still correctly determines whether the total is at least 2. Since we only care about the threshold, we can cap each dp entry at 2 (or any number >1) and sum with capping. But we have to be careful about propagation: When we sum dp[d] for d != c, if any of those dp[d] is capped at 2, the sum may exceed 2 even if actual sum is 1? Actually if we cap at 2, we might overestimate? But we want to know if actual sum >=2. If we cap at 2, then the computed sum may be less than or equal to actual sum? Let's think: If we cap each dp[d] at 2, then computed sum = min(actual_sum, something). Actually, suppose actual dp[d] values are large, but we cap them at 2. Then the sum of capped values might be >=2 even if actual sum is also >=2. But it might also be that actual sum is 1 but due to capping, we might get 2? Let's test: If we cap at 2, we never increase a value; we only reduce large values to 2. So the sum of capped values <= actual sum? Actually if a value is 5, capped at 2, so it becomes smaller. So sum of capped values <= actual sum. Therefore if computed sum >=2, actual sum might be >=2 (or might be less? Let's see: Suppose actual dp0 = 0, dp1 = 1, dp2 = 1 => actual sum = 2. Capped values: 0,1,1 => sum=2. So ok. If actual sum = 1, e.g., dp = [1,0,0], capped sum = 1. So if computed sum >=2, then actual sum must be at least 2? Not necessarily: Because capping reduces values, so computed sum could be less than actual sum but not more. So if computed sum is 2, actual sum could be 2 or more. But could computed sum be 2 while actual sum is 1? That would require that some dp value that is 1 in actual becomes larger after capping? But capping reduces, never increases. So actual sum must be at least computed sum. So if computed sum >=2, actual sum >=2. Conversely, if computed sum <2, actual sum might be >=2? Consider actual sum = 2 but due to capping, sum becomes less? Let's test: dp = [2,0,0] actual sum=2. Capped dp = [2,0,0] sum=2. ok. dp = [3,0,0] actual sum=3, capped sum=2. So if actual sum >=2, capped sum could be 2 (if at least one dp is >=2) or maybe 1? Could actual sum be 2 but capped sum be 1? For that to happen, the actual dp entries must be such that each is at most 1, sum=2 => that would require two entries of 1 and others 0, e.g., [1,1,0] sum=2. Capped values are [1,1,0] sum=2. So sum=2. If actual sum=2, then the sum of capped values equals actual sum because each entry ≤2, and sum=2 implies each entry is at most 2, and capped doesn't change them. So if actual sum >=2, capped sum is at least 2? Not always: actual sum could be 2 with entries like [2,0,0] -> capped sum=2; [1,1,0] -> 2; [0,0,2] -> 2. All good. So capped sum is exactly the same as actual sum when actual sum <=2, and when actual sum >2, capped sum = 2 (if any entry >=2, but careful: if we cap each entry at 2, then sum could be >2? For example, dp = [2,2,0] capped = [2,2,0] sum=4 >2. But we would then cap sum also? Actually we are interested in the sum, but we can also cap the sum at 2. However, the DP recurrence involves sums of dp entries. If we cap each dp entry at 2, then sum of capped entries could be up to 6 (if all three are 2). That sum might be >2, and then we would set new_dp[c] = min(actual_sum, 2) or we could cap new_dp at 2 as well. But to correctly propagate the threshold, we need to ensure that if the actual sum is >=2, we set the new dp entry to >=1? Actually we want to know if the final total sum is >=2. So we can implement DP where we keep values capped at 2, but also the sum operation must be capped at 2 to avoid overflow? But we need to compute new_dp[c] = sum over d != c of dp[d], and then we cap new_dp[c] at 2 as well. However, capping after sum could cause underestimation: Suppose actual sum is 2, but due to earlier capping, some dp[d] that were actually >2 got reduced, but sum of capped might still be >=2? Actually we need to guarantee that when we cap at each step, the final total will be at least 2 iff actual total is at least 2. Let's think.
Standard approach for "is number of ways >= K?" where K is small is to use DP with values clamped to K (i.e., min(value, K)). This works because addition and other operations are monotonic and we only care about whether the true count reaches K. If we clamp to K, we ensure that if the true count is >= K, the clamped value will be K (or maybe less if there is subtraction? but here only addition). However, we must be careful: When we compute sum, we add clamped values, but the true sum may be larger than the sum of clamped values. But if we then clamp the result to K again, we may lose the fact that the true sum reached K. Example: Suppose we have dp values that are true counts 3 and 0. Clamped to 2 and 0 => sum = 2, clamp to 2 => we keep 2. That's fine because true sum is 3 >=2, and clamped sum is 2, which indicates >=2. However, if we have true counts 1 and 1: clamped 1 and 1 => sum = 2, clamp to 2 => indicates >=2, which matches true sum =2. Good. If true counts 1 and 0: clamped 1 and 0 => sum=1 <2, indicates not enough. Good. So seems clamping works. But is there a scenario where true sum is >=2 but the sum of clamped values is less than 2? For that to happen, the true sum must be at least 2, but each clamped value is at most 2, and the sum of clamped values could be less than 2 if the true values are fractional? Not possible. Since true values are integers, and clamped values are min(true, K). For sum of min(true_i, K) to be less than 2 when true sum >=2, we would need that at least one true_i > K but the sum of others is small such that the sum of min values < K. Example: K=2. Suppose we have two dp entries: true1=3, true2=0 => min(3,2)=2, min(0,2)=0, sum=2, which is >=2. Another: true1=2, true2=0 => sum=2. true1=1, true2=1 => sum=2. true1=1, true2=0 => sum=1. To have true sum >=2 but clamped sum <2, we would need the true sum to be composed of a single large value >2, but its clamped value is 2, sum=2 at least. Actually if there is a single value >=2, clamped to 2 gives sum>=2. If true sum >=2 but no single entry >=2, then we must have at least two entries each >=1, so at least two entries with true >=1 => clamped at least 1 each, sum at least 2. So clamped sum will be at least 2. So indeed, for nonnegative integers, sum(min(true_i,2)) >= min(true_sum, 2)? Actually it's known that if we cap each term at 2, the sum of capped terms is at least min(total, 2) because if total >=2, there are either one term >=2 (capped at 2) giving sum >=2, or at least two terms each >=1 (capped at least 1) giving sum >=2. More formally: Let total = Σ true_i. If total >= 2, then either there exists i such that true_i >= 2 => min(true_i,2) = 2 => sum >=2, or all true_i <= 1, then since total >=2, there are at least 2 terms with true_i = 1, each contributes 1 => sum >=2. So indeed, sum(min(true_i,2)) >= min(total,2). So clamped sum is an upper bound? Actually it's a lower bound? Wait, we have: min(true_i,2) <= true_i, so sum(min) <= sum(true). So sum(min) is less than or equal to true sum. But we need to ensure that if true sum >=2 then sum(min) >=2? As argued, it holds: if true sum >=2, then either some true_i >=2 => min_i=2 => sum >=2; or all true_i <=1, then need at least two 1's => sum >=2. So yes, sum(min) >= min(true,2). Actually sum(min) could be exactly 2 when true sum=3 (e.g., 3+0 -> min:2+0=2) which is >=2. So sum(min) is always >= min(true,2) and <= true. That means if true sum >=2, sum(min) >=2; if true sum <2, sum(min) = true sum (since all <2). So by clamping each DP entry to 2, and then computing sums (and then also clamping the new entry to 2), we can correctly determine whether the true count is >=2. Because after each step we will have values that are either 0,1,2 where 2 means "at least 2". Then at the end, the total sum (which might be >2) we can cap at 2 as well: if total >=2, output Yes; else No.
But we must also consider that DP uses sums of previous dp entries (excluding current color). The true new_dp[c] = Σ_{d != c} true_dp[d]. If we have clamped dp[d] values as c_d = min(true_dp[d], 2). Then we compute sum_c = Σ_{d != c} c_d. Then we set new_c = min(sum_c, 2). This new_c is an approximation. We need to ensure that if true_new_dp[c] >= 2 then new_c = 2, and if true_new_dp[c] < 2 then new_c = true_new_dp[c]. Let's verify.
Let true_dp[d] be nonnegative integers. Let c_d = min(true_dp[d],2). True sum S = Σ_{d != c} true_dp[d]. Approx sum S' = Σ_{d != c} c_d.
We know S' <= S. Also, as argued, if S >= 2 then S' >= 2? Not necessarily? The set of d != c is a subset of {0,1,2} of size 2 (since we exclude exactly one color). Actually there are two d's (since total 3 colors, excluding one). So there are exactly two terms in the sum. If S >= 2, could it be that S' < 2? Let's test. Suppose the two true values are, say, true_d1 = 3, true_d2 = 0. Then c_d1 = 2, c_d2 = 0, S' = 2. So >=2. Suppose true_d1 = 2, true_d2 = 0 => S' = 2. Suppose true_d1 = 1, true_d2 = 1 => S' = 2. Suppose true_d1 = 1, true_d2 = 0 => S=1, S'=1. Suppose true_d1 = 1, true_d2 = 2? Actually 2 is >=2, so c=2, S'=3? But capped at 2? Wait S' sum of two numbers each <=2, max sum =4. But we will later clamp new_c to 2. So S' could be 3 or 4. That's fine; after clamping to 2, we set new_c=2. So if S >=2, we want new_c to be at least 2 (or exactly 2 after clamping). But is it possible that S >=2 yet S' < 2? For S' to be <2, both c_d must be <=1 and sum <2. That would require both true_dp[d] <=1 and at most one of them is 1. So possibilities: (0,0) -> S=0; (0,1) -> S=1; (1,1) -> S=2 but S'=2. So (0,1) gives S=1, not >=2. (1,0) same. So if S >=2, the only way both true values <=1 is if they are (1,1) which gives S'=2. So S' >=2. So indeed if S >=2 then S' >=2. So after clamping new_c = min(S',2), we get new_c = 2 if S >=2; if S = 1, then S' = 1 => new_c = 1; if S = 0 => 0. So the clamped DP exactly captures whether the true count is 0,1, or >=2 (represented as 2). Moreover, the recurrence using clamped values yields the same categorization: each dp entry is 0,1,2 where 2 means "at least 2". So we can run DP with values capped at 2. That's efficient and avoids big integers.
Thus we can implement DP with integers, but after each sum we set new_dp[c] = min(total, 2). And also we can cap dp entries at 2 at each step.
Given n ≤ 100, this is trivial.
But we also need to check if there are any invalid fixed adjacency: DP with clamping will also produce 0 if impossible.
Thus we can implement:
dp = [0,0,0]
if s[0]=='?': dp = [1