Under construction

Still being built. Things may change

The Most Valuable Tower

Time limit1sMemory limit512 MB

Summary
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 (4,5,7,1)(4, 5, 7, 1) and (3,6)(3, 6).

Find the maximum value of a tower that Jas can build.

Input

The first line contains an integer nn (1≤n≤500 0001 \le n \le 500\,000), the number of towers Jas built. Each of the next nn lines describes one tower. The (i+1)(i+1)-th line contains an integer wiw_i (1≤wi≤1 000 0001 \le w_i \le 1\,000\,000), the height of the ii-th tower, followed by wiw_i integers x1,x2,…,xwix_1, x_2, \dots, x_{w_i} (−1 000 000≤xk≤1 000 000-1\,000\,000 \le x_k \le 1\,000\,000), where xkx_k is the number written on the kk-th block from the top of the ii-th tower. The total number of blocks KK across all towers does not exceed 1 000 0001\,000\,000.

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 (4,6)(4, 6), and then from that tower together with tower no. 1 he can build the tower (4,6,7,1)(4, 6, 7, 1), whose value is 1818.

Examples2

  1. Example 1

    Input
    4
    4 4 5 7 1
    2 3 6
    1 4
    1 1
    
    Expected output
    18
    
  2. Example 2

    Input
    4
    3 1 2 3
    2 4 5
    1 6
    4 7 8 9 10
    
    Expected output
    34