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)

use itertools::Itertools;
use proconio::{input, marker::Usize1};

fn main() {
    input!(n: usize, a: [Usize1; 3 * n]);

    let mut add = 0;

    let mut max = vec![i64::min_value(); n];
    max[a[0]] = 0;
    max[a[1]] = 0;

    let mut dp = vec![vec![i64::min_value(); n]; n];
    dp[a[0]][a[1]] = 0;
    dp[a[1]][a[0]] = 0;

    for (a, b, c) in a.iter().copied().skip(2).tuples() {
        let m = *max.iter().max().unwrap();
        let mut queue = vec![];
        let mut update = |i, j, v| queue.push((i, j, v));
        if a == b && b == c {
            add += 1;
            continue;
        }
        for (p, q, r) in [a, b, c, a, b].iter().copied().tuple_windows() {
            if p == q {
                for k in 0..n {
                    update(k, r, dp[p][k] + 1);
                    update(k, r, dp[k][p] + 1);
                }
            }
            update(q, r, dp[p][p] + 1);
            update(p, q, m);
            for k in 0..n {
                update(k, p, max[k]);
            }
        }
        for &(x, y, v) in &queue {
            dp[x][y] = dp[x][y].max(v);
            dp[y][x] = dp[y][x].max(v);
            max[x] = max[x].max(v);
            max[y] = max[y].max(v);
        }
    }

    let last = *a.last().unwrap();
    dp[last][last] += 1;

    let ans = add + dp.iter().flatten().max().unwrap();

    println!("{}", ans);
}