Problem:


Score : 400 points

Problem Statement

You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7:

The string does not contain characters other than A, C, G and T.

The string does not contain AGC as a substring.

The condition above cannot be violated by swapping two adjacent characters once.

Notes

A substring of a string T is a string obtained by removing zero or more characters from the beginning and the end of T.

For example, the substrings of ATCODER include TCO, AT, CODER, ATCODER and  (the empty string), but not AC.

Constraints

3 \leq N \leq 100

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of strings of length N that satisfy the following conditions, modulo 10^9+7.

Sample Input 1

3

Sample Output 1

61

There are 4^3 = 64 strings of length 3 that do not contain characters other than A, C, G and T. Among them, only AGC, ACG and GAC violate the condition, so the answer is 64 - 3 = 61.

Sample Input 2

4

Sample Output 2

230

Sample Input 3

100

Sample Output 3

388130742

Be sure to print the number of strings modulo 10^9+7.



Sample input:
3


Sample output:
61

Submission status: Accepted

Solution code:
# でつoO(YOU PLAY WITH THE CARDS YOU'RE DEALT..)
from itertools import product
from collections import defaultdict
import sys
MOD = 10**9 + 7
def main(N):
    dp = [defaultdict(int) for _ in range(N + 1)]
    dp[0]['TTT'] = 1
    for i in range(N):
        for j in product('AGCT', repeat=3):
            jj = ''.join(j)
            if jj not in dp[i]: continue
            for k in 'AGCT':
                last4 = jj + k
                last3 = last4[1:]
                if last3 == 'AGC': continue
                if last3 == 'GAC': continue
                if last3 == 'ACG': continue
                if last4[0] == 'A' and last4[3] == 'C' and (last4[1] == 'G' or last4[2] == 'G'): continue
                dp[i + 1][last3] += dp[i][jj]
                dp[i + 1][last3] %= MOD
    ans = 0
    for j in product('AGCT', repeat=3):
        jj = ''.join(j)
        ans += dp[N][jj]
        ans %= MOD
    print(ans)

if __name__ == '__main__':
    input = sys.stdin.readline
    N = int(input())
    main(N)

Submission status: Accepted

Solution code:
N, MOD = int(input()), 10 ** 9 + 7
memo = [{} for i in range(N+1)]

def ok(last4):
    for i in range(4):
        t = list(last4)
        if i >= 1:
            t[i-1], t[i] = t[i], t[i-1]
        if ''.join(t).count('AGC') >= 1:
            return False
    return True

def dfs(cur, last3):
    if last3 in memo[cur]:
        return memo[cur][last3]
    if cur == N:
        return 1
    ret = 0
    for c in 'ACGT':
        if ok(last3 + c):
            ret = (ret + dfs(cur + 1, last3[1:] + c)) % MOD
    memo[cur][last3] = ret
    return ret

print(dfs(0, 'TTT'))

Submission status: Accepted

Solution code:
N = int(input())
dp = [[0]*64 for i in range(N-2)]
# 3進数で管理
mod = 10**9+7

d = dict()
d2 = dict()
d2[0] = 'A'
d2[1] = 'G'
d2[2] = 'C'
d2[3] = 'T'
for i in range(64):
    k = i
    ret = ''
    for j in range(3):
        ret += d2[k % 4]
        k //= 4
    d[i] = ret


for i in range(64):
    if d[i] == 'AGC' or d[i] == 'GAC' or d[i] == "ACG":
        continue

    else:
        dp[0][i] = 1


for i in range(N-3):
    for j in range(64):
        if dp[i][j] == 0:
            continue
        tmp = j // 4
        for k in range(4):
            idx = tmp + k * 16
            if d[idx] == "AGC" or d[idx] == 'ACG' or d[idx] == "GAC" or (d[j][0] == 'A' and d[j][1] == 'G' and k == 2) or (d[j][0] == 'A' and d[j][2] == 'G' and k == 2):
                #print(d[j] + d2[k])
                continue
            dp[i+1][idx] += dp[i][j]


print(sum(dp[-1]) % mod)

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 = int(input())
mod = 10**9+7

memo = [{} for _ in range(N+1)]

def ok(x, y, z, nx):
    if y=='A' and z=='G' and nx=='C':
        return False
    if x=='A' and z=='G' and nx=='C':
        return False
    if y=='G' and z=='A' and nx=='C':
        return False
    if y=='A' and z=='C' and nx=='G':
        return False
    if x=='A' and y=='G' and nx=='C':
        return False
    return True

def dfs(idx, lis):
    if idx==N:
        return 1
    x, y, z = lis
    if (x, y, z) in memo[idx]:
        return memo[idx][(x, y, z)]
    ret = 0
    for nx in ['A', 'G', 'C', 'T']:
        if ok(x, y, z, nx):
            ret += dfs(idx+1, (y, z, nx))
    memo[idx][(x, y, z)] = ret%mod
    return ret%mod

print(dfs(0, 'TTT'))

Submission status: Accepted

Solution code:
n = int(input())
dp = [[0] * 4 for i in range(n + 2)]  # dp[i][j]=(長さiの最後の文字がjで条件を満たす文字列の数:j= 0:A 1:G 2:C 3:T)
# 番兵を2つ置いておくと都合がいい
for i in range(4):
    dp[2][i] = 1
mod = 10**9 + 7
for i in range(3, n + 2):
    for j in range(4):
        for k in range(4):
            dp[i][j] += dp[i - 1][k]
    dp[i][2] -= dp[i - 2][0]  # AGCを取り除く.
    dp[i][2] -= dp[i - 2][1]  # GACを取り除く.
    dp[i][1] -= dp[i - 2][0] - dp[i - 3][1]  # ACGを取り除く. ただしGACGはすでに取り除いている.
    dp[i][2] -= 3 * dp[i - 3][0]  # すでに取り除いているものに注意する.結果的にAGGC,ATGC,AGTCを取り除く.

    for j in range(4):
        dp[i][j]%mod
print(sum(dp[-1])%mod)

Submission status: Accepted

Solution code:
n = int(input())
dp = [[0] * 4 for i in range(n + 2)]  # dp[i][j]=(長さiの最後の文字がjで条件を満たす文字列の数:j= 0:A 1:G 2:C 3:T)
# 番兵を2つ置いておくと都合がいい
for i in range(4):
    dp[2][i] = 1
mod = 10**9 + 7
for i in range(3, n + 2):
    for j in range(4):
        for k in range(4):
            dp[i][j] += dp[i - 1][k]
    dp[i][2] -= dp[i - 2][0] # AGCを取り除く.
    dp[i][2] -= dp[i - 2][1] # GACを取り除く.
    dp[i][1] -= dp[i - 2][0] - dp[i - 3][1] # ACGを取り除く. ただしGACGはすでに取り除いている.
    dp[i][2] -= 3 * dp[i - 3][0] # すでに取り除いているものに注意する.結果的にAGGC,ATGC,AGTCを取り除く.
print(sum(dp[-1]) % mod)

Submission status: Accepted

Solution code:
n = int(input())
dp = [[0] * 4 for i in range(n + 2)]
for i in range(4):
    dp[2][i] = 1
mod = 10**9 + 7
for i in range(3, n + 2):
    for j in range(4):
        for k in range(4):
            dp[i][j] += dp[i - 1][k]
    dp[i][2] -= dp[i - 2][0]
    dp[i][2] -= dp[i - 2][1]
    dp[i][1] -= dp[i - 2][0] - dp[i - 3][1]
    dp[i][2] -= 3 * dp[i - 3][0]
print(sum(dp[-1]) % mod)

Submission status: Accepted

Solution code:
MOD = pow(10,9)+7
N = int(input())
dp = [[[[0 for _ in range(4)] for _ in range(4)] for _ in range(4)] for _ in range(N+1)]
dp[0][3][3][3] = 1 #3333Sとくる場合は制約に何も引っかからない
#dp[i][j][k][l]: i文字目まで見て最後のの三文字がlkjであるような場合の数
#A=0, G=1, C=2, T=3

for i in range(N):
  for j in range(4):
    for k in range(4):
      for l in range(4):
        if dp[i][j][k][l] == 0: #i文字目で条件にあてはまるものがないときは飛ばす。
          continue
        for a in range(4): #ダメな条件を飛ばす
          if a == 2 and j == 1 and k == 0: #AGC
            continue
          if a == 1 and j == 2 and k == 0: #ACG
            continue
          if a == 2 and j == 0 and k == 1: #GAC
            continue
          if a == 2 and j == 1 and l == 0: #A?GC
            continue
          if a == 2 and k == 1 and l == 0: #AG?c
            continue
          dp[i+1][a][j][k] += dp[i][j][k][l]%MOD
ans = 0            
for j in range(4):
  for k in range(4):
    for l in range(4):
      ans += dp[N][j][k][l]
ans = ans%MOD
print(ans)

Submission status: Accepted

Solution code:
p = 10**9+7
N = int(input())
dp = [[[[[0 for _ in range(4)] for _ in range(4)] for _ in range(4)] for _ in range(4)] for _ in range(N+1)]
for i in range(4):
    for j in range(4):
        for k in range(4):
            for l in range(4):
                if i==0:
                    dp[3][i][j][k][l] = 1
for i in range(4):
    dp[3][i][0][1][2] = 0
    dp[3][i][1][0][2] = 0
    dp[3][i][0][2][1] = 0
for n in range(4,N+1):
    for i in range(4):
        for j in range(4):
            for k in range(4):
                for l in range(4):
                    for x in range(4):
                        dp[n][i][j][k][l] = (dp[n][i][j][k][l]+dp[n-1][x][i][j][k]*(str(j)+str(k)+str(l)!="012")\
                            *(str(j)+str(k)+str(l)!="102")*(str(j)+str(k)+str(l)!="021")\
                            *(str(i)+str(k)+str(l)!="012")*(str(i)+str(j)+str(l)!="012"))%p
cnt = 0
for i in range(4):
    for j in range(4):
        for k in range(4):
            for l in range(4):
                cnt = (cnt+dp[N][i][j][k][l])%p
print(cnt)

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
#mod = 998244353
INF = 10**18
eps = 10**-7

import itertools

def check(s):
    if "AGC" in s:
        return False
    for i in range(len(s)-1):
        a = s[:i] + s[i+1] + s[i] + s[i+2:]
        if "AGC" in a:
            return False
    return True

N = int(readline())
dp = [[0]*61 for i in range(N-2)]
for i in range(61):
    dp[0][i] = 1

rel = {}
cnt = 0
L = list("AGCT")
for v in itertools.product(L,repeat=3):
    s = ''.join(v)
    if check(s):
        rel[s] = cnt
        cnt += 1

for i in range(N-3):
    for k,v in rel.items():
        for s in L:
            if check(k+s):
                dp[i+1][rel[k[1:]+s]] = (dp[i+1][rel[k[1:]+s]] + dp[i][v])%mod
ans = 0
for i in range(61):
    ans = (ans + dp[N-3][i])%mod
print(ans)

Submission status: Accepted

Solution code:
MOD=10**9+7
n=int(input())
dp=[]
for i in range(n+1):
  dp.append([])
  for j in range(4):
    dp[-1].append([])
    for k in range(4):
      dp[-1][-1].append([])
      for l in range(4):
        dp[-1][-1][-1].append(0)
for i in range(4):
  for j in range(4):
    for k in range(4):
      dp[3][i][j][k]=1
dp[3][0][1][2]=0
dp[3][0][2][1]=0
dp[3][1][0][2]=0
for i in range(3,n):
  for j in range(4):
    for k in range(4):
      for l in range(4):
        dp[i+1][k][l][0]=(dp[i+1][k][l][0]+dp[i][j][k][l])%MOD
        dp[i+1][k][l][1]=(dp[i][j][k][l]+dp[i+1][k][l][1])%MOD
        dp[i+1][k][l][3]=(dp[i][j][k][l]+dp[i+1][k][l][3])%MOD
        if not((j==0 and k==1) or (j==0 and l==1)):
          dp[i+1][k][l][2]=(dp[i+1][k][l][2]+dp[i][j][k][l])%MOD
  dp[i+1][0][1][2]=0
  dp[i+1][0][2][1]=0
  dp[i+1][1][0][2]=0
ans=0
for i in range(4):
  for j in range(4):
    for k in range(4):
      ans=(ans+dp[n][i][j][k])%MOD
print(ans)

Submission status: Accepted

Solution code:
# 2回前までのを保存しておく全探索？
# -> ATGC ACGC AGGC の場合も条件を満たしてしまうので、3つ前までかも（気づくのに長時間かかった）
# -> AGxCの場合も気づかなかった...

# なぜかサンプル3が合わないがコードが間違ってるわけないので表記ミスと判断して提出（傲慢
# -> MODしてないだけだった...

n = int(input())
if n == 3:
    print(61)
    exit()

memo = {}
MOD = 10**9 + 7


def rec(i, pre3, pre2, pre1):
    if pre3 == "A" and pre2 == "G" and pre1 == "C":
        return 0
    if pre3 == "G" and pre2 == "A" and pre1 == "C":
        return 0
    if pre3 == "A" and pre2 == "C" and pre1 == "G":
        return 0
    if (i, pre1, pre2, pre3) in memo:
        return memo[(i, pre1, pre2, pre3)]
    if i == n - 3:
        return 1
    else:
        ret = 0
        if (pre1 == "G" and pre2 == "A") or (pre1 == "A" and pre2 == "G"):
            ret = rec(i + 1, pre2, pre1, "A") % MOD + rec(
                i + 1, pre2, pre1, "G") % MOD + rec(i + 1, pre2, pre1,
                                                    "T") % MOD
        elif pre1 == "C" and pre2 == "A":
            ret = rec(i + 1, pre2, pre1, "C") % MOD + rec(
                i + 1, pre2, pre1, "A") % MOD + rec(i + 1, pre2, pre1,
                                                    "T") % MOD
        elif pre3 == "A" and pre1 == "G":
            ret = rec(i + 1, pre2, pre1, "A") % MOD + rec(
                i + 1, pre2, pre1, "G") % MOD + rec(i + 1, pre2, pre1,
                                                    "T") % MOD
        elif pre3 == "A" and pre2 == "G":
            ret = rec(i + 1, pre2, pre1, "A") % MOD + rec(
                i + 1, pre2, pre1, "G") % MOD + rec(i + 1, pre2, pre1,
                                                    "T") % MOD
        else:
            ret = rec(i + 1, pre2, pre1,
                      "A") + rec(i + 1, pre2, pre1, "G") % MOD + rec(
                          i + 1, pre2, pre1, "C") % MOD + rec(
                              i + 1, pre2, pre1, "T") % MOD
        ret %= MOD
        memo[(i, pre1, pre2, pre3)] = ret
        return ret


# 最初とりうるやつ（めんどい）
ans = 0
for i in ["A", "G", "C", "T"]:
    for j in ["A", "G", "C", "T"]:
        for k in ["A", "G", "C", "T"]:
            ans += rec(0, i, j, k)

print(ans % MOD)

Submission status: Accepted

Solution code:
n=int(input())
mod1,mod2=10**9+7,998244353
mod=mod1
import sys
sys.setrecursionlimit(10**9)
memo=[{}for i in range(n+1)]
def ok(s):
    if "AGC"in s:return False
    for i in range(3):
        if "AGC"in s[:i]+s[i+1]+s[i]+s[i+2:]:
            return False
    return True
def dfs(cnt,las):
    if las in memo[cnt]:return memo[cnt][las]
    if cnt==n:return 1
    ret=0
    for nec in "AGCT":
        if ok(las+nec):
            ret=(ret+dfs(cnt+1,las[1:]+nec))%mod
    memo[cnt][las]=ret
    return ret
print(dfs(0,"TTT"))

Submission status: Accepted

Solution code:
N = int(input())
dp = [[[[0] * 4 for _ in range(4)] for _ in range(4)] for _ in range(N+1)]
for i in range(4):
    for j in range(4):
        for k in range(4):
            if k == 1 and j == 0 and i == 2:
                pass
            elif k == 0 and j == 2 and i == 1:
                pass
            elif k == 0 and j == 1 and i == 2:
                pass
            else:
                dp[3][i][j][k] = 1
mod = 10**9 + 7

for i in range(4, N + 1):
    for j in range(4):
        for k in range(4):
            for l in range(4):
                for p in range(4):
                    if l == 1 and k == 0 and j == 2:
                        pass
                    elif l == 0 and k == 2 and j == 1:
                        pass
                    elif l == 0 and k == 1 and j == 2:
                        pass
                    elif p == 0 and k == 1 and j == 2:
                        pass
                    elif p == 0 and l == 1 and j == 2:
                        pass
                    else:
                        dp[i][j][k][l] += (dp[i - 1][k][l][p]) % mod

ans = 0
for i in range(4):
    for j in range(4):
        for k in range(4):
            ans += dp[N][i][j][k]

print(ans%mod)

Submission status: Accepted

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
import math
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7


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

N = getN()
memo = [{} for i in range(N + 1)]
def ok(last4):
    for i in range(4):
        t = list(last4)
        if i >= 1:
            t[i - 1],t[i] = t[i], t[i - 1]
        if ''.join(t).count('AGC') >= 1:
            return False
    return True
def dfs(cur, last3):
    if last3 in memo[cur]:
        return memo[cur][last3]
    if cur == N: return 1
    res = 0
    for c in 'ACGT':
        if ok(last3 + c):
            res  = (res + dfs(cur + 1, last3[1:] + c)) % mod
    memo[cur][last3] = res
    return res
print(dfs(0,'TTT'))

Submission status: Accepted

Solution code:
N, MOD = int(input()), 10 ** 9 + 7
memo = [{} for i in range(N+1)]
def ok(last4):
    for i in range(4):
        t = list(last4)
        if i >= 1:
            t[i-1], t[i] = t[i], t[i-1]
        if ''.join(t).count('AGC') >= 1:
            return False
    return True
def dfs(cur, last3):
    if last3 in memo[cur]:
        return memo[cur][last3]
    if cur == N:
        return 1
    ret = 0
    for c in 'ACGT':
        if ok(last3 + c):
            ret = (ret + dfs(cur + 1, last3[1:] + c)) % MOD
    memo[cur][last3] = ret
    return ret
print(dfs(0, 'TTT'))

Submission status: Accepted

Solution code:
n,mod=int(input()),10**9+7
dp=[{} for i in range(n+1)]
def ok(last4):
    for i in range(4):
        t=list(last4)
        if i>=1:
            t[i-1],t[i]=t[i],t[i-1]
        if ''.join(t).count('AGC')>=1:
            return 0
    return 1
def dfs(cur,last3):
    if last3 in dp[cur]:
        return dp[cur][last3]
    if cur==n:
        return 1
    ret=0
    for c in 'AGCT':
        if ok(last3+c):
            ret+=dfs(cur+1,last3[1:]+c)
            ret%=mod
    dp[cur][last3]=ret
    return ret




print(dfs(0,'TTT'))

Submission status: Accepted

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

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

import sys
input = sys.stdin.readline

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

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

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

#############
# 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))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]

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

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

N = I()
from itertools import product
dic = list(product(["A","C","G","T"],repeat=3))
NG = [("A","C","G"),("A","G","C"),("G","A","C")]
dp = {k:[0 for i in range(N)] for k in dic}
for k in dic:
  if k not in NG:
    dp[k][2] += 1
    

for i in range(3,N):
  for k in dic:
    if k in NG: continue
    for kk in dic:
      if k[0]!=kk[1] or k[1]!=kk[2]: continue
      if kk[0]=="A" and kk[1]=="G" and k[2]=="C":continue
      if kk[0]=="A" and k[1]=="G" and k[2]=="C":continue
      dp[k][i] += dp[kk][i-1]
  
ans = 0
for k in dic:
  ans += dp[k][-1]
  ans %= MOD
print(ans)

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**6)
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

from functools import lru_cache

n = ni()
mod = 10**9+7

@lru_cache(maxsize=10000)
def dfs(n, l):
    rt = 0
    if n == 0:
        return 1
    if l[1:3] == 'AG' or l[1:3] == 'GA' or (l[0] == 'A' and l[2] == 'G') or l[:2] == 'AG':
        pass
    else:
        rt += dfs(n-1, l[1:]+'C')
    if l[1:] != 'AC':
        rt += dfs(n-1,l[1:]+'G')
    rt += dfs(n-1,l[1:]+'T')
    rt += dfs(n-1,l[1:]+'A')
    return rt%mod

print(dfs(n,'TTT')%mod)

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**6)
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n = ni()
mod = 10**9+7
from functools import lru_cache

@lru_cache(maxsize=1000)
def dfs(n, l):
    rt = 0
    if n == 0:
        return 1
    if l[1:3] == 'AG' or l[1:3] == 'GA' or (l[0] == 'A' and l[2] == 'G') or l[:2] == 'AG':
        pass
    else:
        rt += dfs(n-1, l[1:]+'C')
    if l[1:] != 'AC':
        rt += dfs(n-1,l[1:]+'G')
    rt += dfs(n-1,l[1:]+'T')
    rt += dfs(n-1,l[1:]+'A')
    return rt%mod



print(dfs(n,'TTT')%mod)

Submission status: Accepted

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

def mi(): return map(int,input().split())
def ii(): return int(input())
def isp(): return input().split()
def deb(text): print("-------\n{}\n-------".format(text))

def main():
    N = ii()
    a,g,c,t=0,1,2,3
    MOD = 10**9+7

    dp = [[[[0]*4 for _ in range(4)] for _ in range(4)] for _ in range(110)]

    def ok(j,k,l):
        f = True
        for x,y,z in [(j,k,l),(j,l,k),(k,j,l)]:
            f = f and not (x == a and y == g and z == c)
        return f


    for j in range(4):
        for k in range(4):
            for l in range(4):
                if not ok(j,k,l): continue
                dp[3][j][k][l] = 1
    
    ans = 0
    for i in range(3,N):
        for j in range(4):
            for k in range(4):
                for l in range(4):
                    for c_char in range(4):
                        if not ok(k,l,c_char): continue
                        elif j == a and c_char == c and (k == g or l == g): continue
                        dp[i+1][k][l][c_char] += dp[i][j][k][l] % MOD

    # print(dp)
    for j in range(4):
            for k in range(4):
                for l in range(4): 
                    ans += dp[N][j][k][l]  % MOD


    print(ans % MOD)



if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
#float型を許すな
#numpyはpythonで
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,factorial
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()
out=[(0,0,2,1),(1,0,2,1),(2,0,2,1),(3,0,2,1),(0,0,2,1),(0,1,2,1),(0,2,2,1),(0,3,2,1),(0,0,1,2),(1,0,1,2),(2,0,1,2),(3,0,1,2),(0,2,0,1),(1,2,0,1),(2,2,0,1),(3,2,0,1),(0,2,0,1),(0,2,1,1),(0,2,2,1),(0,2,3,1)]
dp=[[[[0]*4 for i in range(4)]for j in range(4)] for k in range(n-2)]
dp[0]=[[[1]*4 for i in range(4)] for j in range(4)]
dp[0][0][2][1]=0
dp[0][0][1][2]=0
dp[0][2][0][1]=0
for i in range(n-3):
    for j in range(4):
        for k in range(4):
            for l in range(4):
                for m in range(4):
                    if (j,k,l,m) in out:
                        continue
                    else:
                        dp[i+1][k][l][m]+=dp[i][j][k][l]%mod
#print(dp)
ans=0
for i in range(4):
    for j in range(4):
        ans+=sum(dp[-1][i][j])%mod
print(ans%mod)

Submission status: Accepted

Solution code:
n=int(input())
mod=10**9+7
memo=[{} for i in range(n+1)]

def ok(last4):
  for i in range(4):
    t=list(last4)
    if i>=1:
      t[i-1],t[i]=t[i],t[i-1]
    if "".join(t).count("AGC")>=1:
      return False
  return True

def dfs(cur,last3):
  if last3 in memo[cur]:
    return memo[cur][last3]
  if cur==n:
    return 1
  res=0
  for c in "ACGT":
    if ok(last3+c):
      res=(res+dfs(cur+1,last3[1:]+c))%mod
  memo[cur][last3]=res
  return res

print(dfs(0,"TTT"))

Submission status: Accepted

Solution code:
import re
n = int(input())
MOD = 10**9 + 7

string = "ACGT"

# AGC
# A*GC
# GAC
# ACG
# AG*C

table = [{} for i in range(n + 1)]
def dfs(s="", depth=n):
    if table[depth].get(s) is not None:
        return table[depth][s]
    if re.search(r"(AGC|A.GC|GAC|ACG|AG.C)", s):
        table[depth][s] = 0
        return 0
    if depth == 0:
        table[depth][s] = 1
        return 1

    cnt = 0
    for i in string:
        cnt += dfs(s[-3:] + i, depth - 1)
        if cnt >= MOD:
            cnt %= MOD
    table[depth][s] = cnt
    return cnt

print(dfs())

Submission status: Accepted

Solution code:
N = int(input())
mod = int(1e9) + 7
line = 'TAGC'
ng = {"AGC", "ACG", "GAC", "ATGC", "AGGC", "ACGC", "AGTC", "AGCC"}
D = {line[(i//16)%4]+line[(i//4)%4]+line[i%4]: i for i in range(64)}
invD = {i: line[(i//16)%4]+line[(i//4)%4]+line[i%4] for i in range(64)}
dp = [[0 for _ in range(N+1)] for __ in range(64)]
dp[0][0] = 1
for i in range(4):
  dp[i][1] = 1
for i in range(16):
  dp[i][2] = 1
for i in range(3, N+1):
  for j in range(64):
    for k in range(4):
      last = invD[j]
      if last not in ng:
        if (last[1:] + line[k]) not in ng and last + line[k] not in ng:
          dp[D[last[1:]+line[k]]][i] += dp[D[last]][i-1]
          dp[D[last[1:]+line[k]]][i] %= mod
S = 0
for i in range(64):
  S += dp[i][N]
  S %= mod
print(S)

Submission status: Accepted

Solution code:
N = int(input())
mod = 10**9+7
memo = [{} for _ in range(N+1)]
def ok(last4):
    for i in range(4):
        t = list(last4)
        if i >=1:
            t[i-1],t[i] = t[i],t[i-1]
        if ''.join(t).count('AGC') >=1:
            return False
    return True
def dfs(cur,last3):
    if last3 in memo[cur]:
        return memo[cur][last3]
    if cur ==N: return 1
    res = 0
    for c in 'ACGT':
        if ok(last3+c):
            res  = (res + dfs(cur+1,last3[1:]+c))%mod
    memo[cur][last3] = res
    return res
print(dfs(0,'TTT'))

Submission status: Accepted

Solution code:
n = int(input())
mod = 10**9+7
a = []
l = ["A","C","G","T"]
ban = ["AAGC","CAGC","GAGC","TAGC","AGCA","AGCC","AGCG","AGCT","AGAC","CGAC","GGAC","TGAC","GACA","GACC","GACG","GACT","AACG","CACG","GACG","TACG","ACGA","ACGC","ACGG","ACGT","ATGC","ACGC","AGGC","AGTC","AGGC","AGAC"]
for i in l:
    for j in l:
        for k in l:
            a.append(i+j+k)
dp = [[0]*64 for _ in range(n+1)]
for i in range(64):
    if (a[i]=="AGC" or a[i]=="ACG" or a[i]=="GAC"):
        continue
    dp[3][i] = 1
for i in range(4,n+1):
    for j in range(64):
        for k in l:
            b = a[j]+k
            if b in ban:
                continue
            else:
                dp[i][a.index(b[1:])] += dp[i-1][j]
                dp[i][a.index(b[1:])] %= mod
print(sum(dp[-1])%mod)

Submission status: Accepted

Solution code:
# ACGT
# 0123
# exclude the cases AGC, AXGC, GAC, ACG, AGXC
# AGGC TGAC GAGC AAGC AGTC GGAC AGAC CAGC GACG AGCC CACG CGAC AACG ACGC TAGC ATGC TACG
# 
MOD = 10**9 + 7
n = int(input())
dp = [[[[0 for _ in range(4)] for _ in range(4)] for _ in range(4)] for _ in range(n + 1)]
for s in range(4):
    for t in range(4):
        for u in range(4):
            dp[3][s][t][u] = 1
dp[3][0][2][1] = 0
dp[3][0][1][2] = 0
dp[3][2][0][1] = 0
for i in range(3, n):
    for s in range(4):
        for t in range(4):
            for u in range(4):
                for v in range(4):
                    dp[i+1][t][u][v] = (dp[i+1][t][u][v] + dp[i][s][t][u]) % MOD
    dp[i+1][2][2][1] -= dp[i][0][2][2]
    dp[i+1][2][0][1] -= dp[i][3][2][0]
    dp[i+1][0][2][1] -= dp[i][2][0][2]
    dp[i+1][0][2][1] -= dp[i][0][0][2]
    dp[i+1][2][3][1] -= dp[i][0][2][3]
    dp[i+1][2][0][1] -= dp[i][2][2][0]
    dp[i+1][2][0][1] -= dp[i][0][2][0]
    dp[i+1][0][2][1] -= dp[i][1][0][2]
    dp[i+1][0][1][2] -= dp[i][2][0][1]
    dp[i+1][2][1][1] -= dp[i][0][2][1]
    dp[i+1][0][1][2] -= dp[i][1][0][1]
    dp[i+1][2][0][1] -= dp[i][1][2][0]
    dp[i+1][0][1][2] -= dp[i][0][0][1]
    dp[i+1][1][2][1] -= dp[i][0][1][2]
    dp[i+1][0][2][1] -= dp[i][3][0][2]
    dp[i+1][3][2][1] -= dp[i][0][3][2]
    dp[i+1][0][1][2] -= dp[i][3][0][1]
print(sum(dp[n][s][t][u] for s in range(4) for t in range(4) for u in range(4)) % MOD)

Submission status: Accepted

Solution code:
import sys
import numpy as np

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

input_n = lambda: int(readline())
input_nn = lambda: map(int, readline().split())
input_s = lambda: readline().rstrip().decode('utf-8')
input_ss = lambda: readline().rstrip().decode('utf-8').split()

mod = 10 ** 9 + 7


def judge(a, b, c, k):

    ret = False
    ret |= (b == 0 and c == 2 and k == 1)
    ret |= (b == 0 and c == 1 and k == 2)
    ret |= (b == 2 and c == 0 and k == 1)
    ret |= (a == 0 and b == 2 and k == 1)
    ret |= (a == 0 and c == 2 and k == 1)

    return not ret


def main():

    N = input_n()
    dp = np.full((4, 4, 4), 1, np.int32)
    dp[0, 2, 1] = 0
    dp[0, 1, 2] = 0
    dp[2, 0, 1] = 0

    for n in range(N - 3):
        next_dp = np.zeros((4, 4, 4), np.int32)
        for a in range(4):
            for b in range(4):
                for c in range(4):
                    for k in range(4):
                        if judge(a, b, c, k):
                            next_dp[b, c, k] += dp[a, b, c]
                            next_dp[b, c, k] %= mod
        dp = next_dp

    print(dp.sum() % mod)


if __name__ == '__main__':
    main()