Scanf.scanf "%d %d" (fun k t ->
    let a = Array.init t (fun i -> Scanf.scanf " %d" (fun a -> a, i)) in
    let rec loop rest prev acc =
        if rest = 0 then acc else (
            Array.sort (fun a b -> compare b a) a;
            let ma, mi = a.(0) in
            if mi <> prev then (
                a.(0) <- ma - 1, mi;
                loop (rest - 1) mi acc
            ) else (
                if t = 1 ||
                    let na, ni = a.(1) in
                    na = 0 then (
                        a.(0) <- ma - 1, mi;
                        loop (rest - 1) mi (acc + 1)
                    ) else (
                        let na, ni = a.(1) in
                        a.(1) <- na - 1, ni;
                        loop (rest - 1) ni acc
                    )
            )
        )
    in
    loop k (-1) 0 |> Printf.printf "%d\n"
)