let rec select acc trace = function
  | [] -> acc
  | x :: xs -> select ((trace, x, xs) :: acc) (x :: trace) xs
let select xs = select [] [] xs

(* 与えられたリストからn要素を選ぶ順列 *)
let rec perm : int -> 'a list -> 'a list list = fun n xs ->
  match n, xs with
  | 0, _ -> [[]]
  | _, [] -> []
  | n, xs ->
      List.concat @@
        List.map (fun (xs, x, ys) ->
          List.map (fun xs -> x :: xs) @@
            perm (n - 1) @@ List.rev_append xs ys) @@ select xs;;


let () = Scanf.scanf "%d\n" @@ fun n ->
  let ps = Array.to_list @@ Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun p -> p in
  let qs = Array.to_list @@ Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun q -> q in
  let perms = 
    List.mapi (fun i xs -> (i, xs)) @@
    List.sort compare @@
    perm n @@
    Array.to_list @@
    Array.init n succ in
  Printf.printf "%d\n" @@ abs @@
  fst (List.find (fun (_, xs) -> xs = ps) perms)
  - fst (List.find (fun (_, xs) -> xs = qs) perms)


