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.

Solution in Scala (2.11.7) (judge verdict: Accepted)

 object Main {
  def main(args: Array[String]): Unit = {
    val lines = io.Source.stdin.getLines().toArray
    println(D.solve(lines))
  }
}

object D {
  val ACGT = List('A', 'C', 'G', 'T')
  val modulus = 1000 * 1000 * 1000 + 7


  def solve(input: Array[String]) = {
    var memo = initMemo()
    val N = input(0).toInt
    (3 to N).foreach { n =>
      memo  = memo ++ Array(forward(memo(n-1)))
    }
    memo(N).values.reduce { (src, dst) =>
      (src + dst) % modulus
    }
  }

  def initMemo() = {
    var memo: Array[Map[String, Int]] = Array(Map.empty, Map.empty, Map.empty)
    //memo(2) = ACGT.combinations(2).flatMap { cs =>
    //  Map(cs.mkString("") -> 1, cs.reverse.mkString("") -> 1)
    //}.toMap
    memo(2) = ACGT.flatMap { c1 =>
      ACGT.map { c2 =>
        f"$c1$c2" -> 1
      }
    }.toMap
    memo
  }


  def forward(currentMemo: Map[String, Int]) = {
    var nextMemo = Map[String, Int]().withDefaultValue(0)
    currentMemo.keys.foreach { last =>
      ACGT.foreach { c =>
        if (isOK(last + c)) {
          val nextLast = last.takeRight(3) + c
          val added = (nextMemo(nextLast) + currentMemo(last)) % modulus
          val newItem = (nextLast) -> added
          nextMemo += newItem
        } else {
          //println(s"out!${last + c}")
        }
      }
    }
    nextMemo
  }

  def isOK(last: String) = {
    unContainsAGC(last) &&
      (0 until last.length-1).forall { i =>
        unContainsAGC(swapAdjacent(last, i))
      }
  }

  def unContainsAGC(s: String) = {
    !s.contains("AGC")
  }

  def swapAdjacent(last: String, idx: Int) = {
    val sArray = last.toArray
    val tmp = sArray(idx)
    sArray.update(idx, sArray(idx+1))
    sArray.update(idx+1, tmp)
    sArray.mkString("")
  }
}