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 C++ (GCC 9.2.1) (judge verdict: Wrong Answer)

#include <bits/stdc++.h>
#define rep(i,n) for(int i=0;i<n;i++)
using namespace std;
using ll = long long;
using P = pair<int,int>;
using T = tuple<int,int,int>;

int a[6005];
int dp[2005][2005];
int maxa[2005]; //要素にiを持つ場合の最大値

int main(){
  int n;
  cin >> n;
  int n3 = n*3;
  
  rep(i,n3) cin >> a[i],--a[i];
  rep(i,n)rep(j,n) dp[i][j] = -1;
  rep(i,n) maxa[i] = -1;
  

  dp[a[0]][a[1]] = 0;
  dp[a[1]][a[0]] = 0;
  maxa[a[0]] = maxa[a[1]] = 0;
  int maxab = 0; //その時点での最大値
  int ex = 0;
    
  for(int i=2; i < n3-2; i+=3){
    int x = a[i];
    int y = a[i+1];
    int z = a[i+2];
    
    //新しい3枚が一致していたとき
    if(x == y && y == z){ 
      ++ex;
      continue;
    }
    
    vector<T> t;
    //古い2枚と新しい1枚
    //古いのを2枚捨てるからその時点の最大値maxabと比較。
    rep(j,3){
      int m = max(maxab, dp[z][z]+1);
      t.emplace_back(x,y,m);
      swap(x,y); swap(y,z);
    }
    
    //古い1枚と新しい2枚
    rep(j,3){
      rep(k,n){
        int m = maxa[k];
        if(x == y) m = max(m, dp[x][k]+1);
          t.emplace_back(z,k,m);
        }
      swap(x,y); swap(y,z);
    }
    
    for(auto upd : t){
      int na, nb, s;
      tie(na, nb, s) = upd;
      
      dp[na][nb] = max(dp[na][nb], s);
      dp[nb][na] = max(dp[nb][na], s);
      maxa[na] = max(maxa[na], s);
      maxa[nb] = max(maxa[nb], s);

      maxab = max(maxab, s);
    }   
  }
  
  int ans = maxab;
  int al = a[n3-1];
  ans = max(maxab, dp[al][al]+1);
  ans += ex;
  cout << ans << endl;

  return 0;
}