結果
| 問題 |
No.927 Second Permutation
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2019-11-23 06:03:55 |
| 言語 | OCaml (5.2.1) |
| 結果 |
AC
|
| 実行時間 | 36 ms / 2,000 ms |
| コード長 | 1,111 bytes |
| コンパイル時間 | 222 ms |
| コンパイル使用メモリ | 19,840 KB |
| 実行使用メモリ | 6,820 KB |
| 最終ジャッジ日時 | 2024-10-09 00:50:25 |
| 合計ジャッジ時間 | 2,101 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 27 |
ソースコード
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
;;