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: Runtime Error)

// -*- coding:utf-8-unix -*-

use std::collections::HashMap;

#[allow(unused_imports)]
use itertools::Itertools;
use proconio::input;

#[allow(dead_code)]
fn map2d<InnerIt: IntoIterator, It: Iterator<Item = InnerIt>, B>(
    it: It,
    f: fn(InnerIt::Item) -> B,
) -> Vec<Vec<B>> {
    it.map(|row| row.into_iter().map(f).collect::<Vec<_>>())
        .collect::<Vec<_>>()
}

fn count<It: Iterator<Item = Item>, Item>(it: It) -> HashMap<Item, usize>
where
    Item: Eq,
    Item: std::hash::Hash,
{
    let mut c = HashMap::new();
    for item in it {
        *c.entry(item).or_insert(0usize) += 1;
    }
    return c;
}

#[derive(Debug, Hash, PartialEq, Eq, Clone)]
struct CachedArg {
    pub n: usize,
    pub x: i32,
    pub y: i32,
}

#[allow(non_snake_case)]
struct CachedFunc {
    A: Vec<i32>,
    // memo[{n, x, y}] = max points for A[n:], but modified as A[n] = x, A[n + 1] = y
    memo: HashMap<CachedArg, i32>,
}
impl CachedFunc {
    #[allow(non_snake_case)]
    pub fn new(N: usize, A: Vec<i32>) -> CachedFunc {
        assert!(A.len() == 3 * N);
        assert!(N >= 1);
        CachedFunc {
            A: A,
            memo: HashMap::new(),
        }
    }
    fn calc(&mut self, arg: CachedArg) -> i32 {
        if !self.memo.contains_key(&arg) {
            assert!(arg.n + 2 < self.A.len(), "could not take 3 cards");
            if arg.n + 4 >= self.A.len() {
                self.memo.insert(
                    arg.clone(),
                    if arg.x == arg.y && arg.y == self.A[arg.n + 2] {
                        1
                    } else {
                        0
                    },
                );
            } else {
                let head = &self.A[arg.n..arg.n + 5];
                let mut head = head.iter().cloned().collect::<Vec<_>>();
                head[0] = arg.x;
                head[1] = arg.y;
                let head = head;
                let cnt = count(head.iter());
                for (&&k, &v) in cnt.iter() {
                    let mut v = v;
                    if v >= 3usize {
                        let mut rest = Vec::with_capacity(2);
                        for &x in head.iter() {
                            if x == k && v > 0 {
                                v -= 1;
                                continue;
                            }
                            rest.push(x);
                        }
                        let point = 1 + self.calc(CachedArg {
                            n: arg.n + 3,
                            x: rest[0],
                            y: rest[1],
                        });
                        self.memo.insert(arg.clone(), point);
                        break;
                    }
                }
                if !self.memo.contains_key(&arg) {
                    let mut max = None;
                    for perm in head.into_iter().permutations(5) {
                        let point: i32 = self.calc(CachedArg {
                            n: arg.n + 3,
                            x: perm[3],
                            y: perm[4],
                        }) + if perm[0] == perm[1] && perm[1] == perm[2] {
                            1
                        } else {
                            0
                        };
                        match max {
                            None => max = Some(point),
                            Some(v) => {
                                if v < point {
                                    max = Some(point)
                                }
                            }
                        }
                    }
                    self.memo.insert(arg.clone(), max.unwrap());
                }
            }
        }
        return self.memo[&arg];
    }
}

#[allow(non_snake_case)]
fn main() {
    input! {
        N: usize,
        A: [i32; 3 * N],
    }
    let arg = CachedArg {
        n: 0,
        x: A[0],
        y: A[1],
    };
    let mut func = CachedFunc::new(N, A);
    println!("{}", func.calc(arg));
}