from sequtils import map, mapIt
from strutils import split, parseInt, parseFloat

import macros
macro unpack*(input: seq; count: static[int]): untyped =
  result = quote do: ()
  when NimMinor <= 13:
    for i in 0..<count: result[0].add quote do: `input`[`i`]
  else:
    for i in 0..<count: result.add quote do: `input`[`i`]

## count == 0 のとき unpackしない(seq)
## count >  0 のとき count個分 unpack した結果の tuple を返す
type UnselectableTypeError = object of Exception
template input*(typ: typedesc; count: Natural = 0): untyped =
  let line = stdin.readLine.split
  when count == 0:
    when typ is int:    line.map(parseInt)
    elif typ is float:  line.map(parseFloat)
    elif typ is string: line
    else: raise newException(UnselectableTypeError, "You selected a type other than int, float or string")
  else:
    when typ is int:    line.map(parseInt).unpack(count)
    elif typ is float:  line.map(parseFloat).unpack(count)
    elif typ is string: line.unpack(count)
    else: raise newException(UnselectableTypeError, "You selected a type other than int, float or string")

template inputs*(typ: typedesc; count = 0; rows = 1): untyped =
  (1..rows).mapIt(input(typ, count))

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
template secretEcho*(x: varargs[string, `$`]) =
  for v in x:
    stderr.write(v)
  echo ""

template secretEcho*[T](x: seq[seq[T]]) =
  for v in x: secretEcho v

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
from math import sum

let
  N = input(int, 1)
  F = inputs(int, rows = N)
  P = inputs(int, rows = N)

var
  result = 0
  selected = false
for i, f in F:
  let
    s = f.sum
    m = P[i][0..s].max
  result += m
  if not selected:
    for j in countdown(P[i].high, P[i].low):
      if m == P[i][j] and j != P[i].low:
        selected = true
        break

if selected:
  echo result
else:
  let p = P.mapIt(it[1..^1])
  echo p.mapIt(it.min).min
