type 'a mutable_list = Nil | Cons of 'a * 'a mutable_list ref

(* 与えられたリストからn要素を選ぶ順列 *)
let perm n xs =
  let head = ref Nil in
  ignore (List.fold_left (fun tail x ->
    let tail' = ref Nil in
    tail := Cons (x, tail'); tail') head xs);
  let rec perm_aux ys n ptr acc =
    if n <= 0
    then ys :: acc
    else match !ptr with
         | Nil -> acc
         | (Cons (x, next)) as here ->
             let acc = perm_aux ys n next acc in
             ptr := !next; (* リストからconsセルhereを削除 *)
             (* consセルを削除したリストから，n-1要素を選ぶ *)
             let acc = perm_aux (x :: ys) (n - 1) head acc in
             ptr := here; (* consセルを戻す *)
             acc in
  perm_aux [] n head []

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, List.rev xs)) @@
    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)

