This page is still under construction.

Parts of this page are still being built. What you see may change.

Algarvu-Scrabble

Time limit1sMemory limit1024 MB

Summary
Given up to 8 digit tiles, place them one by one at either end of a row to maximize prime-direction scoring minus penalties for unused tiles.
Level

Medium6 of 10

Topics
Backtracking, Brute force, Number theory, Dynamic programming
Solved
No attempts yet

Problem

Algarvu-Scrabble is a single-player board game. The player receives NN tiles, each printed with a single digit from 00 to 99. A tile's value is the digit written on it, except that a tile showing 00 is worth 1010 points.

You build a single row by placing the tiles one at a time. An existing row may be extended at its left end or its right end, but tiles already on the board can never be rearranged.

Each time you place a tile you score if the current row, read left-to-right, is a prime number, and/or read right-to-left, is a prime number. For every direction that reads as a prime you earn the sum of the values of all tiles currently in the row. If both directions are prime at once, you score for both (that is, 22 times the sum). A number may start with 00 (for example, 07 reads as 77). For instance, if the row is 167, then both 167 and 761 are prime, so that placement scores 2×(1+6+7)2 \times (1 + 6 + 7).

At the end of the game the row on the board must itself be prime (in at least one direction). If it is impossible to finish on a prime using all of your tiles, you may leave some tiles unplaced; each unplaced tile costs you its value as a penalty, which is subtracted from your score.

Your total score equals (the sum of the points earned on every placement) minus (the sum of the values of the unplaced tiles). Find the maximum total score obtainable with the given tiles.

Input

The first line contains the number of tiles NN (1≤N≤81 \le N \le 8). The second line contains NN space-separated integers (the tiles).

Output

Print a single integer: the maximum total score obtainable. If no non-empty combination of tiles can end on a prime, then no tile can ever score, so every tile becomes a penalty and the answer is the negative of the total value of all tiles.

Examples3

  1. Example 1

    Input
    4
    1 6 5 7
    
    Expected output
    74
    
  2. Example 2

    Input
    4
    1 7 6 7
    
    Expected output
    48
    
  3. Example 3

    Input
    1
    7
    
    Expected output
    14