The Most Valuable Tower
Time limit1sMemory limit512 MB
Find the largest sum any single tower can reach by swapping top segments between towers of different heights.
- Level
Hard9 of 10
- Topics
- Number theory, Sorting, Greedy, Prefix sum
- Solved
- No attempts yet
Problem
Jas has built several towers of different heights out of blocks. Each block has an integer written on it. A tower is more valuable the larger the sum of the blocks it contains. Jas wants to build the most valuable tower possible, but he does not want to completely destroy the towers he has already built. So he decided that the only move he may make is to choose two towers of different heights and:
- from the taller tower, remove exactly as many of its topmost blocks as there are blocks in the shorter tower (keeping their order) and form a new tower out of them;
- then place the other (shorter) tower, as a whole, on top of the tower from which the blocks were removed.
This produces two towers of the same heights as before, but possibly with a different arrangement of the numbers on the individual blocks (see the figure).

Figure: An example of Jas's move for the towers and .
Find the maximum value of a tower that Jas can build.
Input
The first line contains an integer (), the number of towers Jas built. Each of the next lines describes one tower. The -th line contains an integer (), the height of the -th tower, followed by integers (), where is the number written on the -th block from the top of the -th tower. The total number of blocks across all towers does not exceed .
Output
Output a single integer: the maximum value of a tower that Jas can build.
Hint

Explanation: From towers no. 2 and no. 3 Jas can build the tower , and then from that tower together with tower no. 1 he can build the tower , whose value is .