Problem:


Score : 400 points

Problem Statement

We have a board with a 2 \times N grid.
Snuke covered the board with N dominoes without overlaps.
Here, a domino can cover a 1 \times 2 or 2 \times 1 square.

Then, Snuke decided to paint these dominoes using three colors: red, cyan and green.
Two dominoes that are adjacent by side should be painted by different colors.
Here, it is not always necessary to use all three colors.

Find the number of such ways to paint the dominoes, modulo 1000000007.

The arrangement of the dominoes is given to you as two strings S_1 and S_2 in the following manner:

Each domino is represented by a different English letter (lowercase or uppercase).

The j-th character in S_i represents the domino that occupies the square at the i-th row from the top and j-th column from the left.

Constraints

1 \leq N \leq 52

|S_1| = |S_2| = N

S_1 and S_2 consist of lowercase and uppercase English letters.

S_1 and S_2 represent a valid arrangement of dominoes.

Input

Input is given from Standard Input in the following format:

N
S_1
S_2

Output

Print the number of such ways to paint the dominoes, modulo 1000000007.

Sample Input 1

3
aab
ccb

Sample Output 1

6

There are six ways as shown below:

Sample Input 2

1
Z
Z

Sample Output 2

3

Note that it is not always necessary to use all the colors.

Sample Input 3

52
RvvttdWIyyPPQFFZZssffEEkkaSSDKqcibbeYrhAljCCGGJppHHn
RLLwwdWIxxNNQUUXXVVMMooBBaggDKqcimmeYrhAljOOTTJuuzzn

Sample Output 3

958681902



Sample input:
3
aab
ccb


Sample output:
6

Submission status: Accepted

Solution code:
n = int(input())
s = input()
mod = 1000000007

if n == 1:
    ans = 3
else:
    i = 1
    if s[0] == s[1]:
        ans = 6
        c = 2
        i += 1
    else:
        c = 1
        ans = 3

    while i < n-1:
        if c == 1:
            if s[i] == s[i+1]:
                c = 2
                i += 1
                ans *= 2
                ans %= mod
            else:
                c = 1
                ans *= 2
                ans %= mod
        elif c == 2:
            if s[i] == s[i+1]:
                c = 2
                i += 1
                ans *= 3
                ans %= mod
            else:
                c = 1
        else:
            if s[i] == s[i+1]:
                c = 2
                i += 1
            else:
                c = 1
        i += 1
    if s[-1] != s[-2]:
        if n >= 3:
            if s[-2] != s[-3]:
                ans *= 2
                ans %= mod
        else:
            ans *= 2
            ans %= mod
print(ans%mod)

Submission status: Accepted

Solution code:
n = int(input())
s = [list(input()) for _ in range(2)]

mod = 10 ** 9 + 7
res = 1
flag = 0
skip = False
for i in range(n):
    if s[0][i] == s[1][i]:
        if flag == 0:
            res = res * 3 % mod
        elif flag == 1:
            res = res * 2 % mod
        
        flag = 1

    else:
        if skip:
            skip = False
            continue

        if flag == 0:
            res = res * 6 % mod
        elif flag == 1:
            res = res * 2 % mod
        else:
            res = res * 3 % mod
        
        flag = 2
        skip = True

print(res)

Submission status: Accepted

Solution code:
n=int(input())
mod=10**9+7

s1=input()
s2=input()

if n==1:
    print(3)
    exit(0)

if s1[0]==s1[1]:
    l=1
    ans=6
    i=2
else:
    l=0
    ans=3
    i=1

while i<n:
    if i==n-1:
        if l==0:
            ans*=2
            ans%=mod
        break

    if s1[i+1]==s1[i]:
        c=1
        i+=2
    else:
        c=0
        i+=1
    
    if l==0:
        ans*=2
    if l==1 and c==1:
        ans*=3
    
    ans%=mod
    
    l=c
    
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
S1 = input()
S2 = input()

def prepare(s1,s2,n):
    result = []
    i = 0
    while i < n:
        if s1[i] == s2[i]:
            result.append(1)
            i += 1
        else:
            result.append(0)
            i += 2

    return result



def calculate(arr):
    ans = 1
    for index in range(len(arr)):
        if index == 0:
            if arr[index] == 0:
                ans = 6
            else:
                ans = 3
            continue
        #xo
        if (arr[index - 1] == 1) and (arr[index] == 0):
            ans *= 2

        #xx
        if (arr[index - 1] == 1) and (arr[index] == 1):
            ans *= 2

        #oo
        if (arr[index - 1] == 0) and (arr[index] == 0):
            ans *= 3

        #ox
        if (arr[index - 1] == 0) and (arr[index] == 1):
            ans *= 1

    print(ans % 1000000007)



arr = prepare(S1,S2,N)
calculate(arr)

Submission status: Accepted

Solution code:
MOD = 10**9 + 7

N = input()
S1 = list(input())
S2 = list(input())

res = 1
right_used_color = 0
while len(S1) > 0:
    if S1[len(S1)-1] == S2[len(S1)-1]:
        res = res * (3 - right_used_color) % MOD
        right_used_color = 1
    elif right_used_color == 2:
        res = res * 3 % MOD
        S1.pop()
        S2.pop()
    else:
        res = res * (3 - right_used_color) * (2 - right_used_color) % MOD
        right_used_color = 2
        S1.pop()
        S2.pop()
    S1.pop()
    S2.pop()

print(res)

Submission status: Accepted

Solution code:
n = int(input())
a = input()
b = input()
ans = 1
i = 0
wari = 1000000007
if n == 1:
    print(3)
    exit()
elif n == 2:
    print(6)
    exit()
else:
    if a[i] == b[i]:
        ans *=3
        i +=1
        
    else:
        i +=2
        ans *=6
        
    while True:
        if i >= n:
            break
        if a[i-1] == b[i-1]:
            if a[i] == b[i]:
                ans*=2
                ans%=wari
                i+=1
            else:
                ans*=2
                ans%=wari
                i+=2
        else:
            if a[i] == b[i]:
                ans*=1
                ans%=wari
                i+=1
            else:
                ans*=3
                ans%=wari
                i+=2
    print(ans)

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    n = int(readline())
    s1 = input()
    s2 = input()

    if n == 1:
        print(3)
        return

    ans = 3 * 2

    for i in range(2, n):
        if s1[i-1] == s2[i-1]:
            ans *= 2
        else:
            if s1[i-1] == s1[i-2]:
                if s1[i] == s2[i]:
                    ans *= 1
                else:
                    ans *= 3
        ans %= MOD

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
s = [list(input()) for i in range(2)]
mod = 1000000007


if s[0][0] == s[1][0]:
    now = 1
    ans = 3
    v = True
else:
    now = 2
    ans = 6
    v = False

while now < n:
    if s[0][now] == s[1][now] and v:
        # タテ　タテ
        ans = (ans*2)%mod
        now+=1
        v = True
    elif s[0][now] == s[1][now]:
        # ヨコ　タテ
        ans = (ans*1)%mod
        now+=1
        v = True
    elif s[0][now] != s[1][now] and v:
        # タテ ヨコ
        ans = (ans*2)%mod
        now+=2
        v = False
    else:
        # ヨコ　ヨコ
        ans = (ans*3)%mod
        now+=2
        v = False
print(ans)

Submission status: Accepted

Solution code:
MOD=10**9+7
N=int(input())
S1=input()
S2=input()

if N==1:
  print(3)
  exit()

if S1[0]==S2[0]:
  ans=3
  i=1
else:
  ans=6
  i=2

while i<N:
  if S1[i]==S2[i]:
    if S1[i-1]==S2[i-1]:
      ans=ans*2%MOD
    i+=1
  else:
    if S1[i-1]==S2[i-1]:
      ans=ans*2%MOD
    else:
      ans=ans*3%MOD
    i+=2
    
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys
import collections
from decimal import Decimal # 10進数で考慮できる

mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000

d = collections.deque()
def LI(): return list(map(int, sys.stdin.readline().split()))

N = int(input())
S_1 = str(input())
S_2 = str(input())

dominos = []
i = 0
while i < N:
    if S_1[i] == S_2[i]:
        dominos.append(1)
        i += 1
    else:
        i += 2
        dominos.append(2)
ans = 1
for i, domino in enumerate(dominos):
    if i == 0:
        if dominos[i] == 1:
            ans *= 3
        else:
            ans *= 6
    else:
        if dominos[i] == dominos[i - 1] == 1 or dominos[i-1] == 1 and dominos[i] == 2:
            ans *= 2
            ans = ans % mod
        elif dominos[i] == dominos[i - 1] == 2:
            ans *= 3
            ans = ans % mod

print(ans)

Submission status: Accepted

Solution code:
N=int(input())
S1=input()
S2=input()
mod=10**9+7
dp=[]
a=0
for i in range(N):
  if i!=N-1:
    if a==1:
      a=0
      continue
    else:
      if S1[i]==S1[i+1]:
        dp.append(2)
        a=1
      else:
        dp.append(1)
  else: 
    if a==0:
      dp.append(1)
ans=1
if len(dp)==1:
  if dp[0]==1:
    print(3)
  else:
    print(6)
  exit()
for i in range(len(dp)):
  if i==0:
    if dp[i]==1:
      ans*=3
    else:
      ans*=6
  else:
    if dp[i-1]==2:
      if dp[i]==1:
        continue
      else:
        ans*=3
    else:
      if dp[i]==1:
        ans*=2
      else:
        ans*=2
  ans%=mod
print(ans%mod)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10

N = INT()
S1 = input()
S2 = input()

if 1 < N and S1[0] == S1[1]:
	ans = 6
	tmp = 2
	flg = 1
else:
	ans = 3
	tmp = 1
	flg = 0


while tmp < N:
	if tmp < N-1 and S1[tmp] == S1[tmp+1]:
		if flg:
			ans *= 3
		else:
			ans *= 2
		flg = 1
		tmp += 2

	else:
		if flg:
			ans *= 1
		else:
			ans *= 2
		flg = 0
		tmp += 1
	ans %= mod


print(ans)

Submission status: Accepted

Solution code:
N,S1,S2 = open(0).read().split()
N = int(N)
m = 1000000007
if N == 1:
    print(3)
else:
    if S1[0] == S1[1]:
        ans = 6
        count = 2
        state = 'h'
    else:
        ans = 3
        count = 1
        state = 'v'
    while count < N - 1:
        if S1[count] == S1[count+1]:
            if state == 'h':
                ans = (ans*3) % m
            else:
                ans = (ans*2) % m
                state = 'h'
            count += 2
        else:
            if state == 'h':
                state = 'v'
            else:
                ans = (ans*2) % m
            count += 1
    if count == N - 1:
        if state == 'v':
            ans = (ans*2) % m
    print(ans)

Submission status: Accepted

Solution code:
def solve():
    MOD = 1000000007

    N = int(input())
    S1 = input()
    S2 = input()

    patterns = []

    i = 0
    while i < N:
        if S1[i] == S2[i]:
            patterns.append(0)
            i += 1
        else:
            patterns.append(1)
            i += 2
    
    ans = 1
    for i in range(len(patterns)):
        c = 0
        if i == 0:
            if patterns[i] == 0:
                c = 3
            else:
                c = 6
            
            ans *= c
            ans %= MOD
            continue

        if patterns[i] == 0:
            if patterns[i-1] == 0:
                c = 2
            else:
                c = 1
        else:
            if patterns[i-1] == 1:
                c = 3
            else:
                c = 2
        
        ans *= c
        ans %= MOD
    
    print(ans)
    
if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
n=int(input())
s1=input()
s2=input()
mod=10**9+7

if s1[0]==s2[0]:
    ans=3
    i=1
    flag=0
else:
    ans=6
    i=2
    flag=1

while i<n:
    if flag==0:
        if s1[i]==s2[i]:
            ans*=2
            i+=1
        else:
            ans*=2
            i+=2
            flag=1
    else:
        if s1[i]==s2[i]:
            i+=1
            flag=0
        else:
            ans*=3
            i+=2
    ans%=mod
print(ans)

Submission status: Accepted

Solution code:
MOD = 1000000007
N = int(input())
s1 = input().strip()
s2 = input().strip()
ans = 1
i = 0
pi = -1
while i < N:
    if s1[i] != s2[i]:
        if i == 0:
            ans *= 6
        else:
            if s1[pi] != s2[pi]:
                ans *= 3
            else:
                ans *= 2
        pi = i
        i += 2
    else:
        if i == 0:
            ans *= 3
        else:
            if s1[pi] != s2[pi]:
                ans *= 1
            else:
                ans *= 2
        pi = i
        i += 1
    ans = ans % MOD

print(ans)

Submission status: Accepted

Solution code:
n = int(input())
s1 = input()
s2 = input()
mod = 10**9+7
def tate(i, s1, s2):
    return s1[i] == s2[i]

ans = 1
for i in range(n-1):
    if s1[i] == s1[i+1]:
        continue
    cur_tate = tate(i, s1, s2)
    nex_tate = tate(i+1, s1, s2)
    if cur_tate and nex_tate:
        ans *= 2
    elif cur_tate and not nex_tate:
        ans *= 2
    elif not cur_tate and not nex_tate:
        ans *= 3
    else:
        continue
    ans %= mod

if tate(0, s1, s2):
    print(3*ans%mod)
else:
    print(6*ans%mod)

Submission status: Accepted

Solution code:
N = int(input())
S1 = input()
S2 = input()

m = 1000000007

if S1[0] == S2[0]:
    result = 3
else:
    result = 6
x = 0
W = len(S1)
while x < W:
    if S1[x] == S2[x]:
        if x + 1 == W:
            break
        result *= 2
        result %= m
        x += 1
    else:
        if x + 2 == W:
            break
        if S1[x + 2] != S2[x + 2]:
            result *= 3
            result %= m
        x += 2
print(result)

Submission status: Accepted

Solution code:
n = int(input())
s1 = input()
s2 = input()
mod = 1000000007
dp = [0]*n
dp[0] = 3 if s1[0] == s2[0] else 6
for i in range(1,n):
    if s1[i] == s1[i-1]: dp[i] = dp[i-1]
    elif s1[i-1] == s2[i-1]: dp[i] = dp[i-1]*2%mod
    elif s1[i] == s2[i]: dp[i] = dp[i-1]
    else: dp[i] = dp[i-1]*3%mod
print(dp[n-1])

Submission status: Accepted

Solution code:
MOD = 1000000007

n = int(input())
s1 = input()
s2 = input()


def tiles(s1, s2):
    t = []
    c1p, c2p = None, None
    for c1, c2 in zip(s1, s2):
        if c1 == c2:
            t.append(1)
        elif c1 != c1p and c2 != c2p:
            t.append(2)
        c1p, c2p = c1, c2
    return t


def solve(s1, s2):
    ncolor = 1
    t = tiles(s1, s2)

    prev = None
    ncolor = 1
    for ti in t:
        if prev is None:
            if ti == 1:
                ncolor *= 3
            if ti == 2:
                ncolor *= 6
        if prev == 1:
            if ti == 1:
                ncolor *= 2
            if ti == 2:
                ncolor *= 2
        if prev == 2:
            if ti == 1:
                ncolor *= 1
            if ti == 2:
                ncolor *= 3
        ncolor %= MOD
        prev = ti

    return ncolor


answer = solve(s1, s2)
print(answer)

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    s = input()
    t = input()
    mod = 10 ** 9 + 7

    p = {"||": 2, "==": 3, "|=": 2, "=|": 1, "|": 3, "=": 6}
    ans = 1
    bf = ""
    it = iter(range(n))
    for i in it:
        if s[i] == t[i]:
            nw = "|"
        else:
            nw = "="
            it.__next__()

        ans *= p[bf + nw]
        ans %= mod
        bf = nw

    print(ans % mod)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    s = input()
    t = input()
    mod = 10 ** 9 + 7

    p = {"||": 2, "==": 3, "|=": 2, "=|": 1, "|": 3, "=": 6}
    ans = 1
    bf = ""
    it = iter(range(n))
    for i in it:
        if s[i] == t[i]:
            nw = "|"
        else:
            nw = "="
            it.__next__()

        ans *= p[bf + nw]
        bf = nw

    print(ans % mod)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n = int(input())
# s = [list(input()) for _ in range(2)]
s1 = input()
s2 = input()

MOD = 10 ** 9 + 7

i = 0
pattern = 0
res = 1
while i < n:
    if s1[i] == s2[i]:
        i += 1
        res *= (3 - pattern)
        pattern = 1
    else:
        i += 2
        if pattern == 1:
            res *= 2
        elif pattern == 2:
            res *= 3
        else:
            res *= 6
        pattern = 2
    res %= MOD

res %= MOD
print(res)

Submission status: Accepted

Solution code:
def resolve():
    N = int(input())
    S = [list(input()) for _ in range(2)]
    i = 0
    ans = 1
    prev_color = 0
    while i < N:
        if S[0][i] == S[1][i]:
            ans *= 3 - prev_color
            prev_color = 1
            i += 1
        else:
            if prev_color == 0:
                ans *= 6
            elif prev_color == 1:
                ans *= 2
            else:
                ans *= 3 
            prev_color = 2
            i += 2
    print(ans%(10**9+7))
    


        

if '__main__' == __name__:
    resolve()

Submission status: Accepted

Solution code:
from collections import deque
def main():
    n = int(input())
    S1 = deque(list(input()))
    S2 = deque(list(input()))
    mod = 1000000007
    A = []
    while S1:
        s1 = S1.popleft()
        s2 = S2.popleft()
        if s1 == s2:
            A.append(0)
        else:
            S1.popleft()
            S2.popleft()
            A.append(1)
    if A[0] == 0:
        ans = 3
    else:
        ans = 6
    for i in range(1, len(A)):
        if A[i] == 0:
            if A[i - 1] == 0:
                ans = ans * 2 % mod
            else:
                pass
        else:
            if A[i - 1] == 0:
                ans = ans * 2 % mod
            else:
                ans = ans * 3 % mod
    print(ans)



if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
N = int(input())
S1 = input()
S2 = input()
count = 1

if(S1[0] == S2[0]):
  ans= 3
else:
  ans= 6
  count+= 1

while count < N:
  if(S1[count] == S2[count]):
    if(S1[count- 1] == S2[count- 1]):
      ans*= 2
      count+= 1
    else:
      count+= 1
  else:
    if(S1[count- 1] == S2[count- 1]):
      ans*= 2
      count+= 2
    else:
      ans*= 3
      count+= 2
      
print(ans% (10** 9+ 7))

Submission status: Accepted

Solution code:
MOD=10**9+7
N=int(input())
S=[list(input()) for i in range(2)]

l=[]
i=0
while(i<N):
    if S[0][i]==S[1][i]:
        l.append(1)
        i+=1
    else:
        l.append(2)
        i+=2
n=len(l)
dp=[0]*n
dp[0]=3 if l[0]==1 else 6
for i in range(1,n):
    if l[i-1]==1 and l[i]==1:
        dp[i]=dp[i-1]*2%MOD
    elif l[i-1]==1 and l[i]==2:
        dp[i]=dp[i-1]*2%MOD
    elif l[i-1]==2 and l[i]==1:
        dp[i]=dp[i-1]
    else:
        dp[i]=dp[i-1]*3%MOD
print(dp[n-1])

Submission status: Accepted

Solution code:
MOD = 10**9 + 7
def main():
  N = int(input())
  S1 =str(input())
  S2 = str(input())
  if N > 1 and S1[0] == S1[1]:
      ans = 6
  else:
    ans = 3
  flag = False
  for i in range(N-1):
    if S1[i] == S1[i+1]:
      flag = True
      continue
    else:
      if flag:
        if i+2 < N:
          if S1[i+1] == S1[i+2]:
            ans *= 3
            ans %= MOD
        flag = False
      else:
        ans *= 2
        ans %= MOD
  print(ans)
if __name__ == "__main__":
  main()

Submission status: Accepted

Solution code:
n = int(input())
s1 = list(input())
s2 = list(input())
mod = int(1e9+7)

def ranl(lst):
    ans = []
    cnt = 1
    ini = lst[0]
    for i in range(1, len(lst)):
        if ini == lst[i]:
            cnt += 1
        else:
            ans.append((ini, cnt))
            cnt = 1
            ini = lst[i]
    ans.append((ini, cnt))
    return ans

lst = ranl(s1)
ans = 1
if lst[0][1] == 1:
    ans *= 3
else:
    ans *= 6

for i in range(1, len(lst)):
    if lst[i-1][1] == 1 and lst[i][1] == 1:
        ans *= 2
        ans %= mod
    elif lst[i-1][1] == 1 and lst[i][1] == 2:
        ans *= 2
        ans %= mod
    elif lst[i-1][1] == 2 and lst[i][1] == 1:
        ans *= 1
    else:
        ans *= 3
        ans %= mod
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3

import sys
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
# import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1             # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n = ii()
    up = input()
    bottom = input()
    standing = []
    i = 0
    while i < n:
        if up[i] == bottom[i]:
            standing.append(True)
        else:
            standing.append(False)
            i += 1
        i += 1
    # print(standing)
    ans = 1
    for i in range(len(standing)):
        if i == 0:
            if standing[i]:
                ans *= 3
            else:
                ans *= 6
        elif standing[i]:
            if standing[i-1]:
                ans = (ans * 2) % mod
            else:
                continue
        else:
            if standing[i-1]:
                ans = (ans * 2) % mod
            else:
                ans = (ans * 3) % mod
    print(ans)



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
MOD=10**9+7
N = int(input())
s1 = list(input())
s2 = list(input())
pre = s1[0] == s2[0]
if s1[0] == s2[0]:
    ans = 3
    idx = 1

else:
    ans = 6
    idx = 2
while idx < N:
    if pre:
        ans *= 2
    else:
        if s1[idx] != s2[idx]:
            ans *= 3

    pre=s1[idx] == s2[idx]
    if s1[idx] == s2[idx]:
        idx += 1
    else:
        idx += 2

print(ans%MOD)

Submission status: Accepted

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

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

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
from collections import defaultdict
from collections import deque
from functools import lru_cache


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

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

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

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)


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

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

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

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

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

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

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

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n -1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n:
    return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

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

N = I()
S = S()

B = []
prev = None
Hold = False
for s in S:
  if Hold:
    if s == prev:
      B.append(2)
      Hold = False
    else:
      B.append(1)
  else:
    Hold = True
  prev = s
if Hold:
  B.append(1)

ans = 1
prev = None
for b in B:
  if b == 1:
    if prev == None:
      ans = 3
    elif prev == 1:
      ans *= 2
      ans %= MOD
  else:
    if prev == None:
      ans = 6
    elif prev == 1:
      ans *= 2
      ans %= MOD
    else:
      ans *= 3
      ans %= MOD
  prev = b
print(ans)

Submission status: Accepted

Solution code:
import collections
N = int(input())
S = input()
_ = input()

c = collections.Counter(S)
instant = []
i = 0
while i < N:
    if c[S[i]] == 2:
        instant.append(2)
        i += 2
    else:
        instant.append(1)
        i += 1


if instant[0] == 2:
    ans = 6
else:
    ans = 3

for i in range(1, len(instant)):
    if instant[i-1] == 1:
        ans *= 2
    elif instant[i] == 2:
        ans *= 3

print(ans % (10 ** 9 + 7))

Submission status: Accepted

Solution code:
#dpでできないかな？
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

n=I()
s1=SI()
s2=SI()
i=0
vh=[]
while i<n:
    if s1[i]==s2[i]:
        vh.append(1)
        i+=1
    else:
        vh.append(0)
        i+=2
#print(vh)
if vh[0]==1:
    ans=3
else:
    ans=6
#print(ans)
for i in range(len(vh)-1):
    if vh[i]==1 and vh[i+1]==1:
        ans=ans*2%mod
    elif vh[i]==0 and vh[i+1]==1:
        ans=ans
    elif vh[i]==1 and vh[i+1]==0:
        ans=ans*2%mod
    else:
        ans=ans*3%mod
print(ans)

Submission status: Accepted

Solution code:
n = int(input())
sa = input()
sb = input()
p = 1000000007

sal =list(sa)
sal.append("2")
rel =[0]

for i in range(n):
    if rel[-1] ==2:
        rel.append(0)
    elif sal[i] ==sal[i+1]:
        rel.append(2)
    else:
        rel.append(1)

rell =[s for s in rel if s != 0]

if rell[0] ==2:
    res = 6
else:
    res = 3

for j in range(1,len(rell)):
    if rell[j-1] ==2 and rell[j] ==2:
        res = res*3 % p
    elif rell[j-1] ==2 and rell[j] ==1:
        pass
    else:
        res = res*2 % p

print(res)