Problem:
Score : 600 points

Problem Statement

We have 3N cards arranged in a row from left to right, where each card has an integer between 1 and N (inclusive) written on it. The integer written on the i-th card from the left is A_i.

You will do the following operation N-1 times:

Rearrange the five leftmost cards in any order you like, then remove the three leftmost cards. If the integers written on those three cards are all equal, you gain 1 point.

After these N-1 operations, if the integers written on the remaining three cards are all equal, you will gain 1 additional point.

Find the maximum number of points you can gain.

Constraints

1 \leq N \leq 2000

1 \leq A_i \leq N

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_{3N}

Output

Print the maximum number of points you can gain.

Sample Input 1

2
1 2 1 2 2 1

Sample Output 1

2

Let us rearrange the five leftmost cards so that the integers written on the six cards will be 2\ 2\ 2\ 1\ 1\ 1 from left to right.

Then, remove the three leftmost cards, all of which have the same integer 2, gaining 1 point.

Now, the integers written on the remaining cards are 1\ 1\ 1.

Since these three cards have the same integer 1, we gain 1 more point.

In this way, we can gain 2 points - which is the maximum possible.

Sample Input 2

3
1 1 2 2 3 3 3 2 1

Sample Output 2

1

Sample Input 3

3
1 1 2 2 2 3 3 3 1

Sample Output 3

3

Solution in Rust (1.42.0) (judge verdict: Accepted)

#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
use std::io::{Write, BufWriter};
// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};
    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

macro_rules! read_value {
    ($next:expr, [graph1; $len:expr]) => {{
        let mut g = vec![vec![]; $len];
        let ab = read_value!($next, [(usize1, usize1)]);
        for (a, b) in ab {
            g[a].push(b);
            g[b].push(a);
        }
        g
    }};
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };
    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };
    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };
    ($next:expr, usize1) => (read_value!($next, usize) - 1);
    ($next:expr, [ $t:tt ]) => {{
        let len = read_value!($next, usize);
        read_value!($next, [$t; len])
    }};
    ($next:expr, $t:ty) => ($next().parse::<$t>().expect("Parse error"));
}

#[allow(unused)]
macro_rules! debug {
    ($($format:tt)*) => (write!(std::io::stderr(), $($format)*).unwrap());
}
#[allow(unused)]
macro_rules! debugln {
    ($($format:tt)*) => (writeln!(std::io::stderr(), $($format)*).unwrap());
}

fn solve() {
    let out = std::io::stdout();
    let mut out = BufWriter::new(out.lock());
    macro_rules! puts {
        ($($format:tt)*) => (let _ = write!(out,$($format)*););
    }
    input! {
        n: usize,
        a: [usize1; 3 * n],
    }
    const INF: i64 = 1 << 40;
    let mut dp = vec![vec![-INF; n]; n];
    let mut rmax = vec![-INF; n];
    let mut cmax = vec![-INF; n];
    let mut gl_ma = -INF;
    if n == 1 {
        puts!("{}\n", if a[0] == a[1] && a[1] == a[2] { 1 } else { 0 });
        return;
    }
    for i in 0..5 {
        for j in 0..i {
            let mut rest = vec![];
            for k in 0..5 {
                if k != i && k != j {
                    rest.push(a[k]);
                }
            }
            let v = if rest[0] == rest[1] && rest[1] == rest[2] {
                1
            } else {
                0
            };
            dp[a[i]][a[j]] = v;
            rmax[a[i]] = max(rmax[a[i]], v);
            cmax[a[j]] = max(cmax[a[j]], v);
            gl_ma = max(gl_ma, v);
        }
    }
    let mut global: i64 = 0;
    let mut upd = vec![];
    for i in 1..n - 1 {
        // [3 * i + 2, 3 * i + 5)
        let v = if a[3 * i + 2] == a[3 * i + 3]
            && a[3 * i + 3] == a[3 * i + 4] {
                1
            } else {
                0
            };
        global += v;
        for j in 0..3 {
            for k in 0..j {
                let rest = a[3 * i + 2 + 3 - j - k];
                let aj = a[3 * i + 2 + j];
                let ak = a[3 * i + 2 + k];
                upd.push((aj, ak, max(gl_ma - v, dp[rest][rest] + 1 - v)));
            }
        }
        for j in 0..3 {
            let aj = a[3 * i + 2 + j];
            let ok = a[3 * i + 2 + ((j + 1) % 3)] == a[3 * i + 2 + ((j + 2) % 3)];
            let ak = a[3 * i + 2 + ((j + 1) % 3)];
            for r in 0..n {
                upd.push((r, aj, rmax[r] - v));
                if ok {
                    upd.push((r, aj, dp[r][ak] - v + 1));
                }
            }
            for c in 0..n {
                upd.push((aj, c, cmax[c] - v));
                if ok {
                    upd.push((aj, c, dp[ak][c] - v + 1));
                }
            }
        }
        for (x, y, val) in upd.drain(..) {
            dp[x][y] = max(dp[x][y], val);
            rmax[x] = max(rmax[x], val);
            cmax[y] = max(cmax[y], val);
            gl_ma = max(gl_ma, val);
        }
    }/*
    eprintln!("global = {}", global);
    for i in 0..n {
        eprintln!("dp[{}] = {:?}", i, dp[i]);
    }*/
    let mut ma = 0;
    for i in 0..n {
        for j in 0..n {
            ma = max(ma, dp[i][j]);
        }
    }
    let rest = a[3 * n - 1];
    ma = max(ma, dp[rest][rest] + 1);
    puts!("{}\n", ma + global);
}

fn main() {
    // In order to avoid potential stack overflow, spawn a new thread.
    let stack_size = 104_857_600; // 100 MB
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}