#B4317. Yummy's Circular Journey

    ID: 11973 Type: Default 1000ms 256MiB

Yummy's Circular Journey

Yummy's Circular Journey

Yummy has recently downloaded a game that features ( n ) regions arranged in a circle and numbered from ( 1 ) to ( n ). Initially, Yummy is in region ( s ) (this initial visit counts as an arrival). Then, Yummy makes ( m ) moves. Each move is represented by either a 1 or a 2. Specifically, if Yummy is currently in region ( x ):

  • A move of 1 means Yummy goes to region ( x+1 ), with the special rule that when ( x = n ), the next region is ( 1 ).
  • A move of 2 means Yummy goes to region ( x-1 ), with the special rule that when ( x = 1 ), the next region is ( n ).

In each region ( i ) (where ( 1 \le i \le n )), there is a reward mechanism. The region awards coins only on its first ( t_i ) arrivals. On the ( j )-th arrival (( 1 \le j \le t_i )), Yummy receives ( p_{i,j} ) coins.

Given the starting region, the move sequence, and the reward information for each region, calculate the total number of coins Yummy collects. All formulas are represented in ( \LaTeX ) format.

inputFormat

The first line contains three integers ( n ), ( m ) and ( s ) (the number of regions, number of moves, and the starting region), respectively.

The second line contains ( n ) integers ( t_1, t_2, \ldots, t_n ) where ( t_i ) indicates that region ( i ) awards coins only on its first ( t_i ) arrivals.

Then, for each region ( i ) from ( 1 ) to ( n ), there is a line containing ( t_i ) integers: ( p_{i,1}, p_{i,2}, \ldots, p_{i,t_i} ). Here, ( p_{i,j} ) is the number of coins earned on the ( j )-th arrival at region ( i ).

The last line contains ( m ) integers (each either 1 or 2) representing Yummy's moves.

outputFormat

Output a single integer, the total number of coins Yummy collects after all moves.

sample

3 5 1
2 1 2
5 10
3
8 4
1 1 2 2 1
26