module mod_selection_sort
  implicit none
  integer, private, parameter :: intkind = 4
contains
  logical function less(a, b) result(res)
    integer(intkind), intent(in) :: a, b
    res = a <= b
  end
  subroutine swap(a, b)
    integer(intkind), intent(inout) :: a, b
    a = xor(a, b)
    b = xor(a, b)
    a = xor(a, b)
  end
  subroutine selection_sort(a)
    integer(intkind), intent(inout) :: a(:)
    integer :: n, i, j, m
    n = size(a)
    do i = 1, n - 1
      m = i
      do j = i + 1, n
        if (.not.less(a(m), a(j))) m = j
      end do
      if (i /= m) call swap(a(i), a(m))
    end do
  end
end module mod_selection_sort
program brave_chain
  use mod_selection_sort
  implicit none
  integer, parameter :: inf = 1e9
  integer :: n, a(6000) = 0, dp(2000, 2000) = -inf, m = 0, b(3) = 0, v, i, j
  integer, dimension(2000) :: dp0 = 0, mv = -inf, mv0 = 0
  read(*,*) n
  read(*,*) a(1:3 * n)
  call update(a(1), a(2), 0)
  do i = 3, 3 * n - 2, 3
    if (a(i) == a(i + 1) .and. a(i) == a(i + 2)) then
      m = m + 1
      cycle
    end if
    call selection_sort(a(i:i + 2))
    if (a(i + 1) == a(i + 2)) call swap(a(i), a(i + 2))
    do j = 1, n
      dp0(j) = dp(min(a(i), j), max(a(i), j))
    end do
    mv0(1:n) = mv(1:n)
    v = max(0, maxval(mv(1:n)))
    do j = 1, 3
      b(j) = dp(a(i + j - 1), a(i + j - 1))
    end do
    if (a(i) == a(i + 1)) then
      do j = 1, n
        call update(a(i + 2), j, dp0(j) + 1)
      end do
    end if
    call update(a(i + 1), a(i + 2), b(1) + 1)
    call update(a(i), a(i + 2), b(2) + 1)
    call update(a(i), a(i + 1), b(3) + 1)
    call update(a(i + 1), a(i + 2), v)
    call update(a(i), a(i + 2), v)
    call update(a(i), a(i + 1), v)
    do j = 1, n
      call update(a(i), j, mv0(j))
      call update(a(i + 1), j, mv0(j))
      call update(a(i + 2), j, mv0(j))
    end do
  end do
  i = a(3 * n)
  write(*,'(i0)') max(dp(i, i) + 1, maxval(mv(1:n))) + m
contains
  subroutine update(a, b, z)
    integer, intent(in) :: a, b, z
    integer :: x, y
    if (a > b) then
      x = b
      y = a
    else
      x = a
      y = b
    end if
    if (dp(x, y) >= z) return
    dp(x, y) = z
    mv(x) = max(mv(x), z)
    mv(y) = max(mv(y), z)
  end
end program brave_chain