main = do
    (n : m : _) <- getLine >>= readLst
    ps <- getLine >>= readLst
    let lstcs = [1 .. n] `zip` [[] | _ <- [1 ..]] ++ ps `zip` ((: []) `map` [2 ..])
    let mcs = M.fromListWith (flip (++)) lstcs
    let arrcs = array (1, n) (M.toList mcs)
    let lstlvs = buildlvs arrcs 1 1
    let arrlvs = array (1, n) lstlvs
    let (_, lstns) = buildns arrcs arrlvs [] (0, []) 1
    let arrns = array (1, n) lstns
    let (lstseq, lstmap, finalix) = buildrmq ([], [], 1) arrcs arrlvs 1
    let arrseq = array (1, finalix - 1) lstseq
    let leftmap = M.toList $ M.fromListWith min lstmap
    let rightmap = M.toList $ M.fromListWith max lstmap
    let arrlm = array (1, n) leftmap
    let arrrm = array (1, n) rightmap
    let (minn, lcast) = buildst arrseq 1 (pred finalix)
    tst (arrlvs, arrns, (lcast, arrlm, arrrm)) m
    --return ()
main = do
    (n : m : _) <- getLine >>= readLst
    ps <- getLine >>= readLst
    let lstcs = [1 .. n] `zip` [[] | _ <- [1 ..]] ++ ps `zip` ((: []) `map` [2 ..])
    let mcs = M.fromListWith (flip (++)) lstcs
    let arrcs = array (1, n) (M.toList mcs)
    let lstlvs = buildlvs arrcs 1 1
    let arrlvs = array (1, n) lstlvs
    let (_, lstns) = buildns arrcs arrlvs [] (0, []) 1
    let arrns = array (1, n) lstns
    let (lstseq, lstmap, finalix) = buildrmq ([], [], 1) arrcs arrlvs 1
    let arrseq = array (1, finalix - 1) lstseq
    let leftmap = M.toList $ M.fromListWith min lstmap
    let rightmap = M.toList $ M.fromListWith max lstmap
    let arrlm = array (1, n) leftmap
    let arrrm = array (1, n) rightmap
    let (minn, lcast) = buildst arrseq 1 (pred finalix)
    tst (arrlvs, arrns, (lcast, arrlm, arrrm)) m
    --return ()
main = do
    (n : m : _) <- getLine >>= readLst
    ps <- getLine >>= readLst
    let lstcs = [1 .. n] `zip` [[] | _ <- [1 ..]] ++ ps `zip` ((: []) `map` [2 ..])
    let mcs = M.fromListWith (flip (++)) lstcs
    let arrcs = array (1, n) (M.toList mcs)
    let lstlvs = buildlvs arrcs 1 1
    let arrlvs = array (1, n) lstlvs
    let (_, lstns) = buildns arrcs arrlvs [] (0, []) 1
    let arrns = array (1, n) lstns
    let (lstseq, lstmap, finalix) = buildrmq ([], [], 1) arrcs arrlvs 1
    let arrseq = array (1, finalix - 1) lstseq
    let leftmap = M.toList $ M.fromListWith min lstmap
    let rightmap = M.toList $ M.fromListWith max lstmap
    let arrlm = array (1, n) leftmap
    let arrrm = array (1, n) rightmap
    let (minn, lcast) = buildst arrseq 1 (pred finalix)
    tst (arrlvs, arrns, (lcast, arrlm, arrrm)) m
    --return ()