Under construction

Still being built. Things may change

Card Game Is Great Fun

Time limit3sMemory limit1280 MB

Summary
Each turn, take the 1st or 3rd card from a row, where it must match the pile top's color or number, to maximize the total value of the pile.
Level

Medium7 of 10

Topics
Dynamic programming, Simulation
Solved
No attempts yet

Problem

Anna often played card games with her friend Bruno. She got bored of games for two players, so she invented a card game that one person can play alone.

At the start of the game, N cards of various colors are laid out in a row, and each card has one integer written on it. Each card's color is also an integer, and each card has a value. At the start, the card at position i (1 \le i \le N) from the front of the row has color CiC_i, written integer AiA_i, and value ViV_i.

The game repeats the following step. Anna removes one card from the row and adds it to the top of a draw pile. The pile starts empty.

  • Step: Choose the 1st or the 3rd card from the front of the row. If the pile is not empty, you can only choose a card whose color or written integer matches at least one of the top card's color or written integer. Remove the chosen card from the row and place it on top of the pile.

The game ends when no card can be chosen. Anna's score is the total value of the cards in the pile at that point.

Write a program that finds the maximum score Anna can get.

Input

Read the following data from standard input.

  • The first line contains an integer NN, the number of cards in the row at the start.
  • Line ii of the following NN lines (1≤i≤N1 \le i \le N) contains three integers CiC_i, AiA_i, ViV_i, separated by spaces. These mean that the card at position ii from the front has color CiC_i, written integer AiA_i, and value ViV_i.

Output

Print the maximum score Anna can get as a single integer on one line to standard output.

Constraints

  • 1≤N≤5001 \le N \le 500
  • 1≤Ci≤5001 \le C_i \le 500 (1≤i≤N1 \le i \le N)
  • 1≤Ai≤5001 \le A_i \le 500 (1≤i≤N1 \le i \le N)
  • 1≤Vi≤10000001 \le V_i \le 1000000 (1≤i≤N1 \le i \le N)

Examples2

  1. Example 1

    Input
    5
    1 3 2
    4 2 9
    1 4 6
    2 3 3
    2 2 1
    
    Expected output
    15
    
  2. Example 2

    Input
    8
    11 5 31
    2 8 19
    2 9 2
    11 8 45
    4 8 22
    4 2 23
    6 9 58
    6 2 5
    
    Expected output
    160