object Main extends App {
  val sc = new java.util.Scanner(System.in)
  val N = sc.nextInt()
  val As = Array.fill(3*N)(sc.nextInt() - 1)

  def comp(a: Int, b: Int): Int = a*N + b
  val dp = Array.fill(N*N)(Int.MinValue)
  val m1 = Array.fill(N)(Int.MinValue)
  val m2 = Array.fill(N)(Int.MinValue)
  var m = 0
  var ans = 0
  dp(comp(As(0), As(1))) = 0
  m1(As(0)) = 0
  m2(As(1)) = 0
  var update = List[(Int, Int, Int)]()
  for (i <- 1 until N) {
    val p = As(3*i - 1)
    val q = As(3*i)
    val r = As(3*i + 1)
    if (p == q && q == r) {
      ans += 1
    } else {
      if (p == q || p == r || r == q) {
        val x = if (p == q || r == p) p else q
        val y = if (p == q) r else if (r == p) q else p
        for (i <- 0 until N) {
          update ::= (i, y, dp(comp(x, i)).max(dp(comp(i, x))) + 1)
        }
      }
      update ::= (q, r, dp(comp(p, p)) + 1)
      update ::= (p, r, dp(comp(q, q)) + 1)
      update ::= (p, q, dp(comp(r, r)) + 1)
      update ::= (p, q, m)
      update ::= (p, r, m)
      update ::= (q, r, m)
      for (i <- 0 until N) {
        update ::= (i, p, m1(i).max(m2(i)))
        update ::= (i, q, m1(i).max(m2(i)))
        update ::= (i, r, m1(i).max(m2(i)))
      }
      for ((i, j, v) <- update) {
        dp(comp(i, j)) = dp(comp(i, j)).max(v)
        m1(i) = m1(i).max(dp(comp(i, j)))
        m2(j) = m2(j).max(dp(comp(i, j)))
        m = m.max(dp(comp(i, j)))
      }
      update = Nil
    }
  }
  val last = As(3*N - 1)
  m = m.max(dp(comp(last, last)) + 1)
  println(ans + m)
}