let for_range s e step f =
  let rec loop i =
    if i > e then ()
    else
      begin f i;loop (i + step) end
  in loop s;;

let a =
  let num = 1000000 in
  let p = Array.init (num+1) (fun x -> 1) in
  let rec loop i =
    if i*i < num then
      begin
        if p.(i) = 1 then
          for_range (i+i) num i (fun x -> p.(x) <- 0);
        loop (i+2)
      end
  in
  p.(0) <- 0; p.(1)<-(0);
  for_range 4 num 2 (fun x -> p.(x) <- 0);
  loop 3;
  for i = 1 to num-1 do
    p.(i) <- p.(i) + p.(i-1);
  done;
  let rec read () =
    try let n = read_int () in
        Printf.printf "%d\n" p.(n);
        read ()
    with End_of_file -> ()
  in read ();;

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Prime Number

Write a program which reads an integer n and prints the number of prime numbers which are less than or equal to n. A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.

Input

Input consists of several datasets. Each dataset has an integer n (1 ≤ n ≤ 999,999) in a line.

The number of datasets is less than or equal to 30.

Output

For each dataset, prints the number of prime numbers.

Sample Input

10
3
11

Output for the Sample Input

4
2
5

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


let m=1000000open Array;;let a,b=make m 1,make m 0;;a.(0)<-0;;let rec($)i j=if i*j<m then(a.(i*j)<-0;i$(j+1));;for i=2to m-1do if a.(i)=1then i$2;b.(i)<-b.(i-1)+a.(i)done;;let rec f()=f(Printf.printf"%d
"b.(read_int()));;try f()with _->()


let for_range s e step f =
  let rec loop i =
    if i <= e then begin f i;loop (i + step) end
  in loop s;;

let sieve num =
  let p = Array.init num (fun x -> x mod 2) in
  let rec loop i =
    if i*i < num then
      begin
        if p.(i) = 1 then for_range (i*i) num (i*2) (fun x -> p.(x) <- 0);
        loop (i+2)
      end
  in
  p.(0) <- 0; p.(1)<-(0);p.(2)<-1;loop 3;
  for i = 3 to num-1 do
    p.(i) <- p.(i) + p.(i-1);
  done;
  p
;;

let _ =
  let p = sieve 1000000 in
  let rec read () =
    try let n = read_int () in
        Printf.printf "%d\n" p.(n);
        read ()
    with End_of_file -> ()
  in read ()
;;


open Scanf

let iota ?(init=0) ?(step=1) n =
  let rec iota i n acc =
    if i = 0 then List.rev acc
    else iota (i - 1) (n + step) (n :: acc) in
  iota n init []

let rec primes last =
  if last < 2 then []
  else if last = 2 then [2]
  else if last mod 2 = 0 then primes (last - 1)
  else
    let index n = (n - 3) / 2 in
    let value i = 2 * i + 3 in
    let last_index = index last in
    let sieve = Array.make (last_index + 1) true in
    let rec mark i step =
      if i < Array.length sieve then begin
        sieve.(i) <- false;
        mark (i + step) step
      end
      else () in
    let primes = ref [2] in
    for i = 0 to last_index do
      if sieve.(i) then begin
        primes := (value i) :: !primes;
        mark (2 * i * i + 6 * i + 3) (value i)
      end
    done;
    !primes

let rec matches budget prices =
  if budget = 0 then true
  else
    match prices with
      | [] -> false
      | price :: prices when price > budget -> matches budget prices
      | price :: prices' ->
         try
           List.rev_map
             (fun m -> budget - price * m)
             (iota ~init:1 (budget / price))
           |> List.exists (fun budget -> matches budget prices')
         with Not_found -> matches budget prices'

let read_lines n =
  let rec read_lines n acc =
    if n = 0 then List.rev acc
    else read_lines (pred n) ((read_line ())::acc) in
  read_lines n []

let rec solve () =
  sscanf
    (read_line ()) "%d %d"
    (fun n budget ->
     if n = 0 && budget = 0 then ()
     else
       let prices =
         List.map int_of_string (read_lines n)
         |> List.sort (fun (a : int) b -> compare b a) in
       let result =
         try
           List.find (fun prime -> matches prime prices) (primes budget)
           |> string_of_int
         with Not_found -> "NA" in
       print_endline result;
       solve ())

let () = solve ()

上司のおごり

会津太郎さんの会社には、割り切れない事が大嫌いな上司がいます。太郎さんがその上司と食事に行くときは、割り勘で会計をしているのですが、支払金額が参加人数で割り切れないときは、いつも上司がおごってくれています。

ある日、太郎さんは食事会の幹事になりました。お金の少ない太郎さんは、その上司を誘ってなんとかおごってもらえるように出来ないか考えました。もう料理屋に注文をしなければならないのですが、まだ何人参加するかは分からないので、どんな人数が参加してもおごってもらえるような注文をしておきたいようです。太郎さんの同期で、同じく食事会に参加する予定のあなたは、太郎さんに協力して、予算額以下で最大のどんな人数でも割り切れない金額を算出することにしました。

料理の種類、各料理の料金、予算額を入力とし、予算額以下で最大のどんな数字でも割り切れない合計金額(ただし、 1 と合計金額は除く)を出力するプログラムを作成してください。なお、各種類の料理は複数個注文できますが、全種類の料理を注文する必要はありません。ただし、このような合計金額がない場合は、 NA と出力してください。

Input

複数のデータセットの並びが入力として与えられます。 入力の終わりはゼロふたつの行で示されます。
各データセットは以下の形式で与えられます。

n x
v1
v2
:
vn

1 行目に料理の種類 n (1 ≤ n ≤ 30) と予算額 x (1 ≤ x ≤ 1000000) が空白区切りで与えられます。続くn 行に i 種類目の料理の金額を表す整数 vi (1 ≤ vi ≤ 1000000) が与えられます。

データセットの数は 100 を超えません。

Output

入力データセットごとに、予算額に最も近い合計金額、または NA を１行に出力します。

Sample Input

4 15000
305
260
129
500
3 400
10
20
30
3 200909
5
9
12
0 0

Output for the Sample Input

14983
NA
200909


open Printf
open Scanf

let id x = x

let solve m n sg =
  let am = Array.make_matrix (n + 2) (n + 2) false in
  let que = Queue.create () in
  let ars = Array.make (n + 2) false in
  let arg = Array.make (n + 2) false in
  for i = 0 to n do
    for j = 1 to m do
      let k = if i + j >= n + 1 then n + 1 else i + j + sg.(i + j) in
      am.(i).(min (max 0 k) (n + 1)) <- true
    done
  done;
  Queue.push 0 que;
  ars.(0) <- true;
  while (not (Queue.is_empty que)) do
    let i = Queue.pop que in
    for j = 0 to n + 1 do
      if am.(i).(j) then
        begin
          if ars.(j) then ()
          else begin
              ars.(j) <- true;
              Queue.push j que
            end
        end
      else ()
    done
  done;
  Queue.push (n + 1) que;
  arg.(n + 1) <- true;
  while (not (Queue.is_empty que)) do
    let i = Queue.pop que in
    for j = 0 to n + 1 do
      if am.(j).(i) then
        begin
          if arg.(j) then ()
          else begin
              arg.(j) <- true;
              Queue.push j que
            end
        end
      else ()
    done
  done;
  let rec iter i =
    if i = n + 2 then printf "OK\n"
    else if ars.(i) && not arg.(i) then
      printf "NG\n"
    else iter (i + 1) in
  iter 0

let () =
  let rec loop () =
    let m = scanf "%d " id in
    if m = 0 then ()
    else
      begin
        let n = scanf "%d " id in
        let sg = Array.make (n + 2) 0 in
        for i = 1 to n do
          let d = scanf "%d " id in
          sg.(i) <- d
        done;
        solve m n sg;
        loop ()
      end
  in loop ()

すごろくを作る

太郎君は、子供会の催しでみんなで遊べるようにすごろくを作りました。ゲームをおもしろくするために、「ふりだし」と「あがり」以外のすごろくのマスのいくつかに「６つ進む」、「５つ戻る」のように指示を書き込んでいきました。ルーレットを回して出た数だけ進み、止まったマスに指示が書き込んであれば、その指示に従って移動します。ただし、指示に従って進んだ先のマスの指示には従いません。

ルーレットは１からある数までの間の数を等確率で出すことができるものとします。また、「あがり」に達するより大きな数が出たときや、指示に従うと「あがり」より先に進んでしまうときは「あがり」に移動します。指示に従って戻るときに「ふりだし」より前に戻ってしまうときは「ふりだし」に戻ることにします。

ところが、ルーレットとマスの指示によっては「あがり」にたどりつけない場合が出てきてしまいます。たとえば、図のようなすごろくを作ったとしましょう。１と２しか出ないルーレットを使うと、１，２の順に出れば「あがり」に行けますが、はじめに２が出たらその後は何が出ても永久に「あがり」にはたどり着けません。太郎君は、そうとは知らずに調子に乗ってあちこちのマスに指示を書き込んでしまいました。

そこで、太郎君に代わって、ルーレットとマスの指示によっては、「あがり」にたどり着けない場合が生じるかどうか判定するプログラムを作成してください。

入力

入力は複数のデータセットからなる。入力の終わりはゼロ１つの行で示される。各データセットは以下の形式で与えられる。

max
n
d1
d2
.
.
.
dn

１行目にルーレットが出す数の最大値 max (2 ≤ max ≤ 250) が与えられ、２行目に「ふりだし」と「あがり」以外のマスの数 n (2 ≤ n ≤ 250) が与えられる。続く n 行に各マスの指示を表す数 di(-n ≤ di ≤ n) が与えられる。di がゼロのときは指示が書いていないことを、正の数のときは |di| 進む指示を、負の数のときは |di| 戻る指示を表す（ここで、|x| は x の絶対値を表す）。入力される値はすべて整数である。

データセットの数は 100 を超えない。

出力

各データセットごとに判定結果を１行に出力する。ルーレットとマスの指示によっては、「あがり」にたどり着けない場合が生じるときは「NG」、そうでなければ「OK」を出力する。

入力例

3
3
-2
1
0
2
4
2
0
-1
-2
2
2
-2
-2
0

出力例

OK
NG
NG


type trays = Tray of int list * int list * int list

type move_command = AB | BA | BC | CB

let finished = function
  | Tray (_, [], []) | Tray ([], [], _) -> true
  | _ -> false

let move (Tray (as_, bs, cs)) command =
  let move xs ys = match xs, ys with
    | x :: xs, [] -> (xs, [x])
    | x :: xs, y :: ys when x > y -> (xs, x :: y :: ys)
    | _ -> invalid_arg "move" in
  try
    Some
      begin
        match command with
        | AB -> let as_, bs = move as_ bs in Tray (as_, bs, cs)
        | BA -> let bs, as_ = move bs as_ in Tray (as_, bs, cs)
        | BC -> let bs, cs = move bs cs in Tray (as_, bs, cs)
        | CB -> let cs, bs = move cs bs in Tray (as_, bs, cs)
      end
  with Invalid_argument _ -> None

let next_states state =
  List.fold_left
    (fun acc ->
     function
     | None -> acc
     | Some s -> s :: acc)
    []
  @@ List.map (move state) [CB; BC; BA; AB]

let search initial_state max_swaps =
  let states = Queue.create () in
  Queue.push (initial_state, 0) states;
  let seen = Hashtbl.create 1024 in
  let rec search () =
    if Queue.length states = 0 then -1
    else
      let state, count = Queue.pop states in
      if finished state then count
      else if count > max_swaps then -1
      else if Hashtbl.mem seen state then search ()
      else
        begin
          Hashtbl.add seen state true;
          List.iter
            (fun next_state -> Queue.push (next_state, succ count) states)
            @@ List.filter
                 (fun state -> not @@ Hashtbl.mem seen state)
                 (next_states state);
          search ()
        end in
  search ()

let read_lines n =
  let rec read_lines n acc =
    if n = 0 then List.rev acc
    else read_lines (pred n) ((read_line ()) :: acc) in
  read_lines n []

let split str delim =
  let len = String.length str in
  let rec split offset acc =
    try
      let index = String.index_from str offset delim in
      split (index + 1) ((String.sub str offset (index - offset)) :: acc)
    with Not_found -> List.rev ((String.sub str offset (len - offset)) :: acc) in
  split 0 []

let rec solve () =
  let read_tray () =
    List.rev @@ List.tl @@ List.map int_of_string @@ split (read_line ()) ' ' in
  let line = read_line () in
  let n_cups, max_swaps = Scanf.sscanf line "%d %d" (fun n m -> (n, m)) in
  if (n_cups, max_swaps) = (0, 0) then ()
  else
    let tray_a = read_tray () in
    let tray_b = read_tray () in
    let tray_c = read_tray () in
    print_endline @@ string_of_int
    @@ search (Tray (tray_a, tray_b, tray_c)) max_swaps;
    solve ()

let () = solve ()

大きさが異なる n 個のコップと 3 つのトレイ（お盆）A，B，C があり，それらのコップは 3 つのトレイの上にそれぞれ何個かずつ一山に重ねて置かれている．ただし，どのトレイにおいても，そのトレイの中で一番小さいコップが一番下に， 2 番目に小さいコップがその上に， 3 番目に小さいコップがその上にと，小さい順に伏せて重ねてある．例えば，下図の右側は， n = 5 個のコップがトレイ A，B，C にそれぞれ 2 個，0 個，3 個重ねて置かれている状態を示している．

このように，コップの初期状態が与えられたとき，次の規則 1 〜 3 を守りながら，すべてのコップを A または C のどちらかのトレイに移動させるには何回移動を行えばよいかを求めたい．

（規則 1） 1 回に 1 つのコップだけを移動させることができる．それは，そのトレイにあるコップの中で一番上のコップ（つまり，一番大きいコップ）である．

（規則 2）大きいコップの上に小さいコップを重ねてはいけない．

（規則 3）コップ 1 個の直接移動は，トレイ A から B，B から A，B から C，C から B のみが許され， A から C への直接移動や C から A への直接移動は許されない．

　n 個のコップの初期状態と整数 m が与えられたとき， m 回以内の移動で， A または C のどちらかのトレイにすべてのコップをまとめて重ねることができるかどうかを判定し，可能な場合には移動回数の最小値を，不可能な場合には -1 を出力するプログラムを作成しなさい．

　入力ファイルの 1 行目には， n と m がこの順に空白を区切り文字として書いてある． 1 ≦ n ≦ 15 であり， 1 ≦ m ≦ 15000000 である． 2 行目，3 行目，4 行目には， 1 から n までの整数を何個かずつ 3 つのグループに分けて，それぞれのグループ内で小さい順（昇順）に並べたものが書いてある．ただし，各行の先頭（それらの整数の前）には，それらの個数が書いてある． 2 行目に書かれている整数（先頭の 1 つを除く）はトレイ A の上に重ねられている各コップの大きさを表す．同様に， 3 行目に書かれている整数（先頭の 1 つを除く）はトレイ B の上に重ねられている各コップの大きさを表し， 4 行目に書かれている整数（先頭の１つを除く）はトレイ C の上に重ねられている各コップの大きさを表す．

入力例１

入力例２

入力例３

入力例４

3 10

4 20

2 5

3 3

0

2 1 2

2 1 2

0

1 1

1 3

0

1 1

2 2 3

1 4

0

2 2 3

出力例１

出力例２

出力例３

出力例４

9

3

0

-1

入力

入力は複数のデータセットからなる．n, m がともに 0 のとき入力が終了する．データセットの数は 5 を超えない．

出力

データセットごとに、移動回数または -1 を１行に出力する．

入力例

3 10
0
1 1
2 2 3
4 20
2 1 2
1 3
1 4
2 5
2 1 2
0
0
3 3
0
1 1
2 2 3
0 0

出力例

9
3
0
-1

各データセットの出力（移動回数または -1）の後に改行を入れること．

上記問題文と自動審判に使われるデータは、情報オリンピック日本委員会が作成し公開している問題文と採点用テストデータです。


let init n f =
  let rec loop i l = if i < n then loop (i + 1) (f i :: l) else l in
  List.rev (loop 0 [])

let n = Scanf.scanf "%d\n" (fun n -> n)
let ps = init n (fun _ -> Scanf.scanf " %c" (fun c -> c = 'T'))
let b = match ps with
    p :: ps -> List.fold_left (fun b p -> not b || p) p ps
  | _ -> raise (Failure "")
let () = if b then
           print_endline "T"
         else
           print_endline "F"

B: たぬきつね

問題

謎の装置 $M$ があり,この装置に Tanuki と Fox を入れると, 装置から一匹の動物が出てくる（以下, Tanuki を $T$ ,Foxを $F$ とする）.

$M(x, y)$ は,装置 $M$ に $x, y$ の順で動物を入れて出てきた動物を表す.

色々試した結果,以下のことがわかった.

$M(T, T) = T$

$M(T, F) = F$

$M(F, T) = T$

$M(F, F) = T$

あなたは,一列に並んでいる動物たち $P_1, P_2, ... , P_N$ を以下のように装置に入れていった.

$M(....M(M(P_1,P_2), P_3)...., P_N)$

最後に出てくる動物を答えよ.

制約

$2 \leq N \leq 10^{5}$

$P_i$ は $T$ か $F$ の一文字

入力形式

入力は以下の形式で与えられる.

$N$

$P_1\ P_2\ ...\ P_N$

出力

最後に出てくる動物を表す文字 $T$ または $F$ を出力せよ.また,末尾に改行も出力せよ.

サンプル

サンプル入力 1

3
F T T

サンプル出力 1

T

サンプル入力 2

7
F T T F T T F

サンプル出力 2

F


let lcs (x, y) =
  let m = String.length x in
  let n = String.length y in
  let dp = Array.make_matrix (m + 1) (n + 1) 0 in
  for i = 1 to m do
    for j = 1 to n do
      dp.(i).(j) <-
        if x.[i-1] = y.[j-1] then dp.(i-1).(j-1) + 1
        else if dp.(i-1).(j) > dp.(i).(j-1) then dp.(i-1).(j)
        else dp.(i).(j-1)
    done
  done;
  dp.(m).(n)

let () =
  let q = read_int () in
  for _ = 0 to q - 1 do
    Scanf.scanf "%s\n%s\n" (fun x y -> (x, y)) |> lcs |> Printf.printf "%d\n"
  done

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Longest Common Subsequence

For given two sequences $X$ and $Y$, a sequence $Z$ is a common subsequence of $X$ and $Y$ if $Z$ is a subsequence of both $X$ and $Y$. For example, if $X = \{a,b,c,b,d,a,b\}$ and $Y = \{b,d,c,a,b,a\}$, the sequence $\{b,c,a\}$ is a common subsequence of both $X$ and $Y$. On the other hand, the sequence $\{b,c,a\}$ is not a longest common subsequence (LCS) of $X$ and $Y$, since it has length 3 and the sequence $\{b,c,b,a\}$, which is also common to both $X$ and $Y$, has length 4. The sequence $\{b,c,b,a\}$ is an LCS of $X$ and $Y$, since there is no common subsequence of length 5 or greater.

Write a program which finds the length of LCS of given two sequences $X$ and $Y$. The sequence consists of alphabetical characters.

Input

The input consists of multiple datasets. In the first line, an integer $q$ which is the number of datasets is given. In the following $2 \times q$ lines, each dataset which consists of the two sequences $X$ and $Y$ are given.

Output

For each dataset, print the length of LCS of $X$ and $Y$ in a line.

Constraints

$1 \leq q \leq 150$

$1 \leq$ length of $X$ and $Y$ $\leq 1,000$

$q \leq 20$ if the dataset includes a sequence whose length is more than 100

Sample Input 1

3
abcbdab
bdcaba
abc
abc
abc
bc

Sample Output 1

4
3
2

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


let split_on_char sep s =
  let open String in
  let r = ref [] in
  let j = ref (length s) in
  for i = length s - 1 downto 0 do
    if get s i = sep then begin
      r := sub s (i + 1) (!j - i - 1) :: !r;
      j := i
    end
  done;
  sub s 0 !j :: !r

let read_ints () = read_line () |> split_on_char ' ' |>  List.map int_of_string

let dfs vs n =
  let d = Array.make n (-1) in
  let rec doit i j =
    d.(i) <- j;
    List.iter (fun v -> if d.(v) = (-1) then doit v j) vs.(i) in
  Array.iteri (fun i e -> if e = (-1) then doit i i) d;
  d

let solve n m =
  let g = Array.make n [] in
  for _ = 0 to m - 1 do
    match read_ints () with
    | [s; t] ->
      g.(s) <- t :: g.(s);
      g.(t) <- s :: g.(t);
    | _ -> assert false
  done;
  let v = dfs g n in
  let q = read_int () in
  for _ = 0 to q - 1 do
    match read_ints () with
    | [s; t] -> print_endline (if v.(s) = v.(t) then "yes" else "no")
    | _ -> assert false
  done

let () =
  match read_ints () with
  | [n;m] -> solve n m
  | _ -> assert false

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Connected Components

Write a program which reads relations in a SNS (Social Network Service), and judges that given pairs of users are reachable each other through the network.

Input

In the first line, two integer $n$ and $m$ are given. $n$ is the number of users in the SNS and $m$ is the number of relations in the SNS. The users in the SNS are identified by IDs $0, 1, ..., n-1$.

In the following $m$ lines, the relations are given. Each relation is given by two integers $s$ and $t$ that represents $s$ and $t$ are friends (and reachable each other).

In the next line, the number of queries $q$ is given. In the following $q$ lines, $q$ queries are given respectively. Each query consists of two integers $s$ and $t$ separated by a space character.

Output

For each query, print "yes" if $t$ is reachable from $s$ through the social network, "no" otherwise.

Constraints

$2 \leq n \leq 100,000$

$0 \leq m \leq 100,000$

$1 \leq q \leq 10,000$

Sample Input

10 9
0 1
0 2
3 4
5 7
5 6
6 7
6 8
7 8
8 9
3
0 1
5 9
1 3

Sample Output

yes
yes
no


module MakeBinaryHeap (M : sig type t val compare : t -> t -> int end) = struct

  type t = { node : M.t array; mutable size : int }

  let make n (init : M.t) = { node = Array.make n init; size = 0 }

  let empty_p t = if t.size = 0 then true else false

  let pop t =
    if t.size <= 0 then failwith "out of size" else
    let rec max_heapify i =
      let l = 2*i in
      let r = 2*i + 1 in
      let m = if l <= t.size && M.compare t.node.(l) t.node.(i) > 0 then l else i in
      let m = if r <= t.size && M.compare t.node.(r) t.node.(m) > 0 then r else m in
      if m = i then ()
      else begin
        let tmp = t.node.(i) in
        t.node.(i) <- t.node.(m);
        t.node.(m) <- tmp;
        max_heapify m
      end in
    let ret = t.node.(1) in
    t.node.(1) <- t.node.(t.size);
    t.size <- t.size - 1;
    max_heapify 1;
    ret

  let push x t =
    let parent i = int_of_float (floor (float_of_int i) /. 2.) in
    let rec doit i =
      let p = parent i in
      if i <= 1 || M.compare t.node.(p) t.node.(i) >= 0 then ()
      else begin
        let tmp = t.node.(i) in
        t.node.(i) <- t.node.(p);
        t.node.(p) <- tmp;
        doit p
      end in
    t.size <- t.size + 1;
    t.node.(t.size) <- x;
    doit t.size

end

module H = MakeBinaryHeap(struct type t = (int * int) let compare (_, x) (_, y) = y - x end)

let dijkstra g n =
  let reached_p = Array.make n false in
  let min_costs = Array.make n max_int in
  min_costs.(0) <- 0;
  let h = H.make 500000 (0, 0) in
  H.push (0, 0) h;
  while not (H.empty_p h) do
    let (u, x) = H.pop h in
    reached_p.(u) <- true;
    if x > min_costs.(u) then ()
    else
      List.iter (fun (v, c) ->
        let x = min_costs.(u) + c in
        if not reached_p.(v) && x < min_costs.(v) then begin
          min_costs.(v) <- x;
          H.push (v, x) h;
        end) g.(u);
  done;
  min_costs

let rec make_pair acc = function
  | [] -> acc
  | v :: c :: tl -> make_pair ((v, c) :: acc) tl
  | _ -> assert false

let make_pair lst = make_pair [] lst

let split_on_char sep s =
  let open String in
  let r = ref [] in
  let j = ref (length s) in
  for i = length s - 1 downto 0 do
    if get s i = sep then begin
      r := sub s (i + 1) (!j - i - 1) :: !r;
      j := i
    end
  done;
  sub s 0 !j :: !r

let () =
  let n = read_int () in
  let g = Array.make n [] in
  for _ = 0 to n - 1 do
    match read_line () |> split_on_char ' ' |> List.map int_of_string with
    | u :: _ :: l -> g.(u) <- make_pair l
    | _ -> assert false
  done;
  dijkstra g n |> Array.iteri (fun i e -> Printf.printf "%d %d\n" i e)

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Single Source Shortest Path II

For a given weighted graph $G = (V, E)$, find the shortest path from a source to each vertex. For each vertex $u$, print the total weight of edges on the shortest path from vertex $0$ to $u$.

Input

In the first line, an integer $n$ denoting the number of vertices in $G$ is given. In the following $n$ lines, adjacency lists for each vertex $u$ are respectively given in the following format:

$u$ $k$ $v_1$ $c_1$ $v_2$ $c_2$ ... $v_k$ $c_k$

Vertices in $G$ are named with IDs $0, 1, ..., n-1$. $u$ is ID of the target vertex and $k$ denotes its degree. $v_i (i = 1, 2, ... k)$ denote IDs of vertices adjacent to $u$ and $c_i$ denotes the weight of a directed edge connecting $u$ and $v_i$ (from $u$ to $v_i$).

Output

For each vertex, print its ID and the distance separated by a space character in a line respectively. Print in order of vertex IDs.

Constraints

$1 \leq n \leq 10,000$

$0 \leq c_i \leq 100,000$

$|E| < 500,000$

All vertices are reachable from vertex $0$

Sample Input 1

5
0 3 2 3 3 1 1 2
1 2 0 2 3 4
2 3 0 3 3 1 4 1
3 4 2 1 0 1 1 4 4 3
4 2 2 1 3 3

Sample Output 1

0 0
1 2
2 2
3 1
4 3

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


module MakeBinaryHeap (M : sig type t val compare : t -> t -> int end) = struct

  type t = { node : M.t array; mutable size : int }

  let make n (init : M.t) = { node = Array.make n init; size = 0 }

  let empty_p t = if t.size = 0 then true else false

  let pop t =
    let rec max_heapify i =
      let l = 2*i in
      let r = 2*i + 1 in
      let m = if l <= t.size && M.compare t.node.(l) t.node.(i) > 0 then l else i in
      let m = if r <= t.size && M.compare t.node.(r) t.node.(m) > 0 then r else m in
      if m = i then ()
      else begin
        let tmp = t.node.(i) in
        t.node.(i) <- t.node.(m);
        t.node.(m) <- tmp;
        max_heapify m
      end in
    let ret = t.node.(1) in
    t.node.(1) <- t.node.(t.size);
    t.size <- t.size - 1;
    max_heapify 1;
    ret

  let push x t =
    let parent i = int_of_float (floor (float_of_int i) /. 2.) in
    let rec doit i =
      let p = parent i in
      if i <= 1 || M.compare t.node.(p) t.node.(i) >= 0 then ()
      else begin
        let tmp = t.node.(i) in
        t.node.(i) <- t.node.(p);
        t.node.(p) <- tmp;
        doit p
      end in
    t.size <- t.size + 1;
    t.node.(t.size) <- x;
    doit t.size

end

module H = MakeBinaryHeap(struct type t = (int * int) let compare (_, x) (_, y) = y - x end)

let dijkstra g n =
  let reached_p = Array.make n false in
  let d = Array.make n max_int in
  d.(0) <- 0;
  let h = H.make 30000 (0, 0) in
  H.push (0, 0) h;
  while not (H.empty_p h) do
    let (u, x) = H.pop h in
    reached_p.(u) <- true;
    if x > d.(u) then ()
    else
      List.iter (fun (v, c) ->
        let x = d.(u) + c in
        if not reached_p.(v) && x < d.(v) then begin
          d.(v) <- x;
          H.push (v, x) h;
        end) g.(u)
  done;
  d

let rec make_pair acc = function
  | [] -> acc
  | v :: c :: tl -> make_pair ((v, c) :: acc) tl
  | _ -> assert false

let make_pair lst = make_pair [] lst

let split_on_char sep s =
  let open String in
  let r = ref [] in
  let j = ref (length s) in
  for i = length s - 1 downto 0 do
    if get s i = sep then begin
      r := sub s (i + 1) (!j - i - 1) :: !r;
      j := i
    end
  done;
  sub s 0 !j :: !r

let () =
  let n = read_int () in
  let g = Array.make n [] in
  for _ = 0 to n - 1 do
    match read_line () |> split_on_char ' ' |> List.map int_of_string with
    | u :: _ :: l -> g.(u) <- make_pair l
    | _ -> assert false
  done;
  dijkstra g n |> Array.iteri (fun i e -> Printf.printf "%d %d\n" i e)


module ArrayL = ArrayLabels
module ListL = ListLabels

let dbg = Printf.printf "[debug]%s"

let max_num = 100_000_000_000

let id = fun x -> x
let tuple2 x y = (x,y)
let tuple3 x y z = (x,y,z)
let succ x = x + 1
let pred x = x - 1

let (++) n m =
  let rec aux i =
    if i = m then [m]
    else i :: aux (i+1) in
  if n > m then [] else aux n

let (++^) n m = n ++ (m-1)

let scan fmt f = Scanf.sscanf (read_line ()) fmt f

let scan_list ~sep cnv =
  let line = read_line () in
  Str.split (Str.regexp_string sep) line
  |> List.map cnv

let scan_lines n fmt f =
  List.map (fun _ -> scan fmt f) (0++^n)

let scan_matrix n m e conv =
  let arr = Array.make_matrix n m e in
  Array.iteri (fun i line ->
      let s = Scanf.Scanning.from_string @@ read_line () in
      Array.iteri (fun j _ ->
          arr.(i).(j) <- Scanf.bscanf s " %s" conv;
        ) line) arr; arr

let rec powerset = function
  | [] -> [[]]
  | hd::tl ->
    let pws =  powerset tl in
    pws @ ListL.map pws ~f:(fun pw -> hd::pw)

let permutations l =
  let rec interleave x = function
    | [] -> [[x]]
    | (hd::tl) as l ->
      (x::l) :: (interleave x tl |> ListL.map ~f:(fun l -> hd::l)) in
  let rec aux = function
    | [] -> [[]]
    | a::rest ->
      aux rest |> ListL.map ~f:(interleave a) |> List.concat in
  aux l

let between n x m = n <= x && x < m

let string_to_list s =
  List.map (String.get s) (0 ++^ String.length s)

let n = scan "%d" id
let ls = scan_lines n "%d %d" tuple2

exception Found of int array array
let print_mat mat =
  ArrayL.iter mat ~f:(fun a ->
      ArrayL.iter a ~f:(fun v ->
          if v = 0 then Printf.printf "."
          else Printf.printf "Q"
        );
      Printf.printf "\n"
    )

let () =
  let sets = permutations (0++^8) in
  (try ListL.iter sets ~f:(fun set ->
       let mat = Array.make_matrix 8 8 0 in
       ListL.iteri set ~f:(fun i n -> mat.(i).(n) <- 1;);
       if not @@ ListL.for_all ls ~f:(fun (i, j) -> mat.(i).(j) = 1) then ()
       else
       if ListL.map (0++^8) ~f:(fun i ->
           ListL.map (0++^8) ~f:(fun j ->
               if mat.(i).(j) = 1 then
                 ListL.for_all (0++^8) ~f:(fun k -> k = i || mat.(k).(j) = 0)
                 && ListL.for_all (1++^8) ~f:(fun k -> i-k < 0 || j-k < 0 || mat.(i-k).(j-k) = 0)
                 && ListL.for_all (1++^8) ~f:(fun k -> i+k >= 8 || j+k >= 8 || mat.(i+k).(j+k) = 0)
                 && ListL.for_all (1++^8) ~f:(fun k -> i-k < 0 || j+k >= 8 || mat.(i-k).(j+k) = 0)
                 && ListL.for_all (1++^8) ~f:(fun k -> i+k >= 8 || j-k < 0 || mat.(i+k).(j-k) = 0)
               else true))
          |> List.concat |> List.for_all ((=) true) then raise @@ Found mat else ());
      Array.make_matrix 8 8 0
   with
   | Found x -> x)
  |> print_mat

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

8 Queens Problem

The goal of 8 Queens Problem is to put eight queens on a chess-board such that none of them threatens any of others. A queen threatens the squares in the same row, in the same column, or on the same diagonals as shown in the following figure.

For a given chess board where $k$ queens are already placed, find the solution of the 8 queens problem.

Input

In the first line, an integer $k$ is given. In the following $k$ lines, each square where a queen is already placed is given by two integers $r$ and $c$. $r$ and $c$ respectively denotes the row number and the column number. The row/column numbers start with 0.

Output

Print a $8 \times 8$ chess board by strings where a square with a queen is represented by 'Q' and an empty square is represented by '.'.

Constraints

There is exactly one solution

Sample Input 1

2
2 2
5 3

Sample Output 1

......Q.
Q.......
..Q.....
.......Q
.....Q..
...Q....
.Q......
....Q...


let pn = 1000000007

let pow x n =
  let rec doit i acc =
    if i = n then acc
    else doit (i + 1) (acc*x)
  in doit 0 1

let str_fold_left f init s =
  let n = String.length s in
  let rec doit i acc =
    if i = n then acc
    else doit (i + 1) (f acc s.[i])
  in doit 0 init

let () =
  let p = read_line () in
  let t = read_line () in
  let n = String.length p in
  let m = String.length t in
  let h = Array.make (n + 1) 0 in
  String.iteri (fun i c -> h.(i+1) <- h.(i)*pn + Char.code c) p;
  let ht = str_fold_left (fun acc c -> acc*pn + Char.code c) 0 t in
  let x = pow pn m in
  let rec doit i =
    if i <= n then begin
      if h.(i) - h.(i-m)*x = ht then Printf.printf "%d\n" (i - m);
      doit (i + 1)
    end in
  doit m

String Search

Find places where a string P is found within a text T.
Print all indices of T where P found. The indices of T start with 0.

Input

In the first line, a text T is given. In the second line, a string P is given.

Output

Print an index of T where P found in a line. Print the indices in ascending order.

Constraints

1 ≤ length of T ≤ 1000000

1 ≤ length of P ≤ 10000

The input consists of alphabetical characters and digits

Sample Input 1

aabaaa
aa

Sample Output 1

0
3
4

Sample Input 2

xyzz
yz

Sample Output 2

1

Sample Input 3

abc
xyz

Sample Output 3

The output should be empty.


let pn = 1000000007

let pow x n =
  let rec doit x n acc =
    if n = 0 then acc
    else if n mod 2 = 0 then doit (x * x) (n / 2) acc
    else doit (x * x) (n / 2) (acc * x) in
  doit x n 1

let fold_left f init s n =
  let rec doit i acc =
    if i = n then acc
    else doit (i + 1) (f acc s.[i]) in
  doit 0 init

let () =
  let p = read_line () in
  let t = read_line () in
  let n = String.length p in
  let m = String.length t in
  let h = Array.make (n + 1) 0 in
  String.iteri (fun i c -> h.(i+1) <- h.(i)*pn + Char.code c) p;
  let ht = fold_left (fun acc c -> acc*pn + Char.code c) 0 t m in
  let x = pow pn m in
  for i = m to n do
    if h.(i) - h.(i-m)*x = ht then Printf.printf "%d\n" (i - m);
  done


let (p1, p2, p3) = (257, 251, 1000000007)

let pow x n =
  let rec doit i acc =
    if i = n then acc
    else doit (i + 1) (acc*x mod p3) in
  doit 0 1

let solve a (h, w) b (r, c) =
  let make_hash v (y, x) =
    let h1 = Array.make_matrix y x 0 in
    let c1 = pow p1 c in
    let rec duduwa i =
      if i < y then begin
        let rec calc_z j acc =
          if j = c then acc
          else calc_z (j + 1) ((acc*p1 + Char.code v.(i).(j)) mod p3) in
        let rec aux j z =
          if j = x - c then h1.(i).(j) <- z
          else begin
            h1.(i).(j) <- z;
            let new_z = (z*p1 - (Char.code v.(i).(j))*c1 + Char.code v.(i).(j+c)) mod p3 in
            aux (j + 1) (if new_z < 0 then new_z + p3 else new_z)
          end in
        aux 0 (calc_z 0 0);
        duduwa (i + 1)
      end in
    duduwa 0;
    let h2 = Array.make_matrix y x 0 in
    let c2 = pow p2 r in
    let rec doit j =
      if j < x then begin
        let rec calc_z i acc =
          if i = r then acc
          else calc_z (i + 1) ((acc*p2 + h1.(i).(j)) mod p3) in
        let rec aux i z =
          if i = y - r then h2.(i).(j) <- z
          else begin
            h2.(i).(j) <- z;
            let new_z = (z*p2 - h1.(i).(j)*c2 + h1.(i+r).(j)) mod p3 in
            aux (i + 1) (if new_z < 0 then new_z + p3 else new_z)
          end in
        aux 0 (calc_z 0 0);
        doit (j + 1)
      end in
    doit 0;
    h2 in
  let s = make_hash a (h, w) in
  let t = make_hash b (r, c) in
  let rec doit = function
    | (i, _) when i > h - r -> ()
    | (i, j) when j > w - c -> doit (i + 1, 0)
    | (i, j) ->
      if s.(i).(j) = t.(0).(0) then Printf.printf "%d %d\n" i j;
      doit (i, j + 1) in
  doit (0, 0)

let input_array y x =
  let a = Array.make_matrix y x '\000' in
  let rec doit = function
    | (i, _) when i = y -> a
    | (i, j) when j = x -> doit (i + 1, 0)
    | (i, j) ->
      a.(i).(j) <- Scanf.scanf "%c " (fun c -> c);
      doit (i, j + 1) in
  doit (0, 0)

let () =
  let (h, w) = Scanf.scanf "%d %d\n" (fun h w -> (h, w)) in
  let a = input_array h w in
  let (r, c) = Scanf.scanf "%d %d\n" (fun r c -> (r, c)) in
  let b = input_array r c in
  solve a (h, w) b (r, c)

Pattern Search

Find places where a R × C pattern is found within a H × W region. Print top-left coordinates (i, j) of sub-regions where the pattern found. The top-left and bottom-right coordinates of the region is (0, 0) and (H-1, W-1) respectively.

Input

In the first line, two integers H and W are given. In the following H lines, i-th lines of the region are given.

In the next line, two integers R and C are given. In the following R lines, i-th lines of the pattern are given.

output

For each sub-region found, print a coordinate i and j separated by a space character in a line. Print the coordinates in ascending order of the row numbers (i), or the column numbers (j) in case of a tie.

Constraints

1 ≤ H, W ≤ 1000

1 ≤ R, C ≤ 1000

The input consists of alphabetical characters and digits

Sample Input 1

4 5
00010
00101
00010
00100
3 2
10
01
10

Sample Output 1

0 3
1 2


let (p1, p2, p3) = (257, 251, 1000000007)

let split_on_char sep s =
  let open String in
  let r = ref [] in
  let j = ref (length s) in
  for i = length s - 1 downto 0 do
    if get s i = sep then begin
      r := sub s (i + 1) (!j - i - 1) :: !r;
      j := i
    end
  done;
  sub s 0 !j :: !r

let pow x n =
  let rec doit x n acc =
    if n = 0 then acc
    else if n mod 2 = 0 then doit (x * x mod p3) (n / 2) acc
    else doit (x * x mod p3) (n / 2) (acc * x mod p3) in
  doit x n 1

let make_hash v (x, y) (r, c) =
  let h1 = Array.make_matrix x y 0 in
  let c1 = pow p1 c in
  for i = 0 to x - 1 do
    let rec aux j acc =
      if j = c then acc
      else aux (j + 1) ((acc*p1 + Char.code v.(i).(j)) mod p3) in
    let rec doit j z =
      if j = y - c then h1.(i).(j) <- z
      else begin
        h1.(i).(j) <- z;
        let z = (z*p1 - (Char.code v.(i).(j))*c1 + Char.code v.(i).(j+c)) mod p3 in
        doit (j + 1) (if z < 0 then z + p3 else z)
      end in
    aux 0 0 |> doit 0;
  done;
  let h2 = Array.make_matrix x y 0 in
  let c2 = pow p2 r in
  for j = 0 to y - 1 do
    let rec aux i acc =
      if i = r then acc
      else aux (i + 1) ((acc*p2 + h1.(i).(j)) mod p3) in
    let rec doit i z =
      if i = x - r then h2.(i).(j) <- z
      else begin
        h2.(i).(j) <- z;
        let z = (z*p2 - h1.(i).(j)*c2 + h1.(i+r).(j)) mod p3 in
        doit (i + 1) (if z < 0 then z + p3 else z)
      end in
    aux 0 0 |> doit 0;
  done;
  h2

let solve (h, w) (r, c) a b =
  let s = make_hash a (h, w) (r, c) in
  let t = make_hash b (r, c) (r, c) in
  for i = 0 to h - r do
    for j = 0 to w -c do
      if s.(i).(j) = t.(0).(0) then Printf.printf "%d %d\n" i j;
    done
  done

let read_array x y =
  let a = Array.make_matrix x y '\000' in
  for i = 0 to x - 1 do
    let l = read_line () in
    for j = 0 to y - 1 do
      a.(i).(j) <- l.[j];
    done
  done;
  a

let () =
  match read_line () |> split_on_char ' ' |> List.map int_of_string with
  | [h; w] ->
    begin
      let a = read_array h w in
      match read_line () |> split_on_char ' ' |> List.map int_of_string with
      | [r; c] ->
        if h < r || w < c then ()
        else read_array r c |> solve (h, w) (r, c) a
      | _ -> assert false
    end
  | _ -> assert false


exception Not_equal of int

let cmp_sa rank a b n k =
  if rank.(a) <> rank.(b) then compare rank.(a) rank.(b)
  else
    compare
      (if a + k <= n then rank.(a+k) else (-1))
      (if b + k <= n then rank.(b+k) else (-1))

let construct_sa t n =
  let sa = Array.make (n + 1) 0 in
  let rank = Array.make (n + 1) 0 in
  let tmp = Array.make (n + 1) 0 in
  for i = 0 to n - 1 do
    sa.(i) <- i;
    rank.(i) <- Char.code t.[i];
  done;
  sa.(n) <- n;
  rank.(n) <- (-1);
  let rec doit k =
    if k > n then ()
    else begin
      Array.fast_sort (fun a b -> cmp_sa rank a b n k) sa;
      tmp.(sa.(0)) <- 0;
      for i = 1 to n do
        tmp.(sa.(i)) <-
          tmp.(sa.(i-1)) + (if cmp_sa rank sa.(i-1) sa.(i) n k = (-1) then 1 else 0);
      done;
      for i = 0 to n do rank.(i) <- tmp.(i) done;
      doit (2 * k)
    end in
  doit 1;
  sa

let range_cmp t n offset p k =
  let m = n - offset in
  let m = if m < k then m else k in
  try
    for i = 0 to m - 1 do
      if t.[i+offset] <> p.[i] then
        raise (Not_equal (compare t.[i+offset] p.[i]));
    done;
    if m = k then 0
    else (-1)
  with Not_equal i -> i

let () =
  let t = read_line () in
  let n = String.length t in
  let sa = construct_sa t n in
  let q = read_int () in
  for _ = 0 to q - 1 do
    let p = read_line () in
    let k = String.length p in
    let rec doit l r =
      if r - l <= 1 then l
      else
        let m = (l + r) / 2 in
        if range_cmp t n sa.(m) p k <= 0 then doit m r
        else doit l m in
    let l = doit 0 (n + 1) in
    Printf.printf "%d\n" (if range_cmp t n sa.(l) p k = 0 then 1 else 0);
  done

String Search

Determine whether a text T includes a pattern P. Your program should answer for given queries consisting of P_i.

Input

In the first line, a text T is given. In the second line, an integer Q denoting the number of queries is given. In the following Q lines, the patterns P_i are given respectively.

Output

For each question, print 1 if the text includes P_i, or print 0 otherwise.

Constraints

1 ≤ length of T ≤ 1000000

1 ≤ length of P_i ≤ 1000

1 ≤ Q ≤ 10000

The input consists of alphabetical characters and digits

Sample Input 1

aabaaa
4
aa
ba
bb
xyz

Sample Output 1

1
1
0
0


let id x = x

let string_search s p =
  let sl = String.length s in
  let pl = String.length p in
  let sa = Array.init (sl+1) id in
  let rank = Array.init (sl+1) (fun i -> if i = sl then (-1) else Char.code s.[i]) in
  let cmp k i j =
    if rank.(i) = rank.(j) then
      let rik = if i + k <= sl then rank.(i+k) else (-1) in
      let rjk = if j + k <= sl then rank.(j+k) else (-1) in
      rik - rjk
    else rank.(i) - rank.(j) in
  let ra_rank k =
    let ta = Array.make (sl+1) 0 in
    let rec iter i =
      if i > sl then ()
      else begin
          ta.(sa.(i)) <- ta.(sa.(i-1)) + (if cmp k sa.(i) sa.(i-1) > 0 then 1 else 0);
          iter (i+1)
        end in
    let rec copy i =
      if i > sl then ()
      else begin
          rank.(i) <- ta.(i);
          copy (i+1)
        end in
    iter 1;
    copy 0 in
  let rec sort_sa k =
    if k > sl then ()
    else begin
        Array.sort (cmp k) sa;
        ra_rank k;
        sort_sa (2 * k)
      end in
  let rec search l r =
    if r - l <= 1 then
      try String.sub s sa.(r) pl = p with _ -> false
    else
      let m = (l + r) / 2 in
      match compare (String.sub s sa.(m) (min pl (sl - sa.(m)))) p with
        0 -> true
      | x when x < 0 -> search m r
      | _ -> search l m
  in
  sort_sa 1;
  search 0 (sl+1)

let () =
  let t = read_line () in
  let q = read_int () in
  let rec loop x =
    if x = 0 then ()
    else let p = read_line () in
         (if string_search t p then "1" else "0") |> print_endline;
         loop (x-1)
  in loop q


let prime_p = function
  | 2 -> true
  | n when n < 2 || n mod 2 = 0 -> false
  | n ->
      let rec doit i =
        if i*i > n then true
        else if n mod i = 0 then false
        else doit (i + 2)
      in
      doit 3

let () =
  let n = read_int () in
  let rec read i cnt =
    if i >= n then cnt
    else read (i + 1) (cnt + (if prime_p (read_int ()) then 1 else 0))
  in
  Printf.printf "%d\n" (read 0 0)

Prime Numbers

A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.

Write a program which reads a list of N integers and prints the number of prime numbers in the list.

Input

The first line contains an integer N, the number of elements in the list.

N numbers are given in the following lines.

Output

Print the number of prime numbers in the given list.

Constraints

1 ≤ N ≤ 10000

2 ≤ an element of the list ≤ 108

Sample Input 1

5
2
3
4
5
6

Sample Output 1

3

Sample Input 2

11
7
8
9
10
11
12
13
14
15
16
17

Sample Output 2

4


type intseq = Cons of int * (int -> intseq) ;; (* 整数の無限列 *)

let rec is_divisible lst x = (* リストのいずれかの要素でxが割り切れるかどうかチェックする. *)
  let max = float_of_int x |> sqrt |> int_of_float in (* チェックする最大値 *)
  match lst with
    [] -> false
  | p::ps when p > max -> false
  | p::ps -> if x mod p = 0 then true
             else is_divisible ps x ;;

let rec prime_seq primes x =    (* 素数の無限列. primesはアキュムレータであり, 素数のリスト *)
  if is_divisible primes (x+1) then prime_seq primes (x+1)
  else Cons(x+1, prime_seq (primes @ [x+1])) ;;

let is_prime x =                (* xが素数かどうかチェックする *)
  let max = float_of_int x |> sqrt |> int_of_float in
  let rec is_p p_seq =            (* xが素数の数列で割り切れるかチェックする *)
    let Cons(n, f) = p_seq in
    if n > max then true
    else if x mod n = 0 then false
    else is_p (f n)
  in
  is_p (prime_seq [] 1) ;;

let () =
  let open Scanf in
  let m = scanf "%d\n" (fun x -> x) in
  let as_ = Array.init m (fun _ -> scanf "%d\n" (fun x -> if is_prime x then 1 else 0)) in
  Array.fold_left (+) 0 as_
  |> Printf.printf "%d\n" ;;


let () =
  let n = read_int () in
  let minv = ref (read_int ()) in
  let maxv = ref min_int in
  for i = 1 to n - 1 do
    let j = read_int () in
    maxv := max !maxv (j - !minv);
    minv := min !minv j
  done;
  print_int !maxv; print_newline ()

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Maximum Profit

You can obtain profits from foreign exchange margin transactions. For example, if you buy 1000 dollar at a rate of 100 yen per dollar, and sell them at a rate of 108 yen per dollar, you can obtain (108 - 100) × 1000 = 8000 yen.

Write a program which reads values of a currency $R_t$ at a certain time $t$ ($t = 0, 1, 2, ... n-1$), and reports the maximum value of $R_j - R_i$ where $j > i$ .

Input

The first line contains an integer $n$. In the following $n$ lines, $R_t$ ($t = 0, 1, 2, ... n-1$) are given in order.

Output

Print the maximum value in a line.

Constraints

$2 \leq n \leq 200,000$

$1 \leq R_t \leq 10^9$

Sample Input 1

6
5
3
1
3
4
3

Sample Output 1

3

Sample Input 2

3
4
3
2

Sample Output 2

-1


let () =
  let n = read_int () in
  let r1 = read_int () in
  let r2 = read_int () in
  let rec iter mp mr m =
    if m = 0 then mp
    else let r = read_int () in
         iter (max mp (r - mr)) (min mr r) (m-1) in
  iter (r2 - r1) (min r1 r2) (n-2) |> string_of_int |> print_endline


let () =
  let nq = read_line () |> Str.split (Str.regexp " ")
         |> List.map int_of_string |> Array.of_list in
  let (n,q) = (nq.(0), nq.(1)) and
      queue = Queue.create () in
  let rec read = function
      0 -> ()
    | i ->
       let line = read_line () |> Str.split (Str.regexp " ")
                  |> Array.of_list in
       Queue.push (line.(0),int_of_string line.(1)) queue;
       read (i-1)
  in
  read n;
  let rec f time_total =
    if Queue.is_empty queue then ()
    else
      let (name, time) = Queue.pop queue in
      if time <= q then
        begin
          Printf.printf "%s %d\n" name (time+time_total);
          f (time+time_total)
        end
      else
        begin
          Queue.push (name, (time-q)) queue;
          f (q+time_total)
        end
  in
  f 0;;

There are n processes in a queue. Each process has namei and timei. The round-robin scheduling handles the processes in order. A round-robin scheduler gives each process a quantum (a time slot) and interrupts the process if it is not completed by then. The process is resumed and moved to the end of the queue, then the scheduler handles the next process in the queue.

For example, we have the following queue with the quantum of 100ms.

A(150) - B(80) - C(200) - D(200)

First, process A is handled for 100ms, then the process is moved to the end of the queue with the remaining time (50ms).

B(80) - C(200) - D(200) - A(50)

Next, process B is handled for 80ms. The process is completed with the time stamp of 180ms and removed from the queue.

C(200) - D(200) - A(50)

Your task is to write a program which simulates the round-robin scheduling.

Input

n q

name1 time1

name2 time2

...

namen timen

In the first line the number of processes n and the quantum q are given separated by a single space.

In the following n lines, names and times for the n processes are given. namei and timei are separated by a single space.

Output

For each process, prints its name and the time the process finished in order.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 1000

1 ≤ timei ≤ 50000

1 ≤ length of namei ≤ 10

1 ≤ Sum of timei ≤ 1000000

Sample Input 1

5 100
p1 150
p2 80
p3 200
p4 350
p5 20

Sample Output 1

p2 180
p5 400
p1 450
p3 550
p4 800

Notes

Template in C


module DoublyLinkedList = struct
  type t = {
    mutable data : int;
    mutable next : t;
    mutable prev : t;
  }

  let make () =
    let rec head = { data = 0; next = head; prev = head } in
    head

  let insert data head =
    let x = { data = data; next = head.next; prev = head } in
    head.next.prev <- x;
    head.next <- x

  let delete x =
    x.next.prev <- x.prev;
    x.prev.next <- x.next

  let delete_first head = delete head.next

  let delete_last head = delete head.prev

  let delete_node data head =
    let rec doit ite =
      if ite == head then None
      else if ite.data = data then Some ite
      else doit ite.next
    in
    match doit head.next with
    | None -> ()
    | Some ite -> delete ite

  let iteri head ~f =
    let rec doit i ite =
      if ite != head then (f i ite.data; doit (i + 1) ite.next)
    in
    doit 0 head.next
end

module L = DoublyLinkedList

let split str delim =
  let rec doit s acc =
    match
      try Some (String.rindex s delim) with _ -> None
    with
    | None -> s :: acc
    | Some i ->
        let s1 = String.sub s 0 i in
        let s2 = String.sub s (i + 1) (String.length s - String.length s1 - 1) in
        doit s1 (s2 :: acc)
  in
  doit str []

let () =
  let n = read_int () in
  let head = L.make () in
  let rec read i =
    if i < n then begin
      match split (read_line ()) ' ' with
      | ["insert"; n] -> (L.insert (int_of_string n) head; read (i + 1))
      | ["delete"; n] -> (L.delete_node (int_of_string n) head; read (i + 1))
      | ["deleteFirst"] -> (L.delete_first head; read (i + 1))
      | ["deleteLast"] -> (L.delete_last head; read (i + 1))
      | _ -> exit 1
    end
  in
  read 0;
  L.iteri head ~f:(fun i n -> if i <> 0 then print_string " "; print_int n);
  print_newline ()

Doubly Linked List

Your task is to implement a double linked list.

Write a program which performs the following operations:

insert x: insert an element with key x into the front of the list.

delete x: delete the first element which has the key of x from the list. If there is not such element, you need not do anything.

deleteFirst: delete the first element from the list.

deleteLast: delete the last element from the list.

Input

The input is given in the following format:

n

command1

command2

...

commandn

In the first line, the number of operations n is given. In the following n lines, the above mentioned operations are given in the following format:

insert x

delete x

deleteFirst

deleteLast

Output

Print all the element (key) in the list after the given operations. Two consequtive keys should be separated by a single space.

Constraints

The number of operations ≤ 2,000,000

The number of delete operations ≤ 20

0 ≤ value of a key ≤ 109

The number of elements in the list does not exceed 106

For a delete, deleteFirst or deleteLast operation, there is at least one element in the list.

Sample Input 1

7
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5

Sample Output 1

6 1 2

Sample Input 2

9
insert 5
insert 2
insert 3
insert 1
delete 3
insert 6
delete 5
deleteFirst
deleteLast

Sample Output 2

1


open Str

type dllist = {value : int option; mutable prev : dllist ref; mutable next : dllist ref}

let read_list () =
  split (regexp " +") (read_line ())

let () =
  let n = read_int () in
  let rec tn = {value = None; prev = ref tn; next = ref tn} in
  let insert x =
    let nn = {value = Some x; prev = ref tn; next = ref tn} in
    let nnn = !(tn.next) in
    nn.next <- tn.next;
    nn.prev <- nnn.prev;
    tn.next <- ref nn;
    nnn.prev <- ref nn
  in
  let find x =
    let rec loop n =
      let nn = !(n.next) in
      match nn.value with
        None -> raise Not_found
      | Some y -> if x = y then nn else loop nn in
    loop tn
  in
  let delete x = try
      let n = find x in
      let pn = !(n.prev) in
      let nn = !(n.next) in
      pn.next <- n.next;
      nn.prev <- n.prev
    with
      _ -> ()
  in
  let delete_first () =
    let dn = !(tn.next) in
    let nn = !(dn.next) in
    tn.next <- dn.next;
    nn.prev <- dn.prev
  in
  let delete_last () =
    let dn = !(tn.prev) in
    let pn = !(dn.prev) in
    tn.prev <- dn.prev;
    pn.next <- dn.next
  in
  let print_dll () =
    let rec loop n ls =
      let nn = !(n.next) in
      match nn.value with
        None -> List.rev ls
      | Some x -> loop nn (x :: ls) in
    loop tn [] |> List.map string_of_int |> String.concat " " |> print_endline
  in
  let rec iter x =
    if x = 0 then print_dll ()
    else
      let s = read_list () in
      match s with
        "deleteFirst" :: _  -> delete_first (); iter (x-1)
      | "deleteLast" :: _ -> delete_last (); iter (x-1)
      | "insert" :: n :: _ -> insert (int_of_string n); iter (x-1)
      | "delete" :: n :: _ -> delete (int_of_string n); iter (x-1)
      | _ -> failwith "ddl"
  in iter n


let analysis (area:string) =
  let len = String.length area in
  let stack = Stack.create () in
  let rec loop acc = function
      i when i = len -> acc
    | i ->
      match area.[i] with
      | '\\' -> Stack.push i stack; loop acc (i+1)
      | '/' -> loop
                 (match Stack.length stack with
                    0 -> acc
                  | _ -> let j = Stack.pop stack in
                    (((j,i),i-j)::acc))
                 (i+1)
      | _ -> loop acc (i+1)
  in loop [] 0

let summarize lst =
  let rec loop acc = function
      []  -> acc
    | [x] -> x::acc
    | ((s1,e1),v1)::((s2,e2),v2)::r when s1 < s2 && e1 > e2 ->
      loop acc (((s1,e1), v1+v2)::r)
    | a::(b::r as rest) -> loop (a::acc) rest
  in loop [] lst

let () =
  let line = read_line () in
  let count = ref 0 in
  let buf = Buffer.create 128 in
  analysis line |> summarize
  |> List.fold_left
    (fun acc (_,v) ->
       incr count;
       Buffer.add_string buf (Printf.sprintf " %d" v);
       acc+v)
    0
  |> (fun sum -> Printf.printf "%d\n%d%s\n" sum !count (Buffer.contents buf))

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Areas on the Cross-Section Diagram

Your task is to simulate a flood damage.

For a given cross-section diagram, reports areas of flooded sections.

Assume that rain is falling endlessly in the region and the water overflowing from the region is falling in the sea at the both sides.
For example, for the above cross-section diagram, the rain will create floods which have areas of 4, 2, 1, 19 and 9 respectively.

Input

A string, which represents slopes and flatlands by '/', '\' and '_' respectively, is given in a line. For example, the region of the above example is given by a string "\\///\_/\/\\\\/_/\\///__\\\_\\/_\/_/\".

output

Report the areas of floods in the following format:

$A$

$k$ $L_1$ $L_2$ ... $L_k$

In the first line, print the total area $A$ of created floods.

In the second line, print the number of floods $k$ and areas $L_i (i = 1, 2, ..., k)$ for each flood from the left side of the cross-section diagram. Print a space character before $L_i$.

Constraints

$1 \leq$ length of the string $\leq 20,000$

Sample Input 1

\\//

Sample Output 1

4
1 4

Sample Input 2

\\///\_/\/\\\\/_/\\///__\\\_\\/_\/_/\

Sample Output 2

35
5 4 2 1 19 9


let bin_search x ary =
  let rec doit l r =
    if l >= r then false
    else begin
      let m = (l + r) / 2 in
      if x = ary.(m) then true
      else if x < ary.(m) then doit l m
      else doit (m + 1) r
    end
  in
  doit 0 (Array.length ary)

let () =
  let _ = read_int () in
  let s = Array.of_list (List.map int_of_string (Str.split (Str.regexp_string " ") (read_line ()))) in
  let _ = read_int () in
  let t = List.map int_of_string (Str.split (Str.regexp_string " ") (read_line ())) in
  let c = List.fold_left (fun cnt e -> if bin_search e s then (cnt + 1) else cnt) 0 t in
  Printf.printf "%d\n" c

Search II

You are given a sequence of n integers S and a sequence of different q integers T. Write a program which outputs C, the number of integers in T which are also in the set S.

Input

In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers are given.

Output

Print C in a line.

Constraints

Elements in S is sorted in ascending order

n ≤ 100000

q ≤ 50000

0 ≤ an element in S ≤ 109

0 ≤ an element in T ≤ 109

Sample Input 1

5
1 2 3 4 5
3
3 4 1

Sample Output 1

3

Sample Input 2

3
1 2 3
1
5

Sample Output 2

0

Sample Input 3

5
1 1 2 2 3
2
1 2

Sample Output 3

2

Notes


let words str = Str.split (Str.regexp " ") str |> List.map int_of_string

let bs elem (a: int array) =
  let rec loop (i_min,i_max) =
    match i_min > i_max with
      true -> false
    | false ->
      let mid = (i_min+i_max)/2 in
      match a.(mid) = elem with
        true -> true
      | false ->
        loop (match a.(mid) < elem with true -> mid+1,i_max | false -> i_min,mid-1)
  in loop (0,(Array.length a) -1)

let () =
  let _ = read_int () in
  let s = read_line () |> words |> Array.of_list in
  let _ = read_int () in
  let t = read_line () |> words in
  List.fold_left (fun acc x -> match bs x s with true -> acc+1 | false -> acc)
    0 t
  |> Printf.printf "%d\n"


module ArrayL = ArrayLabels
module ListL = ListLabels

let dbg = Printf.printf "[debug]%s"

let max_num = 100_000_000_000

let id = fun x -> x
let tuple2 x y = (x,y)
let tuple3 x y z = (x,y,z)
let succ x = x + 1
let pred x = x - 1

let (++) n m =
  let rec aux i =
    if i = m then [m]
    else i :: aux (i+1) in
  if n > m then [] else aux n

let (++^) n m = n ++ (m-1)

let scan fmt f = Scanf.sscanf (read_line ()) fmt f

let scan_list ~sep cnv =
  let line = read_line () in
  Str.split (Str.regexp_string sep) line
  |> List.map cnv

let scan_lines n fmt f =
  List.map (fun _ -> scan fmt f) (0++^n)

let scan_matrix n m e conv =
  let arr = Array.make_matrix n m e in
  Array.iteri (fun i line ->
      let s = Scanf.Scanning.from_string @@ read_line () in
      Array.iteri (fun j _ ->
          arr.(i).(j) <- Scanf.bscanf s " %s" conv;
        ) line) arr; arr

let rec powerset = function
  | [] -> [[]]
  | hd::tl ->
    let pws =  powerset tl in
    pws @ ListL.map pws ~f:(fun pw -> hd::pw)

let permutations l =
  let rec interleave x = function
    | [] -> [[x]]
    | (hd::tl) as l ->
      (x::l) :: (interleave x tl |> ListL.map ~f:(fun l -> hd::l)) in
  let rec aux = function
    | [] -> [[]]
    | a::rest ->
      aux rest |> ListL.map ~f:(interleave a) |> List.concat in
  aux l

let between n x m = n <= x && x < m

let lower_bound n f =
  let rec aux l u =
    if u - l > 1 then
      let m = (l + u) / 2 in
      if f m then aux l m
      else aux m u
    else u in aux (-1) n

let string_to_list s =
  List.map (String.get s) (0 ++^ String.length s)

let n = scan "%d" id
let s = Array.of_list @@ scan_list ~sep:" " int_of_string
let q = scan "%d" id
let t = scan_list ~sep:" " int_of_string

let () =
  ListL.map t ~f:(fun v ->
      let i = lower_bound (Array.length s) (fun i -> v <= s.(i)) in
      if i < Array.length s && s.(i) = v then  1 else 0
    ) |> ListL.fold_left ~init:0 ~f:(+) |> Printf.printf "%d\n"


let () =
  let (n, k) = Scanf.scanf "%d %d\n" (fun n k -> (n, k)) in
  let a = Array.make n 0 in
  let rec read i =
    if i >= n then ()
    else (Scanf.scanf "%d\n" (fun w -> a.(i) <- w); read (i + 1))
  in
  read 0;
  let check p =
    let rec doit i j s =
      if i = n then n
      else if j >= k then i
      else
        let x = s + a.(i) in
        if x > p then doit i (j + 1) 0
        else doit (i + 1) j x
    in
    doit 0 0 0
  in
  let rec bin_search l r =
    if r < l then l
    else
      let m = (l + r) / 2 in
      let v = check m in
      if v >= n then bin_search l (m - 1)
      else bin_search (m + 1) r
  in
  Printf.printf "%d\n" (bin_search 0 (100000 * 10000))

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

You are given $n$ packages of $w_i$ kg from a belt conveyor in order ($i = 0, 1, ... n-1$). You should load all packages onto $k$ trucks which have the common maximum load $P$. Each truck can load consecutive packages (more than or equals to zero) from the belt conveyor unless the total weights of the packages in the sequence does not exceed the maximum load $P$.

Write a program which reads $n$, $k$ and $w_i$, and reports the minimum value of the maximum load $P$ to load all packages from the belt conveyor.

Input

In the first line, two integers $n$ and $k$ are given separated by a space character. In the following $n$ lines, $w_i$ are given respectively.

Output

Print the minimum value of $P$ in a line.

Constraints

$1 \leq n \leq 100,000$

$1 \leq k \leq 100,000$

$1 \leq w_i \leq 10,000$

Sample Input 1

5 3
8
1
7
3
9

Sample Output 1

10

If the first truck loads two packages of $\{8, 1\}$, the second truck loads two packages of $\{7, 3\}$ and the third truck loads a package of $\{9\}$, then the minimum value of the maximum load $P$ shall be 10.

Sample Input 2

4 2
1
2
2
6

Sample Output 2

6

If the first truck loads three packages of $\{1, 2, 2\}$ and the second truck loads a package of $\{6\}$, then the minimum value of the maximum load $P$ shall be 6.


let () =
  let (n, k) = Scanf.scanf "%d %d\n" (fun n k -> (n, k)) in
  let a = Array.init n (fun _ -> Scanf.scanf "%d\n" (fun i -> i)) in
  let check p =
    let rec doit i j s =
      if i = n then n
      else if j >= k then i
      else
        let x = s + a.(i) in
        if x > p then doit i (j + 1) 0
        else doit (i + 1) j x
    in
    doit 0 0 0
  in
  let rec bin_search l r =
    if r < l then l
    else
      let m = (l + r) / 2 in
      if check m >= n then bin_search l (m - 1)
      else bin_search (m + 1) r
  in
  Printf.printf "%d\n" (bin_search 0 (100000 * 10000))


module ArrayL = ArrayLabels
module ListL = ListLabels

let dbg = Printf.printf "[debug]%s"

let max_num = 100_000_000_000

let id = fun x -> x
let tuple2 x y = (x,y)
let tuple3 x y z = (x,y,z)
let succ x = x + 1
let pred x = x - 1

let (++) n m =
  let rec aux acc i =
    if i = m then m::acc
    else aux (i::acc) (i+1) in
  if n > m then [] else List.rev @@ aux [] n

let (++^) n m = n ++ (m-1)

let scan fmt f = Scanf.sscanf (read_line ()) fmt f

let scan_list ~sep cnv =
  let line = read_line () in
  Str.split (Str.regexp_string sep) line
  |> List.map cnv

let scan_lines n fmt f =
  List.map (fun _ -> scan fmt f) (0++^n)

let scan_matrix n m e conv =
  let arr = Array.make_matrix n m e in
  Array.iteri (fun i line ->
      let s = Scanf.Scanning.from_string @@ read_line () in
      Array.iteri (fun j _ ->
          arr.(i).(j) <- Scanf.bscanf s " %s" conv;
        ) line) arr; arr

let between n x m = n <= x && x < m

let string_to_list s =
  List.map (String.get s) (0 ++^ String.length s)

let rec powerset = function
  | [] -> [[]]
  | hd::tl ->
    let pws =  powerset tl in
    pws @ ListL.map pws ~f:(fun pw -> hd::pw)

(* let powerset l =
 *   let rec append acc l1 l2 =
 *     match l1, l2 with
 *     | [], [] -> acc
 *     | [], h :: t -> append (h :: acc) [] t
 *     | h :: t, l -> append (h :: acc) t l in
 *   let rec aux acc = function
 *     | [] -> acc
 *     | hd::tl ->
 *       aux (append [] acc @@ ListL.map acc ~f:(fun ac -> hd::ac)) tl in
 *   aux [[]] l *)

let permutations l =
  let rec interleave x = function
    | [] -> [[x]]
    | (hd::tl) as l ->
      (x::l) :: (interleave x tl |> ListL.map ~f:(fun l -> hd::l)) in
  let rec aux = function
    | [] -> [[]]
    | a::rest ->
      aux rest |> ListL.map ~f:(interleave a) |> List.concat in
  aux l

let n = scan "%d" id
let arr = Array.of_list @@ scan_list ~sep:" " int_of_string
let q = scan "%d" id
let ls = scan_list ~sep:" " int_of_string

exception Found

let () =
  let pwss = powerset (0 ++^ n) in
  let ht = Hashtbl.create @@ List.length pwss in
  ListL.iter pwss ~f:(fun pws ->
      ListL.map pws ~f:(fun i -> arr.(i))
      |> ListL.fold_left ~init:0 ~f:(+)
      |> (fun v-> Hashtbl.add ht v true));
  ListL.iter ls ~f:(fun v ->
      if Hashtbl.mem ht v then Printf.printf "yes\n"
      else  Printf.printf "no\n")

Exhaustive Search

Write a program which reads a sequence A of n elements and an integer M, and outputs "yes" if you can make M by adding elements in A, otherwise "no". You can use an element only once.

You are given the sequence A and q questions where each question contains Mi.

Input

In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers (Mi) are given.

Output

For each question Mi, print yes or no.

Constraints

n ≤ 20

q ≤ 200

1 ≤ elements in A ≤ 2000

1 ≤ Mi ≤ 2000

Sample Input 1

5
1 5 7 10 21
8
2 4 17 8 22 21 100 35

Sample Output 1

no
no
yes
yes
yes
yes
no
no

Notes

You can solve this problem by a Burte Force approach. Suppose solve(p, t) is a function which checkes whether you can make t by selecting elements after p-th element (inclusive). Then you can recursively call the following functions:

solve(0, M)

solve(1, M-{sum created from elements before 1st element})

solve(2, M-{sum created from elements before 2nd element})

...

The recursive function has two choices: you selected p-th element and not. So, you can check solve(p+1, t-A[p]) and solve(p+1, t) in solve(p, t) to check the all combinations.

For example, the following figure shows that 8 can be made by A[0] + A[2].


let to_array s =
  Str.split (Str.regexp_string " ") s
  |> List.map int_of_string
  |> Array.of_list;;

let print_array l =
  Array.map string_of_int l
  |> Array.to_list
  |> String.concat " "
  |> print_endline;;

let merge (a:int array) left mid right =
  let n1 = mid - left and
      n2 = right - mid in
  let l = Array.init (n1+1) (fun i -> if i < n1 then a.(left+i) else max_int) and
      r = Array.init (n2+1) (fun i -> if i < n2 then a.(mid+i) else max_int) and
      i = ref 0 and
      j = ref 0 and
      count = ref 0
  in
  for k = left to right-1 do
    if l.(!i) <= r.(!j) then
      begin
        a.(k) <- l.(!i); i := !i+1
      end
    else
      begin
        a.(k) <- r.(!j); j := !j+1
      end;
    count := !count+1
  done;
  !count

let rec merge_sort a left right count =
  if left + 1 < right then
    let mid = (left+right)/2 in
    let count1 = merge_sort a left mid count and
        count2 = merge_sort a mid right count in
    count1 + count2 + (merge a left mid right)
  else count
;;

let () =
  let _ = read_int () and
      a = read_line () |> to_array in
  let count = merge_sort a 0 (Array.length a) 0 in
  print_array a;
  print_int count;
  print_newline ()
;;

Merge Sort

Write a program of a Merge Sort algorithm implemented by the following pseudocode. You should also report the number of comparisons in the Merge function.

Merge(A, left, mid, right)
n1 = mid - left;
n2 = right - mid;
create array L[0...n1], R[0...n2]
for i = 0 to n1-1
do L[i] = A[left + i]
for i = 0 to n2-1
do R[i] = A[mid + i]
L[n1] = SENTINEL
R[n2] = SENTINEL
i = 0;
j = 0;
for k = left to right-1
if L[i] <= R[j]
then A[k] = L[i]
i = i + 1
else A[k] = R[j]
j = j + 1

Merge-Sort(A, left, right){
if left+1 < right
then mid = (left + right)/2;
call Merge-Sort(A, left, mid)
call Merge-Sort(A, mid, right)
call Merge(A, left, mid, right)

Input

In the first line n is given. In the second line, n integers are given.

Output

In the first line, print the sequence S. Two consequtive elements should be separated by a space character.

In the second line, print the number of comparisons.

Constraints

n ≤ 500000

0 ≤ an element in S ≤ 109

Sample Input 1

10
8 5 9 2 6 3 7 1 10 4

Sample Output 1

1 2 3 4 5 6 7 8 9 10
34

Notes


let cnt = ref 0

let merge a l m r =
  let init_ary n p =
    let ret = Array.make (n + 1) max_int in
    for i = 0 to n - 1 do
      ret.(i) <- a.(p + i)
    done;
    ret in
  let ai = init_ary (m - l) l in
  let aj = init_ary (r - m) m in
  let i = ref 0 in
  let j = ref 0 in
  for k = l to r - 1 do
    incr cnt;
    if ai.(!i) <= aj.(!j) then begin
      a.(k) <- ai.(!i);
      incr i;
    end else begin
      a.(k) <- aj.(!j);
      incr j;
    end
  done

let rec merge_sort a l r =
  if (l + 1) < r then begin
    let m = (l + r) / 2 in
    merge_sort a l m;
    merge_sort a m r;
    merge a l m r
  end

let () =
  let n = read_int () in
  let a = Array.init n (fun _ -> Scanf.scanf "%d " (fun i -> i)) in
  merge_sort a 0 n;
  print_int a.(0);
  for i = 1 to n - 1 do
    print_string " ";
    print_int a.(i);
  done;
  print_newline ();
  print_int !cnt;
  print_newline ()


let print_ary a =
  Array.iteri (fun i e -> Printf.printf (if i = 0 then "%d" else " %d") e) a;
  print_newline ()

let rev_iter f a =
  let rec doit i =
    if i < 0 then ()
    else (f (Array.get a i); doit (i - 1))
  in
  doit (Array.length a - 1)

let counting_sort a b k =
  let c = Array.make (k + 1) 0 in
  Array.iter (fun e -> c.(e) <- c.(e) + 1) a;
  Array.iteri (fun i _ -> if i = 0 then () else c.(i) <- c.(i) + c.(i - 1)) c;
  rev_iter (fun e -> b.(c.(e) - 1) <- e; c.(e) <- c.(e) - 1) a

let () =
  let n = read_int () in
  let a = Array.init n (fun _ -> Scanf.scanf "%d " (fun e -> e)) in
  let k = Array.fold_left max (-1) a in
  let b = Array.make n 0 in
  counting_sort a b k;
  print_ary b

Counting Sort

Counting sort can be used for sorting elements in an array which each of the n input elements is an integer in the range 0 to k. The idea of counting sort is to determine, for each input element x, the number of elements less than x as C[x]. This information can be used to place element x directly into its position in the output array B. This scheme must be modified to handle the situation in which several elements have the same value. Please see the following pseudocode for the detail:

Counting-Sort(A, B, k)
1 for i = 0 to k
2 do C[i] = 0
3 for j = 1 to length[A]
4 do C[A[j]] = C[A[j]]+1
5 /* C[i] now contains the number of elements equal to i */
6 for i = 1 to k
7 do C[i] = C[i] + C[i-1]
8 /* C[i] now contains the number of elements less than or equal to i */
9 for j = length[A] downto 1
10 do B[C[A[j]]] = A[j]
11 C[A[j]] = C[A[j]]-1

Write a program which sorts elements of given array ascending order based on the counting sort.

Input

The first line of the input includes an integer n, the number of elements in the sequence.

In the second line, n elements of the sequence are given separated by spaces characters.

Output

Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.

Constraints

1 ≤ n ≤ 2,000,000

0 ≤ A[i] ≤ 10,000

Sample Input 1

7
2 5 1 3 2 3 0

Sample Output 1

0 1 2 2 3 3 5


let () =
  let n = read_int () in
  let a = Array.init n (fun _ -> Scanf.scanf "%d " (fun e -> e)) in
  let b = Array.make n 0 in
  let c = Array.make (10000 + 1) 0 in
  Array.iter (fun e -> c.(e) <- c.(e) + 1) a;
  Array.iteri (fun i _ -> if i <> 0 then c.(i) <- c.(i) + c.(i-1)) c;
  for i = n - 1 downto 0 do
    b.(c.( a.(i) ) - 1) <- a.(i);
    c.( a.(i) ) <- c.( a.(i) ) - 1;
  done;
  print_int b.(0);
  for i = 1 to n - 1 do
    print_string " ";
    print_int b.(i);
  done;
  print_newline ()


let counting_sort a b k n =
  let c = Array.make (k + 1) 0 in
  Array.iter (fun e -> c.(e) <- c.(e) + 1) a;
  for i = 1 to k do
    c.(i) <- c.(i) + c.(i-1)
  done;
  for i = n - 1 downto 0 do
    b.(c.( a.(i) ) - 1) <- a.(i);
    c.( a.(i) ) <- c.( a.(i) ) - 1;
  done

let () =
  let n = read_int () in
  let a = Array.init n (fun _ -> Scanf.scanf "%d " (fun e -> e)) in
  let b = Array.make n 0 in
  counting_sort a b 10000 n;
  print_int b.(0);
  for i = 1 to n - 1 do
    print_string " "; print_int b.(i);
  done;
  print_newline ()


let partition (a : int array) p r =
  let x = a.(r) in
  let swap i j = let t = a.(i) in a.(i) <- a.(j); a.(j) <- t
  in
  let rec doit i j =
    if j >= r then i
    else begin
      if a.(j) <= x then (swap (i + 1) j; doit (i + 1) (j + 1))
      else doit i (j + 1)
    end
  in
  let i = doit (p - 1) p in
  swap (i + 1) r;
  i + 1

let () =
  let n = read_int () in
  let a = Array.init n (fun _ -> Scanf.scanf "%d " (fun i -> i)) in
  let k = partition a 0 (n - 1) in
  Array.iteri (fun i e ->
    Printf.printf (if i = 0 then "%d" else if i = k then " [%d]" else " %d") e) a;
  print_newline ()

Partition

Quick sort is based on the Divide-and-conquer approach. In QuickSort(A, p, r), first, a procedure Partition(A, p, r) divides an array A[p..r] into two subarrays A[p..q-1] and A[q+1..r] such that each element of A[p..q-1] is less than or equal to A[q], which is, inturn, less than or equal to each element of A[q+1..r]. It also computes the index q.

In the conquer processes, the two subarrays A[p..q-1] and A[q+1..r] are sorted by recursive calls of QuickSort(A, p, q-1) and QuickSort(A, q+1, r).

Your task is to read a sequence A and perform the Partition based on the following pseudocode:

Partition(A, p, r)
1 x = A[r]
2 i = p-1
3 for j = p to r-1
4 do if A[j] <= x
5 then i = i+1
6 exchange A[i] and A[j]
7 exchange A[i+1] and A[r]
8 return i+1

Note that, in this algorithm, Partition always selects an element A[r] as a pivot element around which to partition the array A[p..r].

Input

The first line of the input includes an integer n, the number of elements in the sequence A.

In the second line, Ai (i = 1,2,...,n), elements of the sequence are given separated by space characters.

Output

Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character. The element which is selected as the pivot of the partition should be indicated by [  ].

Constraints

1 ≤ n ≤ 100,000

0 ≤ Ai ≤ 100,000

Sample Input 1

12
13 19 9 5 12 8 7 4 21 2 6 11

Sample Output 1

9 5 8 7 4 2 6 [11] 21 13 19 12


open Printf
open Scanf

type card = {suit : string; value : int}

let id x = x

let partition cmp a p r =
  let swap i j =
    let t = a.(i) in
    a.(i) <- a.(j);
    a.(j) <- t in
  let x = a.(r) in
  let rec iter i j =
    if j = r then begin swap (i+1) r; i+1 end
    else if cmp a.(j) x <= 0 then
      let ii = i+1 in
      swap ii j;
      iter ii (j+1)
    else iter i (j+1) in
  iter (p-1) p

let rec quick_sort cmp a p r =
  if p >= r then ()
  else let q = partition cmp a p r in
       quick_sort cmp a p (q-1);
       quick_sort cmp a (q+1) r

let () =
  let n = scanf "%d\n" id in
  let ar = Array.init n (fun _ -> scanf "%s %d\n" (fun x y -> {suit = x; value = y})) in
  let ar2 = Array.copy ar in
  quick_sort (fun x y -> compare x.value y.value) ar 0 (n-1);
  Array.stable_sort (fun x y -> compare x.value y.value) ar2;
  printf "%s\n" (if ar = ar2 then "Stable" else "Not stable");
  Array.iter (fun x -> printf "%s %d\n" x.suit x.value) ar

Quick Sort

Let's arrange a deck of cards. Your task is to sort totally n cards. A card consists of a part of a suit (S, H, C or D) and an number. Write a program which sorts such cards based on the following pseudocode:

Partition(A, p, r)
1 x = A[r]
2 i = p-1
3 for j = p to r-1
4 do if A[j] <= x
5 then i = i+1
6 exchange A[i] and A[j]
7 exchange A[i+1] and A[r]
8 return i+1

Quicksort(A, p, r)
1 if p < r
2 then q = Partition(A, p, r)
3 run Quicksort(A, p, q-1)
4 run Quicksort(A, q+1, r)

Here, A is an array which represents a deck of cards and comparison operations are performed based on the numbers.

Your program should also report the stability of the output for the given input (instance). Here, 'stability of the output' means that: cards with the same value appear in the output in the same order as they do in the input (instance).

Input

The first line contains an integer n, the number of cards.

n cards are given in the following lines. Each card is given in a line and represented by a pair of a character and an integer separated by a single space.

Output

In the first line, print the stability ("Stable" or "Not stable") of this output.

In the following lines, print the arranged cards in the same manner of that of the input.

Constraints

1 ≤ n ≤ 100,000

1 ≤ the number of a card ≤ 109

There are no identical card in the input

Sample Input 1

6
D 3
H 2
D 1
S 3
D 2
C 1

Sample Output 1

Not stable
D 1
C 1
D 2
H 2
D 3
S 3

Sample Input 2

2
S 1
H 1

Sample Output 2

Stable
S 1
H 1


let nil = -1

type tree = { mutable parent : int; mutable child : int; mutable bro : int; mutable depth : int }

let make () = { parent = nil; child = nil; bro = nil; depth = nil }

let set_depth t n =
  let rec root i =
    if i = n then nil
    else if t.(i).parent = nil then i
    else root (i + 1) in
  let rec doit i d =
    t.(i).depth <- d;
    if t.(i).bro <> nil then doit t.(i).bro d;
    if t.(i).child <> nil then doit t.(i).child (d + 1) in
  doit (root 0) 0

let print_tree t =
  t |> Array.iteri (fun i _ ->
    print_string "node "; print_int i;
    print_string ": parent = "; print_int t.(i).parent;
    print_string ", depth = "; print_int t.(i).depth;
    print_string (if t.(i).parent = nil then ", root, [" else if t.(i).child = nil then ", leaf, [" else ", internal node, [");
    let rec print_children c =
      if c <> nil then begin
        if c <> t.(i).child then print_string ", ";
        print_int c;
        print_children t.(c).bro
      end in
    print_children t.(i).child;
    print_string "]\n")

let () =
  let n = Scanf.scanf "%d " (fun i -> i) in
  let t = Array.init n (fun _ -> make ()) in
  for _ = 0 to n - 1 do
    let (id, k) = Scanf.scanf "%d %d " (fun id k -> (id, k)) in
    let left_child = ref 0 in
    for i = 0 to k - 1 do
      let c = Scanf.scanf "%d " (fun i -> i) in
      t.(c).parent <- id;
      if i = 0 then t.(id).child <- c else t.(!left_child).bro <- c;
      left_child := c;
    done;
  done;
  set_depth t n;
  print_tree t

Rooted Trees

A graph G = (V, E) is a data structure where V is a finite set of vertices and E is a binary relation on V represented by a set of edges. Fig. 1 illustrates an example of a graph (or graphs).

Fig. 1

A free tree is a connnected, acyclic, undirected graph. A rooted tree is a free tree in which one of the vertices is distinguished from the others. A vertex of a rooted tree is called "node."

Your task is to write a program which reports the following information for each node u of a given rooted tree T:

node ID of u

parent of u

depth of u

node type (root, internal node or leaf)

a list of chidlren of u

If the last edge on the path from the root r of a tree T to a node x is (p, x), then p is the parent of x, and x is a child of p. The root is the only node in T with no parent.

A node with no children is an external node or leaf. A nonleaf node is an internal node

The number of children of a node x in a rooted tree T is called the degree of x.

The length of the path from the root r to a node x is the depth of x in T.

Here, the given tree consists of n nodes and evey node has a unique ID from 0 to n-1.

Fig. 2 shows an example of rooted trees where ID of each node is indicated by a number in a circle (node). The example corresponds to the first sample input.

Fig. 2

Input

The first line of the input includes an integer n, the number of nodes of the tree.

In the next n lines, the information of each node u is given in the following format:

id k c1 c2 ... ck

where id is the node ID of u, k is the degree of u, c1 ... ck are node IDs of 1st, ... kth child of u. If the node does not have a child, the k is 0.

Output

Print the information of each node in the following format ordered by IDs:

node id: parent = p, depth = d, type, [c1...ck]

p is ID of its parent. If the node does not have a parent, print -1.

d is depth of the node.

type is a type of nodes represented by a string (root, internal node or leaf). If the root can be considered as a leaf or an internal node, print root.

c1...ck is the list of children as a ordered tree.

Please follow the format presented in a sample output below.

Constraints

1 ≤ n ≤ 100000

Sample Input 1

13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0

Sample Output 1

node 0: parent = -1, depth = 0, root, [1, 4, 10]
node 1: parent = 0, depth = 1, internal node, [2, 3]
node 2: parent = 1, depth = 2, leaf, []
node 3: parent = 1, depth = 2, leaf, []
node 4: parent = 0, depth = 1, internal node, [5, 6, 7]
node 5: parent = 4, depth = 2, leaf, []
node 6: parent = 4, depth = 2, leaf, []
node 7: parent = 4, depth = 2, internal node, [8, 9]
node 8: parent = 7, depth = 3, leaf, []
node 9: parent = 7, depth = 3, leaf, []
node 10: parent = 0, depth = 1, internal node, [11, 12]
node 11: parent = 10, depth = 2, leaf, []
node 12: parent = 10, depth = 2, leaf, []

Sample Input 2

4
1 3 3 2 0
0 0
3 0
2 0

Sample Output 2

node 0: parent = 1, depth = 1, leaf, []
node 1: parent = -1, depth = 0, root, [3, 2, 0]
node 2: parent = 1, depth = 1, leaf, []
node 3: parent = 1, depth = 1, leaf, []

Note

You can use a left-child, right-sibling representation to implement a tree which has the following data:

the parent of u

the leftmost child of u

the immediate right sibling of u

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


let nil = -1

type tree = { mutable parent : int; mutable child : int; mutable bro : int; mutable depth : int }

let make () = { parent = nil; child = nil; bro = nil; depth = nil }

let set_depth t n =
  let rec root i =
    if i = n then nil
    else if t.(i).parent = nil then i
    else root (i + 1) in
  let rec doit i d =
    t.(i).depth <- d;
    if t.(i).bro <> nil then doit t.(i).bro d;
    if t.(i).child <> nil then doit t.(i).child (d + 1) in
  doit (root 0) 0

let print_tree t =
  let rec string_of_children i c acc =
    if c = nil then acc
    else string_of_children i t.(c).bro (acc ^ (if c <> t.(i).child then ", " else "") ^ string_of_int c) in
  let string_of_children i c = string_of_children i c "" in
  t |> Array.iteri (fun i _ ->
    "node " ^ string_of_int i ^ ": parent = " ^ string_of_int t.(i).parent
       ^ ", depth = " ^ string_of_int t.(i).depth
       ^ (if t.(i).parent = nil then ", root, ["
          else if t.(i).child = nil then ", leaf, ["
          else ", internal node, [")
       ^ string_of_children i t.(i).child
       ^ "]\n"
    |> print_string)

let () =
  let n = Scanf.scanf "%d " (fun i -> i) in
  let t = Array.init n (fun _ -> make ()) in
  for _ = 0 to n - 1 do
    let (id, k) = Scanf.scanf "%d %d " (fun id k -> (id, k)) in
    let left_child = ref 0 in
    for i = 0 to k - 1 do
      let c = Scanf.scanf "%d " (fun i -> i) in
      t.(c).parent <- id;
      if i = 0 then t.(id).child <- c
      else t.(!left_child).bro <- c;
      left_child := c;
    done;
  done;
  set_depth t n;
  print_tree t


let nil = -1

type tree = { mutable parent : int; mutable child : int; mutable bro : int; mutable depth : int }

let make () = { parent = nil; child = nil; bro = nil; depth = nil }

let set_depth t n =
  let rec root i =
    if i = n then nil
    else if t.(i).parent = nil then i
    else root (i + 1) in
  let rec doit i d =
    t.(i).depth <- d;
    if t.(i).bro <> nil then doit t.(i).bro d;
    if t.(i).child <> nil then doit t.(i).child (d + 1) in
  doit (root 0) 0

let print_tree t =
  let rec string_of_children i c acc =
    if c = nil then acc
    else string_of_children i t.(c).bro (acc ^ (if c <> t.(i).child then ", " else "") ^ string_of_int c) in
  let string_of_children i c = string_of_children i c "" in
  t |> Array.iteri (fun i _ ->
    "node " ^ string_of_int i ^ ": parent = " ^ string_of_int t.(i).parent
       ^ ", depth = " ^ string_of_int t.(i).depth
       ^ (if t.(i).parent = nil then ", root, ["
          else if t.(i).child = nil then ", leaf, ["
          else ", internal node, [")
       ^ string_of_children i t.(i).child
       ^ "]"
    |> Printf.printf "%s\n")

let () =
  let n = Scanf.scanf "%d " (fun i -> i) in
  let t = Array.init n (fun _ -> make ()) in
  for _ = 0 to n - 1 do
    let (id, k) = Scanf.scanf "%d %d " (fun id k -> (id, k)) in
    let left_child = ref 0 in
    for i = 0 to k - 1 do
      let c = Scanf.scanf "%d " (fun i -> i) in
      t.(c).parent <- id;
      if i = 0 then t.(id).child <- c
      else t.(!left_child).bro <- c;
      left_child := c;
    done;
  done;
  set_depth t n;
  print_tree t


type bs_tree = Nil | Node of node and
     node = {
         key:int;
         mutable left:bs_tree;
         mutable right:bs_tree
       };;

let new_node key = {key=key;left=Nil;right=Nil};;

let insert t z =
  let rec loop y = function
      Nil -> y
    | Node x ->
       if z.key < x.key then
         loop (Node x) (x.left)
       else
         loop (Node x) (x.right)
  in
  let y = loop t t in
  match y with
    Nil -> (Node z)
  | Node y ->
     if z.key < y.key then
       y.left <- (Node z)
     else
       y.right <- (Node z)
    ;t
;;

let rec print_in = function
    Nil -> ()
  | Node x ->
     print_in (x.left);
     Printf.printf " %d" x.key;
     print_in (x.right)
;;

let rec print_pre = function
    Nil -> ()
  | Node x ->
     Printf.printf " %d" x.key;
     print_pre (x.left);print_pre (x.right)
;;

let () =
  let n = read_int () in
  let rec read t = function
      0 -> ()
    | i ->
       let com = Scanf.scanf "%s" (fun x -> x) in
       if com = "insert" then begin
           let arg = Scanf.scanf " %d\n" (fun x -> x) in
           let z = new_node arg in
           read (insert t z) (i-1)
         end
       else if com = "print" then begin
           let _ = Scanf.scanf "%s\n" (fun x -> x) in
           print_in t;print_newline ();
           print_pre t;print_newline ();
           read t (i-1)
         end
       else ()
  in read Nil n
;;

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Binary Search Tree I

Search trees are data structures that support dynamic set operations including insert, search, delete and so on. Thus a search tree can be used both as a dictionary and as a priority queue.

Binary search tree is one of fundamental search trees. The keys in a binary search tree are always stored in such a way as to satisfy the following binary search tree property:

Let $x$ be a node in a binary search tree. If $y$ is a node in the left subtree of $x$, then $y.key \leq x.key$. If $y$ is a node in the right subtree of $x$, then $x.key \leq y.key$.

The following figure shows an example of the binary search tree.

For example, keys of nodes which belong to the left sub-tree of the node containing 80 are less than or equal to 80, and keys of nodes which belong to the right sub-tree are more than or equal to 80. The binary search tree property allows us to print out all the keys in the tree in sorted order by an inorder tree walk.

A binary search tree should be implemented in such a way that the binary search tree property continues to hold after modifications by insertions and deletions. A binary search tree can be represented by a linked data structure in which each node is an object. In addition to a key field and satellite data, each node contains fields left, right, and p that point to the nodes corresponding to its left child, its right child, and its parent, respectively.

To insert a new value $v$ into a binary search tree $T$, we can use the procedure insert as shown in the following pseudo code. The insert procedure is passed a node $z$ for which $z.key = v$, $z.left = NIL$, and $z.right = NIL$. The procedure modifies $T$ and some of the fields of $z$ in such a way that $z$ is inserted into an appropriate position in the tree.

1 insert(T, z)
2 y = NIL // parent of x
3 x = 'the root of T'
4 while x ≠ NIL
5 y = x // set the parent
6 if z.key < x.key
7 x = x.left // move to the left child
8 else
9 x = x.right // move to the right child
10 z.p = y
11
12 if y == NIL // T is empty
13 'the root of T' = z
14 else if z.key < y.key
15 y.left = z // z is the left child of y
16 else
17 y.right = z // z is the right child of y

Write a program which performs the following operations to a binary search tree $T$.

insert $k$: Insert a node containing $k$ as key into $T$.

print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.

You should use the above pseudo code to implement the insert operation. $T$ is empty at the initial state.

Input

In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$ or print are given.

Output

For each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key.

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

$-2,000,000,000 \leq key \leq 2,000,000,000$

The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

8
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
print

Sample Output 1

1 12 17 20 25 30 88
30 12 1 20 17 25 88

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


module T = struct
  type tree = Nil | Node of int * tree * tree

  let create () = Nil

  let insert x t =
    let rec doit = function
      | Nil -> Node (x, Nil, Nil)
      | (Node (y, _, _)) as d when x = y -> d
      | Node (y, l, r) when x < y -> Node (y, doit l, r)
      | Node (y, l, r) -> Node (y, l, doit r)
    in
    doit t

  let preorder f t =
    let rec doit = function
      | Nil -> ()
      | Node (x, l, r) -> (f x; doit l; doit r)
    in
    doit t

  let inorder f t =
    let rec doit = function
      | Nil -> ()
      | Node (x, l, r) -> (doit l; f x; doit r)
    in
    doit t
end

let print t =
  let f e = print_string " "; print_int e in
  T.inorder f t;
  print_newline ();
  T.preorder f t;
  print_newline ()

let split str delim =
  let rec doit s acc =
    match
      try Some (String.rindex s delim) with _ -> None
    with
    | None -> s :: acc
    | Some i ->
        let s1 = String.sub s 0 i in
        let s2 = String.sub s (i + 1) (String.length s - String.length s1 - 1) in
        doit s1 (s2 :: acc)
  in
  doit str []

let () =
  let m = read_int () in
  let rec read i t =
    if i < m then begin
      match split (read_line ()) ' ' with
      | ["insert"; n] -> read (i + 1) (T.insert (int_of_string n) t)
      | _ -> (print t; read (i + 1) t)
    end
  in
  read 0 (T.create ())


type tree = Nil | Node of int * tree * tree

let create () = Nil

let insert x t =
  let rec doit = function
    | Nil -> Node (x, Nil, Nil)
    | Node (y, l, r) when x < y -> Node (y, doit l, r)
    | Node (y, l, r) -> Node (y, l, doit r)
  in doit t

let preorder f t =
  let rec doit = function
    | Nil -> ()
    | Node (x, l, r) -> (f x; doit l; doit r)
  in doit t

let inorder f t =
  let rec doit = function
    | Nil -> ()
    | Node (x, l, r) -> (doit l; f x; doit r)
  in doit t

let print t =
  let f e = print_string " "; print_int e in
  inorder f t;
  print_newline ();
  preorder f t;
  print_newline ()

let split str delim =
  let rec doit s acc =
    match
      try Some (String.rindex s delim) with _ -> None
    with
    | None -> s :: acc
    | Some i ->
        let s1 = String.sub s 0 i in
        doit s1 (String.sub s (i + 1) (String.length s - String.length s1 - 1) :: acc)
  in doit str []

let () =
  let m = read_int () in
  let rec read i t =
    if i < m then begin
      match split (read_line ()) ' ' with
      | ["insert"; n] -> read (i + 1) (insert (int_of_string n) t)
      | _ -> (print t; read (i + 1) t)
    end in
  read 0 (create ())


type tree = Nil | Node of int * tree * tree

let create () = Nil

let insert x t =
  let rec doit = function
    | Nil -> Node (x, Nil, Nil)
    | Node (y, l, r) when x < y -> Node (y, doit l, r)
    | Node (y, l, r) -> Node (y, l, doit r)
  in doit t

let preorder f t =
  let rec doit = function
    | Nil -> ()
    | Node (x, l, r) -> (f x; doit l; doit r)
  in doit t

let inorder f t =
  let rec doit = function
    | Nil -> ()
    | Node (x, l, r) -> (doit l; f x; doit r)
  in doit t

let print t =
  let f e = print_string " "; print_int e in
  inorder f t;
  print_newline ();
  preorder f t;
  print_newline ()

let find x t =
  let rec doit = function
    | Nil -> false
    | Node (y, _, _) when x = y -> true
    | Node (y, l, _) when x < y -> doit l
    | Node (_, _, r) -> doit r
  in doit t

let split str delim =
  let open String in
  let rec doit s acc =
    match
      try Some (rindex s delim) with _ -> None
    with
    | None -> s :: acc
    | Some i ->
        let s1 = sub s 0 i in
        doit s1 (sub s (i + 1) (length s - length s1 - 1) :: acc)
  in doit str []

let () =
  let m = read_int () in
  let rec read i t =
    if i < m then begin
      match split (read_line ()) ' ' with
      | ["insert"; n] -> read (i + 1) (insert (int_of_string n) t)
      | ["find"; n] -> (print_endline (if find (int_of_string n) t then "yes" else "no"); read (i + 1) t)
      | _ -> (print t; read (i + 1) t)
    end in
  read 0 (create ())

Binary Search Tree II

Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I.

insert $k$: Insert a node containing $k$ as key into $T$.

find $k$: Report whether $T$ has a node containing $k$.

print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.

Input

In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given.

Output

For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not.

In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key.

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

$-2,000,000,000 \leq key \leq 2,000,000,000$

The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

10
insert 30
insert 88
insert 12
insert 1
insert 20
find 12
insert 17
insert 25
find 16
print

Sample Output 1

yes
no
1 12 17 20 25 30 88
30 12 1 20 17 25 88

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


open Str

type btree = Node of node | Nil and
     node = {k : int; l : btree; r : btree}

let preorder f tr =
  let rec iter = function
      Nil -> ()
    | Node n -> f n.k; iter n.l; iter n.r
  in iter tr; print_newline ()

let inorder f tr =
  let rec iter = function
      Nil -> ()
    | Node n -> iter n.l; f n.k; iter n.r
  in iter tr; print_newline ()

let insert k tr =
  let rec iter = function
      Nil -> Node {k = k; l = Nil; r = Nil}
    | Node n -> if n.k = k then Node n
                else if n.k < k then Node {n with r = iter n.r}
                else Node {n with l = iter n.l}
  in iter tr

let find k tr =
  let rec iter = function
      Nil -> "no"
    | Node n -> if n.k = k then "yes"
                else if n.k < k then iter n.r
                else iter n.l
  in iter tr

let read_list () =
  split (regexp " +") (read_line ())

let () =
  let n = read_int () in
  let rec read tr x =
    if x = 0 then ()
    else match read_list () with
           "print" :: _ -> begin
             inorder (fun i -> print_string @@ " " ^ (string_of_int i)) tr;
             preorder (fun i -> print_string @@ " " ^ (string_of_int i)) tr;
             read tr (x-1)
           end
         | "insert" :: ns :: _ -> read (insert (int_of_string ns) tr) (x-1)
         | "find" :: ns :: _ -> begin
             find (int_of_string ns) tr |> print_endline;
             read tr (x-1)
           end
         | _ -> failwith "read"
  in
  read Nil n


type tree = Nil | Node of int * tree * tree

let create () = Nil

let insert x t =
  let rec doit = function
    | Nil -> Node (x, Nil, Nil)
    | Node (y, l, r) when x < y -> Node (y, doit l, r)
    | Node (y, l, r) -> Node (y, l, doit r)
  in doit t

let preorder f t =
  let rec doit = function
    | Nil -> ()
    | Node (x, l, r) -> (f x; doit l; doit r)
  in doit t

let inorder f t =
  let rec doit = function
    | Nil -> ()
    | Node (x, l, r) -> (doit l; f x; doit r)
  in doit t

let print t =
  let f e = print_string " "; print_int e in
  inorder f t;
  print_newline ();
  preorder f t;
  print_newline ()

let find x t =
  let rec doit = function
    | Nil -> false
    | Node (y, _, _) when x = y -> true
    | Node (y, l, _) when x < y -> doit l
    | Node (_, _, r) -> doit r
  in doit t

let delete x t =
  let rec dudu = function
    | Nil -> exit 1
    | Node (x, Nil, _) -> x
    | Node (_, l, _) -> dudu l
  and wa = function
    | Nil -> exit 1
    | Node (_, Nil, r) -> r
    | Node (x, l, r) -> Node (x, wa l, r)
  and doit = function
    | Nil -> exit 1
    | Node (y, l, r) when x = y ->
      if l = Nil then r
      else if r = Nil then l
      else Node (dudu r, l, wa r)
    | Node (y, l, r) when x < y -> Node (y, doit l, r)
    | Node (y, l, r) -> Node (y, l, doit r)
  in doit t

let split str delim =
  let open String in
  let rec doit s acc =
    match
      try Some (rindex s delim) with _ -> None
    with
    | None -> s :: acc
    | Some i ->
      let s1 = sub s 0 i in
      doit s1 (sub s (i + 1) (length s - length s1 - 1) :: acc)
  in doit str []

let () =
  let m = read_int () in
  let rec read i t =
    if i < m then begin
      match split (read_line ()) ' ' with
      | ["insert"; n] -> read (i + 1) (insert (int_of_string n) t)
      | ["find"; n] -> (print_endline (if find (int_of_string n) t then "yes" else "no"); read (i + 1) t)
      | ["delete"; n] -> read (i + 1) (delete (int_of_string n) t)
      | _ -> (print t; read (i + 1) t)
    end in
  read 0 (create ())

Binary Search Tree III

Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II.

insert $k$: Insert a node containing $k$ as key into $T$.

find $k$: Report whether $T$ has a node containing $k$.

delete $k$: Delete a node containing $k$.

print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively.

The operation delete $k$ for deleting a given node $z$ containing key $k$ from $T$ can be implemented by an algorithm which considers the following cases:

If $z$ has no children, we modify its parent $z.p$ to replace $z$ with NIL as its child (delete $z$).

If $z$ has only a single child, we "splice out" $z$ by making a new link between its child and its parent.

If $z$ has two children, we splice out $z$'s successor $y$ and replace $z$'s key with $y$'s key.

Input

In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$, delete $k$ or print are given.

Output

For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not.

In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

$-2,000,000,000 \leq key \leq 2,000,000,000$

The height of the binary tree does not exceed 100 if you employ the above pseudo code.

The keys in the binary search tree are all different.

Sample Input 1

18
insert 8
insert 2
insert 3
insert 7
insert 22
insert 1
find 1
find 2
find 3
find 4
find 5
find 6
find 7
find 8
print
delete 3
delete 7
print

Sample Output 1

yes
yes
yes
no
no
no
yes
yes
1 2 3 7 8 22
8 2 1 3 7 22
1 2 8 22
8 2 1 22

Reference

Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. The MIT Press.


let last_i = ref 0

let parent i = int_of_float (floor (float_of_int i) /. 2.)

let left i = 2*i

let right i = 2*i + 1

let extract (t : int array) =
  let rec max_heapify i =
    let l = left i in
    let r = right i in
    let m = if l <= !last_i && t.(l) > t.(i) then l else i in
    let m = if r <= !last_i && t.(r) > t.(m) then r else m in
    if i = m then ()
    else begin
      let tmp = t.(i) in
      t.(i) <- t.(m);
      t.(m) <- tmp;
      max_heapify m
    end in
  let ret = t.(1) in
  t.(1) <- t.(!last_i);
  decr last_i;
  max_heapify 1;
  ret

let insert x (t : int array) =
  let rec doit i =
    let p = parent i in
    if i <= 1 || t.(p) >= t.(i) then ()
    else begin
      let tmp = t.(i) in
      t.(i) <- t.(p);
      t.(p) <- tmp;
      doit p
    end in
  incr last_i;
  t.(!last_i) <- x;
  doit !last_i

let () =
  let t = Array.make 2000001 0 in
  let rec doit () =
    let op = Scanf.scanf "%s " (fun i -> i) in
    if op = "end" then ()
    else if op = "extract" then begin
      extract t |> Printf.printf "%d\n";
      doit ()
    end else begin
      insert (Scanf.scanf "%d " (fun i -> i)) t;
      doit ()
    end in
  doit ()

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Priority Queue

A priority queue is a data structure which maintains a set $S$ of elements, each of with an associated value (key), and supports the following operations:

$insert(S, k)$: insert an element $k$ into the set $S$

$extractMax(S)$: remove and return the element of $S$ with the largest key

Write a program which performs the $insert(S, k)$ and $extractMax(S)$ operations to a priority queue $S$.
The priority queue manages a set of integers, which are also keys for the priority.

Input

Multiple operations to the priority queue $S$ are given. Each operation is given by "insert $k$", "extract" or "end" in a line. Here, $k$ represents an integer element to be inserted to the priority queue.

The input ends with "end" operation.

Output

For each "extract" operation, print the element extracted from the priority queue $S$ in a line.

Constraints

The number of operations $\leq 2,000,000$

$0 \leq k \leq 2,000,000,000$

Sample Input 1

insert 8
insert 2
extract
insert 10
extract
insert 11
extract
extract
end

Sample Output 1

8
10
11
2