結果

問題 No.927 Second Permutation
ユーザー pekempeypekempey
提出日時 2019-11-23 06:03:55
言語 OCaml
(5.1.0)
結果
AC  
実行時間 36 ms / 2,000 ms
コード長 1,111 bytes
コンパイル時間 206 ms
コンパイル使用メモリ 19,828 KB
実行使用メモリ 6,944 KB
最終ジャッジ日時 2024-04-17 08:50:38
合計ジャッジ時間 1,846 ms
ジャッジサーバーID
(参考情報)
judge4 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
6,812 KB
testcase_01 AC 2 ms
6,940 KB
testcase_02 AC 1 ms
6,944 KB
testcase_03 AC 1 ms
6,940 KB
testcase_04 AC 2 ms
6,940 KB
testcase_05 AC 2 ms
6,940 KB
testcase_06 AC 2 ms
6,940 KB
testcase_07 AC 1 ms
6,940 KB
testcase_08 AC 13 ms
6,940 KB
testcase_09 AC 2 ms
6,940 KB
testcase_10 AC 20 ms
6,940 KB
testcase_11 AC 33 ms
6,944 KB
testcase_12 AC 15 ms
6,944 KB
testcase_13 AC 4 ms
6,940 KB
testcase_14 AC 22 ms
6,944 KB
testcase_15 AC 15 ms
6,940 KB
testcase_16 AC 36 ms
6,940 KB
testcase_17 AC 36 ms
6,940 KB
testcase_18 AC 35 ms
6,940 KB
testcase_19 AC 36 ms
6,940 KB
testcase_20 AC 36 ms
6,940 KB
testcase_21 AC 35 ms
6,940 KB
testcase_22 AC 36 ms
6,940 KB
testcase_23 AC 35 ms
6,940 KB
testcase_24 AC 4 ms
6,944 KB
testcase_25 AC 3 ms
6,940 KB
testcase_26 AC 3 ms
6,944 KB
testcase_27 AC 12 ms
6,940 KB
testcase_28 AC 29 ms
6,940 KB
testcase_29 AC 23 ms
6,940 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

open Scanf ;;
open Printf ;;

exception Invalid_input ;;

let string_to_array s = Array.init (String.length s) (fun i -> s.[i]) ;;
let array_to_string s = String.init (Array.length s) (fun i -> s.(i)) ;;

let find_index f a =
  let n = Array.length a in
  let rec loop i =
    if i = n then None
    else if f a.(i) then Some i
    else loop (i + 1) in
  loop 0
  ;;

let swap i j a =
  let tmp = a.(i) in
  a.(i) <- a.(j);
  a.(j) <- tmp
  ;;

let next_permutation a =
  let n = Array.length a in
  let rec loop i =
    if i = -1 then raise Invalid_input
    else if a.(i) > a.(i + 1) then swap i (i + 1) a
    else loop (i - 1) in
  loop (n - 2)
  ;;

let () =
  let a = read_line () |> string_to_array in
  if Array.for_all (fun x -> x = a.(0)) a then
    print_endline "-1"
  else begin
    Array.sort (fun x y -> compare y x) a;
    begin match find_index (fun x -> x <> '0') a with
    | None -> raise Invalid_input
    | Some k -> 
      swap 0 k a;
      next_permutation a;
      if a.(0) <> '0' then
        array_to_string a |> print_endline
      else
        print_endline "-1"
    end
  end
  ;;

0