Algarvu-Scrabble
Time limit1sMemory limit1024 MB
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 tiles, each printed with a single digit from to . A tile's value is the digit written on it, except that a tile showing is worth 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, times the sum). A number may start with (for example, 07 reads as ). For instance, if the row is 167, then both 167 and 761 are prime, so that placement scores .
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 (). The second line contains 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.