This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
const int MAX = 505;
int dp[MAX][MAX][MAX];
int ckmx(int& a, int b) {
  a = max(a, b);
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n;
  cin >> n;
  vector<int> a(n);
  vector<int> c(n);
  vector<int> v(n);
  for (int i = 0; i < n; i++) {
    cin >> a[i] >> c[i] >> v[i];
  }
  vector<vector<bool>> ok(n, vector<bool>(n));
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      ok[i][j] = (a[i] == a[j] || c[i] == c[j]);
    }
  }
  const int inf = (int) 1e9;
  for (int i = 0; i < n + 2; i++) {
    for (int j = 0; j < n + 2; j++) {
      for (int k = 0; k < n + 2; k++) {
        dp[i][j][k] = -inf;
      }
    }
  }
  function<int(int, int, int, int)> Solve = [&](int x, int y, int z, int f) {
    if (x >= n) {
      return 0;
    }
    if (dp[x][y][f] != -inf) {
      return dp[x][y][f];
    }
    /*if (was[x][z][f]) {
      return dp[x][z][f];
    }
    was[x][z][f] = true;*/
    dp[x][y][f] = 0;
    if (x < n && ok[f][x]) {
      dp[x][y][f] = max(dp[x][y][f], Solve(y, z, z + 1, x) + v[x]);
    }
    if (z < n && ok[f][z]) {
      dp[x][y][f] = max(dp[x][y][f], Solve(x, y, z + 1, z) + v[z]);
    }
    return dp[x][y][f];
  };
  int res = Solve(1, 2, 3, 0) + v[0];
  if (n >= 3) {
    res = max(res, Solve(0, 1, 3, 2) + v[2]);
  }
  cout << res << '\n';
  return 0;
}
Compilation message (stderr)
cardgame2.cpp: In function 'int ckmx(int&, int)':
cardgame2.cpp:11:1: warning: no return statement in function returning non-void [-Wreturn-type]
   11 | }
      | ^| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... |