(n,),*q=$<.map{|l|l.split.map &:to_i}

fact = (1..n).each_with_object([1]){|i,o|o << o[-1]*i}

p q.inject(0){|s,r|
  left = *1..n
  r.each.with_index{|ai,i|
    s -= left.index(ai)*fact[n-1-i]
    left.delete(ai)
  }
  s.abs
}
