{-# LANGUAGE FlexibleInstances #-}

import Data.List

-- stdin
class In a where stdin :: IO a
instance In [Int] where stdin = map read . words <$> getLine

type N = Int
type ChunkCount = Int

getIndex :: [Int] -> Int
getIndex ns = treeBottom (search ns []) [1..(product ns)]
  where
    -- [3, 2, 1, 4] []                       -> [(2, 4)]
    -- [2, 1, 4]    [(2, 4)]                 -> [(2, 4), (1, 3)]
    -- [1, 4]       [(2, 4), (1, 3)]         -> [(2, 4), (1, 3), (0, 2)]
    -- [4]          [(2, 4), (1, 3), (0, 2)] -> [(2, 4), (1, 3), (0, 2), (0, 1)]
    search :: [Int] -> [(N, ChunkCount)] -> [(N, ChunkCount)]
    search [] acc = acc
    search all@(n:ns) acc = search ns $ acc ++ [(indexOf n all, length all)]

    indexOf x xs = length $ takeWhile (/=x) $ sort xs

    -- [(2, 4), (1, 3), (0, 2), (0, 1)] [1..24] -> 15
    treeBottom :: [(N, ChunkCount)] -> [Int] -> Int
    treeBottom [] [n] = n
    treeBottom ((n,cc):remains) ns = treeBottom remains $ chunk ns cc !! n
      where
        -- [1, 2, 3, 4, 5, 6] -> [[1, 2], [3, 4], [5, 6]]
        chunk :: [Int] -> ChunkCount -> [[Int]]
        chunk ns n = chunk_ ns (length ns `div` n) []
          where
            chunk_ [] _ acc = acc
            chunk_ ns len acc = chunk_ (drop len ns) len (acc ++ [take len ns])

main = do
    _ <- getLine
    a <- stdin
    b <- stdin

    print $ abs (getIndex a - getIndex b)
