let solve c n m =
  let dp = Array.make_matrix (m + 1) (n + 1) max_int in
  for i = 1 to m do dp.(i).(0) <- 0 done;
  for i = 1 to m do
    for j = 1 to n do
      dp.(i).(j) <-
        if j - c.(i-1) < 0 then dp.(i-1).(j)
        else min dp.(i-1).(j) (dp.(i).(j - c.(i-1)) + 1)
    done
  done;
  dp.(m).(n)

let () =
  let n, m = Scanf.scanf "%d %d " (fun n m -> n, m) in
  let c = Array.init m (fun _ -> Scanf.scanf "%d " (fun i -> i)) in
  solve c n m |> Printf.printf "%d\n"

Coin Changing Problem

Find the minimum number of coins to make change for n cents using coins of denominations d1, d2,.., dm. The coins can be used any number of times.

Input

n m
d1 d2 ... dm

Two integers n and m are given in the first line. The available denominations are given in the second line.

Output

Print the minimum number of coins in a line.

Constraints

1 ≤ n ≤ 50000

1 ≤ m ≤ 20

1 ≤ denomination ≤ 10000

The denominations are all different and contain 1.

Sample Input 1

55 4
1 5 10 50

Sample Output 1

2

Sample Input 2

15 6
1 2 7 8 12 50

Sample Output 2

2

Sample Input 3

65 6
1 2 7 8 12 50

Sample Output 3

3


let lower_bound (a : int array) first last v =
  let rec doit len first =
    if len = 0 then first
    else
      let half = len / 2 in
      let mid = first + half in
      if a.(mid) < v then doit (len - half - 1) (mid + 1)
      else doit half first in
  doit (last - first + 1) first

let () =
  let n = read_int () in
  let dp = Array.make (n + 1) max_int in
  let l = ref 0 in
  for _ = 0 to n - 1 do
    let a = read_int () in
    let x = lower_bound dp 0 n a in
    dp.(x) <- a;
    if x + 1 > !l then l := x + 1;
  done;
  Printf.printf "%d\n" !l

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

Longest Increasing Subsequence

For a given sequence A = {a0, a1, ... , an-1}, find the length of the longest increasing subsequnece (LIS) in A.

An increasing subsequence of A is defined by a subsequence {ai0, ai1, ... , aik} where 0 ≤ i0 < i1 < ... < ik < n and ai0 < ai1 < ... < aik.

Input

n
a0
a1
:
an-1

In the first line, an integer n is given. In the next n lines, elements of A are given.

Output

The length of the longest increasing subsequence of A.

Constraints

1 ≤ n ≤ 100000

0 ≤ ai ≤ 109

Sample Input 1

5
5
1
3
2
4

Sample Output 1

3

Sample Input 2

3
1
1
1

Sample Output 2

1

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.


type t = { v : int; w : int }

let solve n w a =
  let s = Array.make (w + 1) 0 in
  let t = Array.copy s in
  for i = 0 to n - 1 do
    for j = a.(i).w to w do
      if s.(j - a.(i).w) + a.(i).v > s.(j) then
        t.(j) <- s.(j - a.(i).w) + a.(i).v;
    done;
    Array.iteri (fun i e -> s.(i) <- e) t;
  done;
  t.(w)

let () =
  let (n, w) = Scanf.scanf "%d %d " (fun n w -> n, w) in
  Array.init n (fun _ -> Scanf.scanf "%d %d " (fun v w -> { v; w }))
  |> solve n w |> Printf.printf "%d\n"

0-1 Knapsack Problem II

You have N items that you want to put them into a knapsack. Item i has value vi and weight wi.

You want to find a subset of items to put such that:

The total value of the items is as large as possible.

The items have combined weight at most W, that is capacity of the knapsack.

Find the maximum total value of items in the knapsack.

Input

N W
v1 w1
v2 w2
:
vN wN

The first line consists of the integers N and W. In the following N lines, the value and weight of the i-th item are given.

Output

Print the maximum total values of the items in a line.

Constraints

1 ≤ N ≤ 100

1 ≤ vi ≤ 100

1 ≤ wi ≤ 10,000,000

1 ≤ W ≤ 1,000,000,000

Sample Input 1

4 5
4 2
5 2
2 1
8 3

Sample Output 1

13

Sample Input 2

2 20
5 9
4 10

Sample Output 2

9


let solve h w c =
  let v0 = Array.make w 0 in
  let v1 = Array.make w 0 in
  let r = ref 0 in
  for i = 0 to h - 1 do if c.(i).(0) = 0 then r := 1 done;
  for j = 0 to w - 1 do if c.(0).(j) = 0 then begin v0.(j) <- 1; r := 1 end done;
  for i = 1 to h - 1 do
    if c.(i).(0) = 0 then v1.(0) <- 1;
    for j = 1 to w - 1 do
      if c.(i).(j) = 1 then v1.(j) <- 0
      else begin
        let t = if v0.(j) < v1.(j-1) then v0.(j) else v1.(j-1) in
        v1.(j) <- if v0.(j-1) < t then v0.(j-1) + 1 else t + 1;
        r := if v1.(j) > !r then v1.(j) else !r;
      end
    done;
    Array.iteri (fun i e -> v0.(i) <- e) v1
  done;
  !r * !r

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 () = List.map int_of_string (split_on_char ' ' (read_line ()))

let () =
  match read () with
  | [h; w] ->
    let c = Array.make_matrix h w 0 in
    for i = 0 to h - 1 do
      let rec doit j = function
        | [] -> ()
        | x::xs ->
          c.(i).(j) <- x;
          doit (j + 1) xs in
      doit 0 (read ())
    done;
    Printf.printf "%d\n" (solve h w c)
  | _ -> ()

Largest Square

Given a matrix (H × W) which contains only 1 and 0, find the area of the largest square matrix which only contains 0s.

Input

H W
c1,1 c1,2 ... c1,W
c2,1 c2,2 ... c2,W
:
cH,1 cH,2 ... cH,W

In the first line, two integers H and W separated by a space character are given. In the following H lines, ci,j, elements of the H × W matrix, are given.

Output

Print the area (the number of 0s) of the largest square.

Constraints

1 ≤ H, W ≤ 1,400

Sample Input

4 5
0 0 1 0 0
1 0 0 0 0
0 0 0 1 0
0 0 0 1 0

Sample Output

4


let solve ans w v =
  let rec duduwa ans j k = function
    | [] -> doit ans (j + 1, [(v.(j), k)])
    | (ch, cj) :: y' when ch >= v.(j) -> duduwa (if ch * (j - cj) > ans then ch * (j - cj) else ans) j cj y'
    | ys -> doit ans (j + 1, (v.(j), k) :: ys)
  and doit ans = function
    | (j, xs) when j = w -> List.fold_left (fun acc (ch, cj) -> if ch * (w - cj) > acc then ch * (w - cj) else acc) ans xs
    | (j, []) -> doit ans (j + 1, [(v.(j), j)])
    | (j, ((ch, _) :: _ as xs)) when ch = v.(j) -> doit ans (j + 1, xs)
    | (j, ((ch, _) :: _ as xs)) when ch < v.(j) -> doit ans (j + 1, (v.(j), j) :: xs)
    | (j, xs) -> duduwa ans j j xs in
  doit ans (0, [])

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 () = List.map int_of_string (split_on_char ' ' (read_line ()))

let () =
  match read () with
  | [h; w] ->
    let v0 = Array.make w 0 in
    let v1 = Array.make w 0 in
    let rec doit i ans =
      if i = h then ans
      else
        let rec duduwa j = function
          | [] -> Array.iteri (fun i e -> v0.(i) <- e) v1; doit (i + 1) (solve ans w v1)
          | x::xs ->
            v1.(j) <- 1 - x;
            if i <> 0 then v1.(j) <- if v1.(j) = 0 then 0 else v0.(j) + 1;
            duduwa (j + 1) xs in
        duduwa 0 (read ()) in
    Printf.printf "%d\n" (doit 0 0)
  | _ -> ()

Largest Rectangle

Given a matrix (H × W) which contains only 1 and 0, find the area of the largest rectangle which only contains 0s.

Input

H W
c1,1 c1,2 ... c1,W
c2,1 c2,2 ... c2,W
:
cH,1 cH,2 ... cH,W

In the first line, two integers H and W separated by a space character are given. In the following H lines, ci,j, elements of the H × W matrix, are given.

Output

Print the area (the number of 0s) of the largest rectangle.

Constraints

1 ≤ H, W ≤ 1,400

Sample Input

4 5
0 0 1 0 0
1 0 0 0 0
0 0 0 1 0
0 0 0 1 0

Sample Output

6


module IO = struct

  (* @since 4.04.0 *)
  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_ns () = read_line () |> split_on_char ' ' |> List.map int_of_string

end

let solve ans w v =
  let (ans, _, xs) = Array.fold_left (fun (ans, j, xs) c -> match xs with
    | [] -> (ans, j + 1, [(c, j)])
    | (ch, _) :: _ ->
      if ch = c then (ans, j + 1, xs)
      else if ch < c then (ans, j + 1, (c, j) :: xs)
      else
        let rec f ans k = function
          | [] -> (ans, j + 1, [(c, k)])
          | (ch, cj) :: tl as ys ->
            if ch >= c then f (if ch * (j - cj) > ans then ch * (j - cj) else ans) cj tl
            else (ans, j + 1, (c, k) :: ys) in
        f ans j xs)
    (ans, 0, [])
    v in
  List.fold_left (fun acc (ch, cj) -> if ch * (w - cj) > acc then ch * (w - cj) else acc) ans xs

let () =
  match IO.read_ns () with
  | [h; w] ->
    let s = Array.make w 0 in
    let t = Array.make w 0 in
    let rec doit i ans =
      if i = h then ans
      else begin
        IO.read_ns () |> List.iteri (fun j e -> t.(j) <- if e = 1 then 0 else s.(j) + 1);
        Array.iteri (fun i e -> s.(i) <- e) t;
        solve ans w t |> doit (i + 1)
      end in
    doit 0 0 |> Printf.printf "%d\n"
  | _ -> assert false


let read_lines () =
  let rec iter xs =
    try read_line() :: xs |> iter
    with End_of_file -> xs
  in iter [] |> List.rev

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

let read_ints () =
  read_line () |> split_nums |> Array.of_list

let init n = Array.init n (fun x -> x)

let rec find i a =
  if a.(i) = i then i
  else compress a.(i) a
and compress i a =
  a.(i) <- find i a;
  a.(i)

let same x y a =
  find x a = find y a

let void _ = ()

let unite x y a =
  let i = find x a
  and j = find y a in
  if i = j then ()
  else a.(i) <- j

let () =
  let first_line = read_ints () in
  let tree = init first_line.(0) in
  let answer com x y =
    match com with
    | 0 -> unite x y tree;
    | 1 ->
       Printf.printf "%d\n" (if same x y tree then 1 else 0);
    | _ -> raise Not_found in

  for i = 1 to first_line.(1) do
    let xs = read_ints () in
    answer xs.(0) xs.(1) xs.(2)
  done

Disjoint Set

Write a program which manipulates a disjoint set S = {S1, S2, . . . , Sk}.

First of all, the program should read an integer n, then make a disjoint set where each element consists of 0, 1, ... n−1 respectively.

Next, the program should read an integer q and manipulate the set for q queries. There are two kinds of queries for different operations:

unite(x, y): unites sets that contain x and y, say Sx and Sy, into a new set.

same(x, y): determine whether x and y are in the same set.

Input

n q
com1 x1 y1
com2 x2 y2
...
comq xq yq

In the first line, n and q are given. Then, q queries are given where com represents the type of queries. '0' denotes unite and '1' denotes same operation.

Output

For each same operation, print 1 if x and y are in the same set, otherwise 0, in a line.

Constraints

1 ≤ n ≤ 10000

1 ≤ q ≤ 100000

x ≠ y

Sample Input

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

Sample Output

0
0
1
1
1
0
1
1


type t = { mutable parent : int; mutable rank : int }

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 readln () = read_line () |> split_on_char ' ' |> List.map int_of_string

let find s x =
  let rec doit x =
    let p = s.(x).parent in
    if x = p then x
    else begin
      s.(x).parent <- doit p;
      s.(x).parent
    end in
  doit x

let unite s x y =
  let px = find s x in
  let py = find s y in
  if s.(px).rank > s.(py).rank then s.(py).parent <- px
  else begin
    s.(px).parent <- py;
    if s.(px).rank = s.(py).rank then s.(py).rank <- s.(py).rank + 1
  end

let same_p s x y = find s x = find s y

let solve n q =
  let s = Array.init n (fun i -> { parent = i; rank = 0 }) in
  for i = 0 to q - 1 do
    match readln () with
    | n :: x :: y :: _ ->
      if n = 0 then unite s x y
      else print_endline (if same_p s x y then "1" else "0")
    | _ -> assert false
  done

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


open Printf
open Scanf

module Uftree =
  struct
    type t = int array
    let create n : t = Array.make n (-1)
    let rec find (uft : t) x =
      let p = uft.(x) in
      if p < 0 then x
      else
        let rt = find uft p in
        uft.(x) <- rt; rt
    let unite (uft : t) x y =
      let rx = find uft x in
      let ry = find uft y in
      if rx = ry then ()
      else
        if uft.(rx) < uft.(ry) then
          begin
            uft.(rx) <- uft.(rx) + uft.(ry);
            uft.(ry) <- rx
          end
        else
          begin
            uft.(ry) <- uft.(rx) + uft.(ry);
            uft.(rx) <- ry
          end
    let same (uft : t) x y =
      let rx = find uft x in
      let ry = find uft y in
      rx = ry
    let size (uft : t) x =
      let rx = find uft x in -uft.(rx)
  end

let tuple x y = (x, y)

let () =
  let n, q = scanf "%d %d " tuple in
  let uft = Uftree.create n in
  let rec loop x =
    if x = 0 then ()
    else
      let com, a, b = scanf "%d %d %d " (fun i j k -> (i, j, k)) in
      if com = 0 then
        Uftree.unite uft a b
      else
        (if Uftree.same uft a b then 1 else 0) |> printf "%d\n";
      loop (x-1)
  in loop q


open Printf open Scanf
module Lib = struct
	let i32,i64,ist = Int64.(to_int,of_int,to_string)
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)
	let labs = Int64.abs
	let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)
	let (+=) r v = r := !r + v
	let (-=) r v = r := !r - v
	let ( *= ) r v = r := !r * v
	let (/=) r v = r := !r / v
	let (%=) r v = r := !r % v
	let max_i64,min_i64 = Int64.(max_int,min_int)
	(* math *)
	let ceildiv p q = (p+q-1L) / q
	let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
	let lcm m n = m / gcd m n * n
	module I64_infix = struct
		let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =
			let open Int64 in
			(logand),(logor),(logxor),lognot,
			(fun u v -> shift_left u (i32 v)),
			(fun u v -> shift_right u (i32 v)),
			(fun u v -> shift_right_logical u (i32 v))
	end
	(* input *)
	let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v))
	let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v)
	let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v)
	let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w)
	let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x)
	let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y)
	let i32_get_int _ = Scanf.scanf " %d" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf " %d %d" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y)
	(* utils *)
	external id : 'a -> 'a = "%identity"
	let ( *< ) f g x = f (g x)
	let ( *> ) f g x = g (f x)
	let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)
	let alen a = i64 @@ Array.length a
	let llen l = i64 @@  List.length l
	let string_of_list ?(separator=" ") f ls = ls |> List.map f |> String.concat separator
	let string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
	let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []
	let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
	let fail _ = failwith "fail"
	let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]
	let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev
	let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten
	let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a
	let binary_search ng ok f = let d = if ng < ok then 1L else -1L in
		let rec f0 ng ok =
			if labs (ok - ng) <= 1L then ok
			else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
		in f0 (ng-1L*d) (ok+1L*d)
	let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)
	let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >  v)
	let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)
	let rec fix f x = f (fix f) x
	let fix_memo ?(size=10000) f x =
		let tb = Hashtbl.create ~random:true size in
		let rec f0 x =
			try Hashtbl.find tb x with
			| Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)
		in f0 x
	(* imperative *)
	let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done
	let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do
		match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done
	let repm f t ?(stride=1L) m0 fbod =
		let i,c,m = ref f,ref true,ref m0 in
		while !i<=t && !c do match fbod !m !i with
		| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m
	let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done
	let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do
		match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done
	let repim f t ?(stride=1) m0 fbod =
		let i,c,m = ref f,ref true,ref m0 in
		while !i<=t && !c do match fbod !m !i with
		| `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m
	let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v
	let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v
	let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v
	let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
	let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
	let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v
	(* output *)
	let print_list_mle f ls = string_of_list f ls |> print_endline
	let print_array_mle f a = string_of_array f a |> print_endline
	let print_list f ls = ls |> List.iter (fun v -> printf "%s " @@ f v); print_newline ()
	let print_array f a = a |> Array.iter (fun v -> printf "%s " @@ f v); print_newline ()
	(* debug *)
	let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)
	let dump_i64_list ls = print_list ist ls
	let dump_i64_array a = print_array ist a
end open Lib open Array

module SegTree = struct
	module type S = sig
		type t
		val  op: t -> t -> t
		val def: t
	end
	module RMQ = struct type t = int64 let op = min let def = max_i64 end
	let par i = (i-$1)/$2
	let chl i = 2*$i+$1
	let chr i = 2*$i+$2
	module Make (X:S) = struct
		type t = SegTree of (X.t array * int)
		let raw (SegTree (a,_)) = a
		let make raw =
			let ln = Array.length raw in
			let n =
				let n = ref 1 in
				while !n<ln do n := !n*$2 done; !n in
			let a = Array.make (2*$n-$1) X.def in
			for i=0 to ln-$1 do
				a.(i+$n-$1) <- raw.(i) done;
			for i=n-$2 downto 0 do
				a.(i) <- X.op a.(chl i) a.(chr i) done;
			SegTree (a,n)
		let update_destructive (SegTree(a,n)) i v =
			let i = ref @@ i+$(n-$1) in a.(!i) <- v;
			while !i>0 do
				i := par !i;
				a.(!i) <- X.op a.(chl !i) a.(chr !i) done
		let get_half_open (SegTree(a,n)) l r = (* [l,r) *)
			let rec f0 i p q =
				if q<=l || r<=p then X.def
				else if l<=p && q<=r then a.(i)
				else
					let vl = f0 (2*$i+$1) p ((p+$q)/$2) in
					let vr = f0 (2*$i+$2) ((p+$q)/$2) q in
					X.op vl vr
			in f0 0 0 n
		let get_closed seg l r = get_half_open seg l (r+$1) (* [l,r] *)
	end
end

module RMQ = SegTree.Make(SegTree.RMQ)
let () =
	let n,q = get_2_i64 0 in
	let a = RMQ.make (make (i32 n) (i64 (2 lsl 30) - 1L)) in
	rep 1L q (fun _ ->
		let com,x,y = get_3_i64 0 in
		if com = 0L then (
			RMQ.update_destructive a (i32 x) y
		) else (
			printf "%Ld\n" @@ RMQ.get_closed a (i32 x) (i32 y)
		)
	)

Range Minimum Query (RMQ)

Write a program which manipulates a sequence A = {a0, a1, . . . , an-1} with the following operations:

find(s, t): report the minimum element in as, as+1, . . . ,at.

update(i, x): change ai to x.

Note that the initial values of ai (i = 0, 1, . . . , n−1) are 231-1.

Input

n q
com0 x0 y0
com1 x1 y1
...
comq−1 xq−1 yq−1

In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, q queries are given where com represents the type of queries. '0' denotes update(xi, yi) and '1' denotes find(xi, yi).

Output

For each find operation, print the minimum element.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

If comi is 0, then 0 ≤ xi < n, 0 ≤ yi < 231-1.

If comi is 1, then 0 ≤ xi < n, 0 ≤ yi < n.

Sample Input 1

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

Sample Output 1

1
2

Sample Input 2

1 3
1 0 0
0 0 5
1 0 0

Sample Output 2

2147483647
5


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 parent i = int_of_float ((float_of_int (i - 1)) /. 2.)

let left i = 2*i + 1

let right i = 2*i + 2

let to_pow_of_2 n =
  let rec doit i =
    if i > n then i
    else doit (i * 2) in
  doit 1

let add s n i x =
  let j = n + i - 1 in
  s.(j) <- x + s.(j);
  let rec doit j =
    if j > 0 then begin
      let j = parent j in
      s.(j) <- s.(left j) + s.(right j);
      doit j
    end in
  doit j

let sum s n a b =
  let rec doit a b k l r =
    if r < a || b < l then 0
    else if a <= l && r <= b then s.(k)
    else doit a b (left k) l ((l + r) / 2) + doit a b (right k) ((l + r) / 2 + 1) r in
  doit a b 0 0 (n - 1)

let solve n q =
  let n = to_pow_of_2 n in
  let s = Array.make (2*n) 0 in
  let rec doit i =
    if i < q then begin
      begin match List.map int_of_string (split_on_char ' ' (read_line ())) with
      | 0 :: x :: y :: _ -> add s n x y
      | 1 :: x :: y :: _ -> Printf.printf "%d\n" (sum s n x y)
      | _ -> ()
      end;
      doit (i + 1)
    end in
  doit 0

let () =
  match List.map int_of_string (split_on_char ' ' (read_line ())) with
  | [n; q] -> solve n q
  | _ -> ()

Range Sum Query

Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:

add(i, x): add x to ai.

getSum(s, t): print the sum of as, as+1,...,at.

Note that the initial values of ai (i = 1, 2, . . . , n) are 0.

Input

n q
com1 x1 y1
com2 x2 y2
...
comq xq yq

In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, q queries are given where com represents the type of queries. '0' denotes add(xi, yi) and '1' denotes getSum(xi, yi).

Output

For each getSum operation, print the sum in a line.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

If comi is 0, then 1 ≤ xi ≤ n, 0 ≤ yi ≤ 1000.

If comi is 1, then 1 ≤ xi ≤ n, 1 ≤ yi ≤ n.

Sample Input 1

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

Sample Output 1

3
2


let nil = -1

type node = {
  value : int;
  left : int;
  right : int;
}

let make_node () = { value = nil; left = nil; right = nil }

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 -> doit (sub s 0 i) (sub s (i + 1) (length s - i - 1) :: acc) in
  doit str []

let sort_range (a : (int * int * int) array) first last cmp =
  let swap i j = let tmp = a.(i) in a.(i) <- a.(j); a.(j) <- tmp in
  let partition p r =
    let rec exchange = function
      | (i, j) when j = r -> swap i r; i
      | (i, j) when cmp a.(j) a.(r) <= 0 -> swap i j; exchange (i + 1, j + 1)
      | (i, j) -> exchange (i, j + 1) in
    exchange (p, p) in
  let rec doit p r =
    if p < r then begin
      let q = partition p r in
      doit p (q - 1);
      doit q r
    end in
  doit first (last - 1)

let make_kd_tree p t n =
  let num = ref 0 in
  let rec doit l r d =
    if l >= r then nil
    else begin
      if d mod 2 = 0 then sort_range p l r (fun (_, ax, _) (_, bx, _) -> ax - bx)
      else sort_range p l r (fun (_, _, ay) (_, _, by) -> ay - by);
      let m = (l + r) / 2 in
      let i = !num in
      incr num;
      let il = doit l m (d + 1) in
      let ir = doit (m + 1) r (d + 1) in
      t.(i) <- { value = m; left = il; right = ir };
      i
    end in
  let _ = doit 0 n 0 in
  (p, t)

let find (p : (int * int * int) array) t (sx, sy) (tx, ty) =
  let acc = ref [] in
  let rec doit i d =
    let (id, x, y) = p.(t.(i).value) in
    if sx <= x && x <= tx && sy <= y && y <= ty then acc := id :: !acc;
    if d mod 2 = 0 then begin
      if t.(i).left != nil && sx <= x then doit t.(i).left (d + 1);
      if t.(i).right != nil && x <= tx then doit t.(i).right (d + 1);
    end else begin
      if t.(i).left != nil && sy <= y then doit t.(i).left (d + 1);
      if t.(i).right != nil && y <= ty then doit t.(i).right (d + 1);
    end in
  doit 0 0;
  acc

let () =
  let n = read_int () in
  let p = Array.init n (fun i ->
    match List.map int_of_string (split (read_line ()) ' ') with
    | [x; y] -> (i, x, y)
    | _ -> exit 1) in
  let t = Array.make n (make_node ()) in
  let (p, t) = make_kd_tree p t n in
  let q = read_int () in
  let rec doit i =
    if i < q then
      begin match List.map int_of_string (split (read_line ()) ' ') with
      | [sx; tx; sy; ty] ->
        let z = find p t (sx, sy) (tx, ty) in
        List.iter (fun e -> Printf.printf "%d\n" e) (List.sort (-) !z);
        print_newline ();
        doit (i + 1)
      | _ -> exit 1
      end in
  doit 0

Range Search (kD Tree)

The range search problem consists of a set of attributed records S to determine which records from S intersect with a given range.

For n points on a plane, report a set of points which are within in a given range. Note that you do not need to consider insert and delete operations for the set.

Input

n
x0 y0
x1 y1
:
xn-1 yn-1
q
sx0 tx0 sy0 ty0
sx1 tx1 sy1 ty1
:
sxq-1 txq-1 syq-1 tyq-1

The first integer n is the number of points. In the following n lines, the coordinate of the i-th point is given by two integers xi and yi.

The next integer q is the number of queries. In the following q lines, each query is given by four integers,
sxi,
txi,
syi,
tyi.

Output

For each query, report IDs of points such that
sxi ≤ x ≤ txi and
syi ≤ y ≤ tyi.
The IDs should be reported in ascending order. Print an ID in a line, and print a blank line at the end of output for the each query.

Constraints

0 ≤ n ≤ 500,000

0 ≤ q ≤ 20,000

-1,000,000,000 ≤ x, y, sx, tx, sy, ty ≤ 1,000,000,000

sx ≤ tx

sy ≤ ty

For each query, the number of points which are within the range is less than or equal to 100.

Sample Input 1

6
2 1
2 2
4 2
6 2
3 3
5 4
2
2 4 0 4
4 10 2 5

Sample Output 1

0
1
2
4

2
3
5


let nil = -1

type node = { value : int; left : int; right : int }

let make_node () = { value = nil; left = nil; right = nil }

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 sort_range (a : (int * int * int) array) first last cmp =
  let swap i j = let tmp = a.(i) in a.(i) <- a.(j); a.(j) <- tmp in
  let partition p r =
    let i = ref p in
    for j = p to r - 1 do
      if cmp a.(j) a.(r) <= 0 then (swap !i j; incr i)
    done;
    swap !i r;
    !i in
  let rec doit p r =
    if p >= r then () else
    let q = partition p r in
    doit p (q - 1);
    doit (q + 1) r in
  doit first (last - 1)

let make_kd_tree p t n =
  let rec doit l r d =
    if l >= r then nil
    else begin
      if d mod 2 = 0 then sort_range p l r (fun (_, ax, _) (_, bx, _) -> ax - bx)
      else sort_range p l r (fun (_, _, ay) (_, _, by) -> ay - by);
      let m = (l + r) / 2 in
      t.(m) <- {value = m; left = doit l m (d + 1); right = doit (m + 1) r (d + 1)};
      m
    end in
  let root = doit 0 n 0 in
  (root, p, t)

let ans = ref []

let find (p : (int * int * int) array) t root sx tx sy ty =
  let rec doit i d =
    let (id, x, y) = p.(t.(i).value) in
    if sx <= x && x <= tx && sy <= y && y <= ty then ans := id :: !ans;
    if d mod 2 = 0 then begin
      if t.(i).left != nil && sx <= x then doit t.(i).left (d + 1);
      if t.(i).right != nil && x <= tx then doit t.(i).right (d + 1);
    end else begin
      if t.(i).left != nil && sy <= y then doit t.(i).left (d + 1);
      if t.(i).right != nil && y <= ty then doit t.(i).right (d + 1);
    end in
  doit root 0

let () =
  let n = read_int () in
  let p =
    Array.init n (fun i ->
      match read_line () |> split_on_char ' ' |> List.map int_of_string with
      | [x; y] -> (i, x, y)
      | _ -> assert false) in
  let t = Array.make n (make_node ()) in
  let (root, p, t) = make_kd_tree p t n in
  let q = read_int () in
  for _ = 0 to q - 1 do
    match read_line () |> split_on_char ' ' |> List.map int_of_string with
    | [sx; tx; sy; ty] ->
      find p t root sx tx sy ty;
      List.iter (fun e -> print_int e; print_newline ()) (List.sort (-) !ans);
      print_newline ();
      ans := []
    | _ -> assert false
  done


open Printf
open Scanf

let () =
  let n, q = scanf "%d %d " (fun x y -> (x, y)) in
  let st = Array.make (4*n) 0 in
  let add s t x =
    let rec iter k l r =
      if t <= l || r <= s then ()
      else if s <= l && r <= t then
        st.(k) <- st.(k) + x
      else
        let m = (l + r) / 2 in
        iter (2*k) l m;
        iter (2*k+1) m r in
    iter 1 0 n in
  let get i =
    let rec iter k l r s =
      if i = l && i+1 = r then s + st.(k)
      else
        let m = (l + r) / 2 in
        if i < m then iter (2*k) l m (s + st.(k))
        else iter (2*k+1) m r (s + st.(k))
    in
    iter 1 0 n 0 in
  let rec loop c =
    if c = 0 then ()
    else
      begin
        begin
          let com = scanf "%d " (fun a -> a) in
          if com = 0 then
            let s, t, x = scanf "%d %d %d " (fun a b c -> (a-1, b, c)) in
            add s t x
          else
            let i = scanf "%d " (fun a -> a-1) in
            get i |> printf "%d\n"
        end;
        loop (c-1)
      end
  in loop q

Range Add Query (RAQ)

Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:

add(s, t, x): add x to as, as+1, ..., at.

get(i): output the value of ai.

Note that the initial values of ai (i = 1, 2, . . . , n) are 0.

Input

n q
query1
query2
:
queryq

In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:

0 s t x

or

1 t

The first digit represents the type of the query. '0' denotes add(s, t, x) and '1' denotes get(i).

Output

For each get operation, print the value.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

1 ≤ s ≤ t ≤ n

1 ≤ i ≤ n

0 ≤ x ≤ 1000

Sample Input 1

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

Sample Output 1

3
5

Sample Input 2

4 3
1 2
0 1 4 1
1 2

Sample Output 2

0
1


open Printf
open Scanf

let () =
  let n, q = scanf "%d %d " (fun a b -> (a, b)) in
  let b = 300 in
  let iv = 2147483647 in
  let ar = Array.make n iv in
  let ubk = Array.make ((n + b - 1) / b) None in
  let mbk = Array.make ((n + b - 1) / b) iv in
  let wb i = match ubk.(i) with
      None -> ()
    | Some v -> let rec iter j =
                  if j = b then ubk.(i) <- None
                  else begin
                      ar.(i*b+j) <- v;
                      iter (j+1)
                    end in
                iter 0;
                mbk.(i) <- v
  in
  let update s t x =
    let rec iter i =
      if i >= t then ()
      else
        if i mod b = 0 && i + b <= t then
          begin
            ubk.(i / b) <- Some x;
            mbk.(i / b) <- x;
            iter (i + b)
          end
        else
          begin
            (match ubk.(i / b) with
               None -> ()
             | Some _ -> wb (i / b));
            ar.(i) <- x;
            mbk.(i / b) <- min mbk.(i / b) x;
            iter (i + 1)
          end
    in iter s
  in
  let find s t =
    let rec iter i m =
      if i >= t then m
      else
        if i mod b = 0 && i + b <= t then
          iter (i + b) (min m mbk.(i / b))
        else
          iter (i + 1) (min m ar.(i))
    in
    iter s iv
  in
  let rec loop c =
    if c = 0 then ()
    else
      begin
        (let com = scanf "%d " (fun u -> u) in
        if com = 0 then
          let s, t, x = scanf "%d %d %d " (fun u v w -> (u, v+1, w)) in
          update s t x
        else
          let s, t = scanf "%d %d " (fun u v -> (u, v+1)) in
          find s t |> printf "%d\n");
        loop (c - 1)
      end
  in
  loop q

RMQ and RUQ

Write a program which manipulates a sequence A = {a0, a1, . . . , an−1} with the following operations:

update(s, t, x): change as, as+1, ..., at to x.

find(s, t): report the minimum element in as, as+1, ..., at.

Note that the initial values of ai (i = 0, 1, . . . , n−1) are 231-1.

Input

n q
query1
query2
:
queryq

In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:

0 s t x

or

1 s t

The first digit represents the type of the query. '0' denotes update(s, t, x) and '1' denotes find(s, t).

Output

For each find operation, print the minimum value.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

0 ≤ s ≤ t < n

0 ≤ x < 231−1

Sample Input 1

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

Sample Output 1

1
2

Sample Input 2

1 3
1 0 0
0 0 0 5
1 0 0

Sample Output 2

2147483647
5


open Batteries
class union_find n = object (self)
  val mutable par = ( [| |] : int array)
  method init =
    par <- Array.init n (fun a -> a)
  method get_par = par

  method root s =
    let rec loop x =
      if par.(x) = x then x else (par.(x) <- loop par.(x); par.(x))
    in loop s

  method rank s =
    let rec loop x n =
      if par.(x) = x then n else loop par.(x) (n+1)
    in loop s 1

  method unite x y =
    let xrank = self#rank x in
    let yrank = self#rank x in
    let rx = self#root x in
    let ry = self#root y in
    if rx != ry then (if xrank < yrank then par.(rx) <- ry else par.(ry) <- rx)

  method same x y = self#root x = self#root y

  method members x = (* 要素xが属する木の全ての要素を返す *)
    let r = self#root x in Array.fold_left (fun a y -> if self#root y = r then y :: a else a) [] par

  method roots = (* 全ての根 *) Array.fold_left (fun x y -> if List.mem y x then x else y :: x) [] par

  method tree_count = (* 木の数 *) List.length @@ self#roots
end

let n, m = Scanf.sscanf (read_line()) "%d %d" (fun n m -> n,m)
let tree = new union_find n
let _ = tree#init
let rec loop i =
  if i >= m then () else Scanf.sscanf (read_line()) "%d %d" (fun a b -> tree#unite a b; loop (i+1))

let () = loop 0
let rec get_next result =
  if result >= n then -1 else
  if tree#same 0 result then get_next (result+1) else result
let rec tree_loop result =
  let a, b = (0, get_next 0) in
    if b = -1 then result else
    (tree#unite a b; tree_loop (result+1))
let () = Printf.printf "%d\n" @@ tree_loop 0

Score : 300 points

Problem Statement

There are N cities numbered 1 through N, and M bidirectional roads numbered 1 through M.
Road i connects City A_i and City B_i.

Snuke can perform the following operation zero or more times:

Choose two distinct cities that are not directly connected by a road, and build a new road between the two cities.

After he finishes the operations, it must be possible to travel from any city to any other cities by following roads (possibly multiple times).

What is the minimum number of roads he must build to achieve the goal?

Constraints

2 \leq N \leq 100,000

1 \leq M \leq 100,000

1 \leq A_i < B_i \leq N

No two roads connect the same pair of cities.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

Print the answer.

Sample Input 1

3 1
1 2

Sample Output 1

1

Initially, there are three cities, and there is a road between City 1 and City 2.

Snuke can achieve the goal by building one new road, for example, between City 1 and City 3.
After that,

We can travel between 1 and 2 directly.

We can travel between 1 and 3 directly.

We can travel between 2 and 3 by following both roads (2 - 1 - 3).


open Batteries
class union_find n = object (self)
  val mutable par = ( [| |] : int array)
  method init =
    par <- Array.init n (fun a -> a)
  method get_par = par

  method root s =
    let rec loop x =
      if par.(x) = x then x else (par.(x) <- loop par.(x); par.(x))
    in loop s

  method rank s =
    let rec loop x n =
      if par.(x) = x then n else loop par.(x) (n+1)
    in loop s 1

  method unite x y =
    let xrank = self#rank x in
    let yrank = self#rank x in
    let rx = self#root x in
    let ry = self#root y in
    if rx != ry then (if xrank < yrank then par.(rx) <- ry else par.(ry) <- rx)

  method same x y = self#root x = self#root y

  method members x = (* 要素xが属する木の全ての要素を返す *)
    let r = self#root x in Array.fold_left (fun a y -> if self#root y = r then y :: a else a) [] par

  method roots = (* 全ての根 *) Array.fold_left (fun x y -> if List.mem y x then x else y :: x) [] par

  method tree_count = (* 木の数 *) List.length @@ self#roots
end

let n, m = Scanf.sscanf (read_line()) "%d %d" (fun n m -> n,m)
let tree = new union_find n
let _ = tree#init
let rec loop i =
  if i >= m then () else Scanf.sscanf (read_line()) "%d %d" (fun a b -> tree#unite a b; loop (i+1))

let () = loop 0
let rec tree_loop result =
  if tree#tree_count = 1 then result else (
    let a, b = (List.hd tree#roots, List.hd @@ List.tl tree#roots) in
    tree#unite a b; tree_loop (result+1)
  )
let () = Printf.printf "%d\n" @@ tree_loop 0


module type Segtree = sig
    type s
    type t

    val create   : int -> t
    val of_array : s array -> t
    val set      : t -> int -> s -> unit
    val get      : t -> int -> s
    val prod     : t -> int -> int -> s
    val all_prod : t -> s
end

module type SegtreeParam = sig
    type t

    val op : t -> t -> t
    val e  : t
end

module Segtree = struct
    module Make(STP: SegtreeParam) : Segtree with type s = STP.t = struct
        type t = int * int * int * STP.t array
        type s = STP.t

        let ceil_pow2 n =
            let rec loop x =
                if 1 lsl x < n then loop (x + 1) else x
            in
            loop 0

        let update d k =
            d.(k) <- STP.op d.(2 * k) d.(2 * k + 1)

        let of_array v =
            let n = Array.length v in
            let log = ceil_pow2 n in
            let size = 1 lsl log in
            let d = Array.make (2 * size) STP.e in
            for i = 0 to n - 1 do d.(size + i) <- v.(i) done;
            for i = size - 1 downto 1 do update d i done;
            n, size, log, d

        let create n =
            of_array (Array.make n STP.e)

        let set (n, size, log, d) p x =
            let p = p + size in
            d.(p) <- x;
            for i = 1 to log do update d (p lsr i) done

        let get (_, size, _, d) p = d.(p + size)

        let prod (n, size, log, d) l r =
            let rec loop l r sml smr =
                if l >= r then STP.op sml smr else
                    let sml, l = if l land 1 = 0 then sml, l else STP.op sml d.(l),     l + 1 in
                    let smr, r = if r land 1 = 0 then smr, r else STP.op d.(r - 1) smr, r - 1 in
                    loop (l lsr 1) (r lsr 1) sml smr
            in
            loop (l + size) (r + size) STP.e STP.e

        let all_prod (_, _, _, d) = d.(1)
    end
end;;
Scanf.scanf "%d %d" (fun n k ->
    let module ST = Segtree.Make (struct type t = int let op = max let e = 0 end) in

    let seg = ST.create 600001 in
    for i = 0 to n - 1 do
        Scanf.scanf " %d" (fun a ->
            let l = max 0 (a - k) in
            let r = min 600000 (a + k + 1) in
            let v = ST.prod seg l r in
            ST.set seg a (v + 1)
        )
    done;
    Printf.printf "%d\n" @@ ST.all_prod seg
)

Score : 400 points

Problem Statement

You are given a sequence A_1, A_2, ..., A_N and an integer K.

Print the maximum possible length of a sequence B that satisfies the following conditions:

B is a (not necessarily continuous) subsequence of A.

For each pair of adjacents elements of B, the absolute difference of the elements is at most K.

Constraints

1 \leq N \leq 300,000

0 \leq A_i \leq 300,000

0 \leq K \leq 300,000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1
A_2
:
A_N

Output

Print the answer.

Sample Input 1

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

Sample Output 1

7

For example, B = (1, 4, 3, 6, 9, 7, 4) satisfies the conditions.

It is a subsequence of A = (1, 5, 4, 3, 8, 6, 9, 7, 2, 4).

All of the absolute differences between two adjacent elements (|1-4|, |4-3|, |3-6|, |6-9|, |9-7|, |7-4|) are at most K = 3.


Scanf.scanf "%s" (fun s ->
    let n = String.length s in
    print_endline @@ if s.[n - 1] = 's' then s ^ "es" else s ^ "s"
)

Score : 100 points

Problem Statement

In the Kingdom of AtCoder, people use a language called Taknese, which uses lowercase English letters.

In Taknese, the plural form of a noun is spelled based on the following rules:

If a noun's singular form does not end with s, append s to the end of the singular form.

If a noun's singular form ends with s, append es to the end of the singular form.

You are given the singular form S of a Taknese noun. Output its plural form.

Constraints

S is a string of length 1 between 1000, inclusive.

S contains only lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

Print the plural form of the given Taknese word.

Sample Input 1

apple

Sample Output 1

apples

apple ends with e, so its plural form is apples.

Sample Input 2

bus

Sample Output 2

buses

bus ends with s, so its plural form is buses.

Sample Input 3

box

Sample Output 3

boxs


Scanf.scanf "%d" (fun n ->
    let rec loop_a a acc =
        let rec loop_b b acc =
            if a * b >= n then loop_a (a + 1) acc else
                loop_b (b + 1) (acc + 1)
        in
        if a >= n then acc else loop_b 1 acc
    in
    loop_a 1 0 |> Printf.printf "%d\n"
)

Score : 300 points

Problem Statement

Given is a positive integer N.
How many tuples (A,B,C) of positive integers satisfy A \times B + C = N?

Constraints

2 \leq N \leq 10^6

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer.

Sample Input 1

3

Sample Output 1

3

There are 3 tuples of integers that satisfy A \times B + C = 3: (A, B, C) = (1, 1, 2), (1, 2, 1), (2, 1, 1).

Sample Input 2

100

Sample Output 2

473

Sample Input 3

1000000

Sample Output 3

13969985


open Batteries
open Printf

let ($) g f x = g (f x)

let swap = Tuple2.swap

let s2i = int_of_string
let i2s = string_of_int
let s2f = float_of_string
let f2s = string_of_float
let f2i = int_of_float
let i2f = float_of_int

let c2a = int_of_char
let a2c = char_of_int

let c2i c = c2a c - 48
let i2c i = a2c (i + 48)

let c2s = String.of_char
let s2cl = String.to_list
let cl2s = String.of_list

let puts s = print_endline s
let putw ?yn:(yn=("Yes", "No")) b = puts (if b then fst yn else snd yn)
let puti i = puts @@ i2s i

module StaleList = struct
  include List

  let nmem x l = not @@ mem x l

  let len = length
  let size = length
  let nempty l = not @@ is_empty l

  let hdop l = if nempty l then Some (hd l) else None

  (* let taker = drop *)
  let takewh = take_while

  (* let dropr = take *)
  let dropwh = drop_while

  let split_by = span

  let chunk = ntake

  let foldl = fold_left
  let foldli = fold_lefti
  let foldr f z l = fold_right f l z
  let foldri f z l = fold_righti f l z

  let partition_to_map f l =
    foldr (fun x m -> Map.modify_opt (f x) (function
      | None -> Some [x]
      | Some [] -> Some [x]
      | Some vl -> Some (x::vl)) m) Map.empty l;;

  let scanl f z ls =
    let rec loop acl acc = function
      | [] -> rev acl
      | h::t ->
        let r = f acc h in
        loop (r::acl) r t
    in loop [] z ls

  let scanr f z ls =
    let rec loop acl acc = function
      | [] -> acl
      | h::t ->
        let r = f h acc in
        loop (r::acl) r t
    in loop [] z (rev ls)

  (* let scanli = scan_lefti *)
  (* let scanri = scan_righti *)

  let flatmap = concat_map

  let zipf = map2
  let zipfi = map2i

end

module L = StaleList

module StaleArray = struct
  include Array

  let nmem x l = not @@ mem x l

  let len = length
  let size = length
  let is_empty r = len r = 0
  let nempty r = len r > 0

  let take n r = left r n
  let taker n r = right r n

  let takeb x r =
    let l = len r in
    let rec loop i =
      if i >= l then r
      else if r.(i) = x then take i r
      else loop (i + 1)
    in loop 0

  (* let takewh = take_while *)

  let drop n r = tail r n
  let dropr n r = take ((len r) - n) r
  (* let dropwh = drop_while *)

  let index_of x r =
    let l = len r in
    let rec loop i =
      if i >= l then None
      else if r.(i) = x then Some i
      else loop (i + 1)
    in loop 0

  (* let split_by = span *)

  (* let chunk = ntake *)

  let foldl = fold_left
  let foldli = fold_lefti
  let foldr f z l = fold_right f l z
  let foldri f z l = fold_righti f l z

  (* let partition_to_map f l = *)
  (*   foldr (fun x m -> Map.modify_opt (f x) (function *)
  (*     | None -> Some [x]  *)
  (*     | Some [] -> Some [x]  *)
  (*     | Some vl -> Some (x::vl)) m) Map.empty l;; *)

  (* let scanl = scan_left *)
  (* let scanli = scan_lefti *)
  (* let scanr = scan_right *)
  (* let scanri = scan_righti *)

  let concat2 = append

  let flatmap (f : 'a -> 'b array) a =
    map f a |> enum |> L.of_enum |> concat

  let zipf = map2
  (* let zipfi = map2i *)

end

module A = StaleArray

module StaleString = struct
  include String

  let len = length

  let replace_chars = map
  let map = replace

  let maptol f s = L.map f (s2cl s)
  let maptoli f s = L.map f (s2cl s)

  let zipf f a b = L.zipf f (s2cl a) (s2cl b)
  let zipfi f a b = L.zipfi f (s2cl a) (s2cl b)

  let mkstr f sep ls =
    L.foldl (fun acc x -> acc ^ sep ^ (f x)) (f @@ L.hd ls) (List.tl ls)

end

module S = StaleString

let spsp s = S.split_on_char ' ' s

module StaleSortedSet = struct
  include Set

  module Make (Ord : Set.OrderedType) = struct
    include Set.Make(Ord)

    let nempty st = not @@ is_empty st
    let sing = singleton
    let nmem x st = not @@ mem x st

    let foldl f s z = fold (fun x a -> f a x) z s

    let size = cardinal
  end

  let nempty st = not @@ is_empty st
  let sing = singleton
  let nmem x st = not @@ mem x st

  let foldl f s z = fold (fun x a -> f a x) z s

  let size = cardinal
end

module Ss = StaleSortedSet

module StaleSortedMap  = struct
  include Map

  module Make (Ord : Map.OrderedType) = struct
    include Map.Make(Ord)

    let nempty st = not @@ is_empty st
    let sing = singleton
    let nmem x st = not @@ mem x st

    let get = find
    let get_or x d m = find_default d x m

    let size = cardinal
  end

  let nempty st = not @@ is_empty st
  let sing = singleton
  let nmem x st = not @@ mem x st

  let get = find
  let get_or x d m = find_default d x m

  let size = cardinal
end

module Ms = StaleSortedMap

module StaleRange = struct

  type t = Range of int * int

  let make lb ub = Range (lb, ub)

  let to_list r =
    let Range (lb, ub) = r in
    L.make (ub - lb) ((+) lb)

  let to_array r =
    let Range (lb, ub) = r in
      A.make (ub - lb) ((+) lb)

  let iter r f =
    let Range (lb, ub) = r in
    for i = lb to ub do f i done

  let iter2 r1 r2 f =
    let Range (lb1, ub1) = r1 and Range (lb2, ub2) = r2 in
      for i = lb1 to ub2 do
        for j = lb2 to ub2 do
          f i j
        done
      done
end

module R = StaleRange

let (---) lb ub = R.make lb ub
let (--^) lb ub = R.make lb (ub - 1)

module StaleGenericAlgorithms = struct

  let set_power ls =
    let rec loop ls pls =
      match ls with
      | [] -> pls
      | hd::tl -> loop tl (L.flatmap (fun p -> [p; hd::p]) pls)
    in loop ls [[]]

  let rec bsearch_max_int f lb ub =
    if lb >= ub then (if f lb then lb else (lb - 1))
    else (
      let m = (lb + ub) / 2 in
      if f m then bsearch_max_int f (m + 1) ub
      else bsearch_max_int f lb m
    )

  let partial_sum n ls =
    let rec loop s k = function
      | [] -> s
      | h::t ->
        if k >= n then s
        else loop (s + h) (k + 1) t
    in
    loop 0 0 ls

end

module Gal = StaleGenericAlgorithms

let rds () = read_line ()

let rdi () = s2i @@ rds ()

let rdhs () = spsp @@ rds ()
let rdhi () = rdhs () |> L.map s2i

let rdhf () = rdhs () |> L.map s2f

let rdf2 () = match rdhf () with
| a::b::_ -> (a, b)
| _ -> (0., 0.)

let rdf3 () = match rdhf () with
| a::b::c::_ -> (a, b, c)
| _ -> (0., 0., 0.)

let rdf4 () = match rdhf () with
| a::b::c::d::_ -> (a, b, c, d)
| _ -> (0., 0., 0., 0.)

let rds2 () = match rdhs () with
  | a::b::_ -> (a, b)
  | _ -> ("", "")

let rdi2 () = match rdhi () with
  | a::b::_ -> (a, b)
  | _ -> (0, 0)

let rdi3 () = match rdhi () with
| a::b::c::_ -> (a, b, c)
| _ -> (0, 0, 0)

let rdi4 () = match rdhi () with
| a::b::c::d::_ -> (a, b, c, d)
| _ -> (0, 0, 0, 0)

let rdi5 () = match rdhi () with
| a::b::c::d::e::_ -> (a, b, c, d, e)
| _ -> (0, 0, 0, 0, 0)

let rdv n rf =
  let rec loop n =
    if n <= 0 then []
    else (
      let s = rf () in
      s::(loop (n - 1))
    )
  in loop n

let rdvi n = rdv n rdi
let rdvi2 n = rdv n rdi2
let rdvi3 n = rdv n rdi3
let rdvi4 n = rdv n rdi4

let print_list aa =
  printf "[ "; aa |> L.iter (fun a -> printf "%d " a); puts "]"

let print_array aa =
  printf "[ "; aa |> A.iter (fun a -> printf "%d " a); puts "]"

let print_carray aa =
  printf "[ "; aa |> A.iter (fun a -> printf "%c " a); puts "]"

let print_matrix mat =
  puts "----";
  mat |> A.iter (fun r -> print_carray r);
  puts "----"

let _ =
  let a,b,c,d = rdi4 () in
  puti (max (a*c) (max (a*d) (max (b*c) (b*d))));
  ()

Score : 200 points

Problem Statement

Given are integers a,b,c and d.
If x and y are integers and a \leq x \leq b and c\leq y \leq d hold, what is the maximum possible value of x \times y?

Constraints

-10^9 \leq a \leq b \leq 10^9

-10^9 \leq c \leq d \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b c d

Output

Print the answer.

Sample Input 1

1 2 1 1

Sample Output 1

2

If x = 1 and y = 1 then x \times y = 1.
If x = 2 and y = 1 then x \times y = 2.
Therefore, the answer is 2.

Sample Input 2

3 5 -4 -2

Sample Output 2

-6

The answer can be negative.

Sample Input 3

-1000000000 0 -1000000000 0

Sample Output 3

1000000000000000000


let () =
  Scanf.scanf "%d\n" @@ fun n ->
  let rec powmod x y ans =
  	if y = 0 then ans else powmod x (y-1) (ans * x mod 1000000007) in
  Printf.printf "%d\n" ((powmod 10 n 1) - 2 * (powmod 9 n 1) + (powmod 8 n 1))

Score : 300 points

Problem Statement

How many integer sequences A_1,A_2,\ldots,A_N of length N satisfy all of the following conditions?

0 \leq A_i \leq 9

There exists some i such that A_i=0 holds.

There exists some i such that A_i=9 holds.

The answer can be very large, so output it modulo 10^9 + 7.

Constraints

1 \leq N \leq 10^6

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer modulo 10^9 + 7.

Sample Input 1

2

Sample Output 1

2

Two sequences \{0,9\} and \{9,0\} satisfy all conditions.

Sample Input 2

1

Sample Output 2

0

Sample Input 3

869121

Sample Output 3

2511445


let rec power ( * ) e m n =
  if n <= 0 then e
  else power ( * ) (if n land 1 = 0 then e else m * e) (m * m) (n lsr 1)

let m = 1000000007
let ( +^ ) x y = (x + y) mod m
let ( -^ ) x y = x +^ (m - y)
let ( *^ ) x y = (x * y) mod m
let perm n k =
  Array.fold_left ( *^ ) 1 @@
  Array.init k @@ ( + ) (n - k + 1)

let () =
  let n = read_int () in
  Printf.printf "%d\n" @@
  power ( *^ ) 1 10 n -^ 2 *^ power ( *^ ) 1 9 n +^ power ( *^ ) 1 8 n


Scanf.scanf "%d" (fun n ->
    let z = 1_000_000_007 in
    let ( +@) a b = (a + b) mod z in
    let ( *@) a b = (a * b) mod z in

    let rec loop i d09 d0 d9 dn =
        if i = n then d09 else
            loop (i + 1) (d09 *@ 10 +@ d0 +@ d9) (d0 *@ 9 +@ dn) (d9 *@ 9 +@ dn) (dn *@ 8)
    in
    loop 0 0 0 0 1 |> Printf.printf "%d\n"
)


module Dsu : sig
    type t

    val make   : int -> t
    val merge  : t -> int -> int -> int
    val same   : t -> int -> int -> bool
    val leader : t -> int -> int
    val size   : t -> int -> int
end = struct
    type t = int * int array

    let make n =
        n, Array.make n (-1)

    let rec leader ((n, parent_or_size) as dsu) a =
        if parent_or_size.(a) < 0 then a else
            let r = leader dsu parent_or_size.(a) in
            let () = parent_or_size.(a) <- r in
            r

    let merge ((n, parent_or_size) as dsu) a b =
        let x = leader dsu a in
        let y = leader dsu b in
        if x = y then x else (
            let x, y = if -parent_or_size.(x) < -parent_or_size.(y) then y, x else x, y in
            parent_or_size.(x) <- parent_or_size.(x) + parent_or_size.(y);
            parent_or_size.(y) <- x;
            x
        )

    let same dsu a b =
        leader dsu a = leader dsu b

    let size ((n, parent_or_size) as dsu) a =
        -parent_or_size.(leader dsu a)
end;;

Scanf.scanf "%d %d" (fun n q ->
    let dsu = Dsu.make n in
    for i = 1 to q do
        Scanf.scanf " %d %d %d" (fun t u v ->
            if t = 0 then ignore (Dsu.merge dsu u v) else
                Printf.printf "%d\n" @@ if Dsu.same dsu u v then 1 else 0
        )
    done
)

Score : 100 points

Problem Statement

You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types.

0 u v: Add an edge (u, v).

1 u v: Print 1 if u and v are in the same connected component, 0 otherwise.

Constraints

1 \leq N \leq 200,000

1 \leq Q \leq 200,000

0 \leq u_i, v_i \lt N

Input

Input is given from Standard Input in the following format:

N Q
t_1 u_1 v_1
t_2 u_2 v_2
:
t_Q u_Q v_Q

出力

For each query of the latter type, print the answer.

Sample Input 1

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

Sample Output 1

0
1
0
1


module type CapType = sig
    type t
    val zero : t
    val cap_max : t
    val add : t -> t -> t
    val sub : t -> t -> t
    val to_int : t -> int
end ;;

module CapInt : CapType with type t = int = struct
    type t = int
    let zero = 0
    let cap_max = max_int
    let add = (+)
    let sub = (-)
    let to_int a = a
end

module type S = sig
    type t
    type cap

    val create : int -> int -> t
    val add_edge : t -> int -> int -> cap -> t
    val edges    : t -> (int * int * cap * cap) array
    val get_edge : t -> int -> int * int * cap * cap
    val flow     : t -> int -> int -> cap
end;;

module Mf_graph = struct
    module Make(Cap: CapType) : S with type cap = Cap.t = struct
        type cap = Cap.t

        type edge = { to_: int; rev: int; mutable cap : cap }
        type t = int * int * int list array * edge array

        let create n m =
            n, 0, Array.make n [], Array.init (m * 2) (fun _ -> { to_ = 0; rev = 0; cap = Cap.zero } )

        let get_edge (n, idx, g, pos) i =
            let _e = pos.(i * 2) in
            let _re = pos.(_e.rev) in
            _re.to_, _e.to_, Cap.add _e.cap _re.cap, _re.cap

        let edges ((n, idx, g, pos) as mf) =
            Array.init (idx / 2) (fun i -> get_edge mf i)

        let add_edge (n, idx, g, pos) from to_ cap =
            pos.(idx)     <- { to_ = to_;  rev = idx + 1; cap = cap  };
            pos.(idx + 1) <- { to_ = from; rev = idx;     cap = Cap.zero };
            g.(from) <- idx :: g.(from);
            g.(to_)  <- (idx + 1) :: g.(to_);
            n, idx + 2, g, pos

        let flow mf s t =
            let flow (n, idx, g, pos) s t flow_limit =
                let g = Array.map List.rev g in
                let rec bfs () =
                    let level = Array.make n (-1) in
                    level.(s) <- 0;

                    let rec loop fq bq =
                        match fq with
                        | [] -> if bq = [] then level else loop (List.rev bq) []
                        | v :: vs -> (
                            let rec loop2 bq = function
                                | [] -> loop vs bq
                                | e :: es ->
                                        let e = pos.(e) in
                                        if e.cap = Cap.zero || level.(e.to_) >= 0 then loop2 bq es else (
                                            level.(e.to_) <- level.(v) + 1;
                                            if e.to_ = t then level else loop2 (e.to_ :: bq) es
                                        )
                            in
                            loop2 bq g.(v)
                        )
                    in
                    loop [ s ] []
                in
                let rec dfs level iter v up =
                    if v = s then up else
                        let level_v = level.(v) in
                        let rec loop res iis =
                            iter.(v) <- iis;
                            match iis with
                            | [] -> res
                            | i :: is ->
                                let e = pos.(i) in
                                if level_v <= level.(e.to_) || pos.(e.rev).cap = Cap.zero then loop res is else
                                    let d = dfs level iter e.to_ (min (Cap.sub up res) pos.(e.rev).cap) in
                                    if d <= Cap.zero then loop res is else (
                                        pos.(i).cap     <- Cap.add pos.(i).cap d;
                                        pos.(e.rev).cap <- Cap.sub pos.(e.rev).cap d;
                                        let res = Cap.add res d in
                                        if res = up then res else loop res is
                                    )
                        in
                        loop Cap.zero iter.(v)
                in
                let rec flow_loop flow =
                    if flow >= flow_limit then flow else
                        let level = bfs () in
                        if level.(t) = -1 then flow else
                            let iter = Array.copy g in
                            let rec loop flow =
                                if flow < flow_limit then (
                                    let f = dfs level iter t (Cap.sub flow_limit flow) in
                                    if f = Cap.zero then flow else
                                        loop (Cap.add flow f)
                                ) else flow
                            in
                            loop flow
                in
                flow_loop Cap.zero

            in
            flow mf s t Cap.cap_max
    end
end;;

Scanf.scanf "%d %d" (fun n m ->
    let ss = Array.init n (fun _ -> Scanf.scanf " %s" (fun s -> s)) in

    let module MF = Mf_graph.Make (CapInt) in
    let mf = MF.create (n * m + 2) (n * m * 3) in
    let s = n * m in
    let t = n * m + 1 in
    let rec loop_y y mf =
        let rec loop_x x mf =
            if x = m then loop_y (y + 1) mf else
                let pivot = y * m + x in
                let mf = if ss.(y).[x] = '#' then mf else (
                    if (x + y) mod 2 <> 0 then MF.add_edge mf pivot t 1 else (
                        let mf = MF.add_edge mf s pivot 1 in
                        let mf = if y > 0     && ss.(y - 1).[x] = '.' then MF.add_edge mf pivot ((y - 1) * m + x) 1 else mf in
                        let mf = if y < n - 1 && ss.(y + 1).[x] = '.' then MF.add_edge mf pivot ((y + 1) * m + x) 1 else mf in
                        let mf = if x > 0     && ss.(y).[x - 1] = '.' then MF.add_edge mf pivot (y * m + x - 1)   1 else mf in
                        let mf = if x < m - 1 && ss.(y).[x + 1] = '.' then MF.add_edge mf pivot (y * m + x + 1)   1 else mf in
                        mf
                    )
                )
                in
                loop_x (x + 1) mf
        in
        if y = n then mf else loop_x 0 mf
    in
    let mf = loop_y 0 mf in
    let f = MF.flow mf s t in
    let ar = MF.edges mf in
    let map = Array.make_matrix n m ' ' in
    for y = 0 to n - 1 do
        for x = 0 to m - 1 do
            map.(y).(x) <- ss.(y).[x]
        done
    done;
    Array.iter (fun (from, to_, c1, c2) -> if c2 > 0 && from <> s && to_ <> t then (
        let prt p1 c1 p2 c2 =
            let prt2 p c =
                let y = p / m in
                let x = p mod m in
                map.(y).(x) <- c
            in
            prt2 p1 c1; prt2 p2 c2
        in
        if from + m = to_  then prt from 'v' to_ '^' else
        if to_  + m = from then prt from '^' to_ 'v' else
        if from + 1 = to_  then prt from '>' to_ '<' else
        if to_  + 1 = from then prt from '<' to_ '>'
    )) ar;
    Printf.printf "%d\n" f;
    for y = 0 to n - 1 do
        for x = 0 to m - 1 do
            print_char map.(y).(x)
        done;
        print_newline ()
    done
)

Score : 100 points

Problem Statement

You are given a grid of N rows and M columns. The square at the i-th row and j-th column will be denoted as (i,j).
Some of the squares contain an object. All the remaining squares are empty.
The state of the grid is represented by strings S_1,S_2,\cdots,S_N. The square (i,j) contains an object if S_{i,j}= # and is empty if S_{i,j}= ..

Consider placing 1 \times 2 tiles on the grid. Tiles can be placed vertically or horizontally to cover two adjacent empty squares.
Tiles must not stick out of the grid, and no two different tiles may intersect. Tiles cannot occupy the square with an object.

Calculate the maximum number of tiles that can be placed and any configulation that acheives the maximum.

Constraints

1 \leq N \leq 100

1 \leq M \leq 100

S_i is a string with length M consists of # and ..

Input

Input is given from Standard Input in the following format:

N M
S_1
S_2
\vdots
S_N

Output

On the first line, print the maximum number of tiles that can be placed.

On the next N lines, print a configulation that achieves the maximum.
Precisely, output the strings t_1,t_2,\cdots,t_N constructed by the following way.

t_i is initialized to S_i.

For each (i,j), if there is a tile that occupies (i,j) and (i+1,j), change t_{i,j}:=v, t_{i+1,j}:=^.

For each (i,j), if there is a tile that occupies (i,j) and (i,j+1), change t_{i,j}:=>, t_{i,j+1}:=<.

See samples for further information.

You may print any configulation that maximizes the number of tiles.

Sample Input 1

3 3
#..
..#
...

Sample Output 1

3
#><
vv#
^^.

The following output is also treated as a correct answer.

3
#><
v.#
^><


open Core;;

let (d, t, s) = Scanf.scanf "%d %d %d" Tuple3.create in
printf "%s\n" (if d <= t * s then "Yes" else "No")
;;

Score : 100 points

Problem Statement

Takahashi is meeting up with Aoki.

They have planned to meet at a place that is D meters away from Takahashi's house in T minutes from now.

Takahashi will leave his house now and go straight to the place at a speed of S meters per minute.

Will he arrive in time?

Constraints

1 \leq D \leq 10000

1 \leq T \leq 10000

1 \leq S \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

D T S

Output

If Takahashi will reach the place in time, print Yes; otherwise, print No.

Sample Input 1

1000 15 80

Sample Output 1

Yes

It takes 12.5 minutes to go 1000 meters to the place at a speed of 80 meters per minute. They have planned to meet in 15 minutes so he will arrive in time.

Sample Input 2

2000 20 100

Sample Output 2

Yes

It takes 20 minutes to go 2000 meters to the place at a speed of 100 meters per minute. They have planned to meet in 20 minutes so he will arrive just on time.

Sample Input 3

10000 1 1

Sample Output 3

No

He will be late.


let () =
  Scanf.scanf "%d %d %d\n" @@ fun d t s ->
  Printf.printf "%s\n" (if d <= t * s then "Yes" else "No")


open Batteries
open Printf

let ($) g f x = g (f x)

let swap = Tuple2.swap

let s2i = int_of_string
let i2s = string_of_int
let s2f = float_of_string
let f2s = string_of_float
let f2i = int_of_float
let i2f = float_of_int

let c2a = int_of_char
let a2c = char_of_int

let c2i c = c2a c - 48
let i2c i = a2c (i + 48)

let c2s = String.of_char
let s2cl = String.to_list
let cl2s = String.of_list

let puts s = print_endline s
let putw ?yn:(yn=("Yes", "No")) b = puts (if b then fst yn else snd yn)
let puti i = puts @@ i2s i

module StaleList = struct
  include List

  let nmem x l = not @@ mem x l

  let len = length
  let size = length
  let nempty l = not @@ is_empty l

  let hdop l = if nempty l then Some (hd l) else None

  (* let taker = drop *)
  let takewh = take_while

  (* let dropr = take *)
  let dropwh = drop_while

  let split_by = span

  let chunk = ntake

  let foldl = fold_left
  let foldli = fold_lefti
  let foldr f z l = fold_right f l z
  let foldri f z l = fold_righti f l z

  let partition_to_map f l =
    foldr (fun x m -> Map.modify_opt (f x) (function
      | None -> Some [x]
      | Some [] -> Some [x]
      | Some vl -> Some (x::vl)) m) Map.empty l;;

  let scanl f z ls =
    let rec loop acl acc = function
      | [] -> rev acl
      | h::t ->
        let r = f acc h in
        loop (r::acl) r t
    in loop [] z ls

  let scanr f z ls =
    let rec loop acl acc = function
      | [] -> acl
      | h::t ->
        let r = f h acc in
        loop (r::acl) r t
    in loop [] z (rev ls)

  (* let scanli = scan_lefti *)
  (* let scanri = scan_righti *)

  let flatmap = concat_map

  let zipf = map2
  let zipfi = map2i

end

module L = StaleList

module StaleArray = struct
  include Array

  let nmem x l = not @@ mem x l

  let len = length
  let size = length
  let is_empty r = len r = 0
  let nempty r = len r > 0

  let take n r = left r n
  let taker n r = right r n

  let takeb x r =
    let l = len r in
    let rec loop i =
      if i >= l then r
      else if r.(i) = x then take i r
      else loop (i + 1)
    in loop 0

  (* let takewh = take_while *)

  let drop n r = tail r n
  let dropr n r = take ((len r) - n) r
  (* let dropwh = drop_while *)

  let index_of x r =
    let l = len r in
    let rec loop i =
      if i >= l then None
      else if r.(i) = x then Some i
      else loop (i + 1)
    in loop 0

  (* let split_by = span *)

  (* let chunk = ntake *)

  let foldl = fold_left
  let foldli = fold_lefti
  let foldr f z l = fold_right f l z
  let foldri f z l = fold_righti f l z

  (* let partition_to_map f l = *)
  (*   foldr (fun x m -> Map.modify_opt (f x) (function *)
  (*     | None -> Some [x]  *)
  (*     | Some [] -> Some [x]  *)
  (*     | Some vl -> Some (x::vl)) m) Map.empty l;; *)

  (* let scanl = scan_left *)
  (* let scanli = scan_lefti *)
  (* let scanr = scan_right *)
  (* let scanri = scan_righti *)

  let concat2 = append

  let flatmap (f : 'a -> 'b array) a =
    map f a |> enum |> L.of_enum |> concat

  let zipf = map2
  (* let zipfi = map2i *)

end

module A = StaleArray

module StaleString = struct
  include String

  let len = length

  let replace_chars = map
  let map = replace

  let maptol f s = L.map f (s2cl s)
  let maptoli f s = L.map f (s2cl s)

  let zipf f a b = L.zipf f (s2cl a) (s2cl b)
  let zipfi f a b = L.zipfi f (s2cl a) (s2cl b)

  let mkstr f sep ls =
    L.foldl (fun acc x -> acc ^ sep ^ (f x)) (f @@ L.hd ls) (List.tl ls)

end

module S = StaleString

let spsp s = S.split_on_char ' ' s

module StaleSortedSet = struct
  include Set

  module Make (Ord : Set.OrderedType) = struct
    include Set.Make(Ord)

    let nmem x st = not @@ mem x st

    let foldl f s z = fold (fun x a -> f a x) z s

    let size = cardinal
  end

  let nmem x st = not @@ mem x st

  let foldl f s z = fold (fun x a -> f a x) z s

  let size = cardinal
end

module Ss = StaleSortedSet

module StaleSortedMap  = struct
  include Map

  module Make (Ord : Map.OrderedType) = struct
    include Map.Make(Ord)

    let nmem x st = not @@ mem x st

    let get = find
    let get_or x d m = find_default d x m

    let size = cardinal
  end

  let nmem x st = not @@ mem x st

  let get = find
  let get_or x d m = find_default d x m

  let size = cardinal
end

module Ms = StaleSortedMap

module StaleRange = struct

  type t = Range of int * int

  let make lb ub = Range (lb, ub)

  let to_list r =
    let Range (lb, ub) = r in
    L.make (ub - lb) ((+) lb)

  let to_array r =
    let Range (lb, ub) = r in
      A.make (ub - lb) ((+) lb)

  let iter r f =
    let Range (lb, ub) = r in
    for i = lb to ub do f i done

  let iter2 r1 r2 f =
    let Range (lb1, ub1) = r1 and Range (lb2, ub2) = r2 in
      for i = lb1 to ub2 do
        for j = lb2 to ub2 do
          f i j
        done
      done
end

module R = StaleRange

let (---) lb ub = R.make lb ub
let (--^) lb ub = R.make lb (ub - 1)

module StaleGenericAlgorithms = struct

  let set_power ls =
    let rec loop ls pls =
      match ls with
      | [] -> pls
      | hd::tl -> loop tl (L.flatmap (fun p -> [p; hd::p]) pls)
    in loop ls [[]]

  let rec bsearch_max_int f lb ub =
    if lb >= ub then (if f lb then lb else (lb - 1))
    else (
      let m = (lb + ub) / 2 in
      if f m then bsearch_max_int f (m + 1) ub
      else bsearch_max_int f lb m
    )

  let partial_sum n ls =
    let rec loop s k = function
      | [] -> s
      | h::t ->
        if k >= n then s
        else loop (s + h) (k + 1) t
    in
    loop 0 0 ls

end

module Gal = StaleGenericAlgorithms

let rds () = read_line ()

let rdi () = s2i @@ rds ()

let rdhs () = spsp @@ rds ()
let rdhi () = rdhs () |> L.map s2i

let rdhf () = rdhs () |> L.map s2f

let rdf2 () = match rdhf () with
| a::b::_ -> (a, b)
| _ -> (0., 0.)

let rdf3 () = match rdhf () with
| a::b::c::_ -> (a, b, c)
| _ -> (0., 0., 0.)

let rdf4 () = match rdhf () with
| a::b::c::d::_ -> (a, b, c, d)
| _ -> (0., 0., 0., 0.)

let rds2 () = match rdhs () with
  | a::b::_ -> (a, b)
  | _ -> ("", "")

let rdi2 () = match rdhi () with
  | a::b::_ -> (a, b)
  | _ -> (0, 0)

let rdi3 () = match rdhi () with
| a::b::c::_ -> (a, b, c)
| _ -> (0, 0, 0)

let rdi4 () = match rdhi () with
| a::b::c::d::_ -> (a, b, c, d)
| _ -> (0, 0, 0, 0)

let rdi5 () = match rdhi () with
| a::b::c::d::e::_ -> (a, b, c, d, e)
| _ -> (0, 0, 0, 0, 0)

let rdv n rf =
  let rec loop n =
    if n <= 0 then []
    else (
      let s = rf () in
      s::(loop (n - 1))
    )
  in loop n

let rdvi n = rdv n rdi
let rdvi2 n = rdv n rdi2
let rdvi3 n = rdv n rdi3
let rdvi4 n = rdv n rdi4

let print_list aa =
  printf "[ "; aa |> L.iter (fun a -> printf "%d " a); puts "]"

let print_array aa =
  printf "[ "; aa |> A.iter (fun a -> printf "%d " a); puts "]"

let print_carray aa =
  printf "[ "; aa |> A.iter (fun a -> printf "%c " a); puts "]"

let print_matrix mat =
  puts "----";
  mat |> A.iter (fun r -> print_carray r);
  puts "----"

let _ =
  let s = s2cl @@ rds () and t = s2cl @@ rds () in
  let len = L.len t in

  let rec diff s1 s2 = L.len @@ L.filter (fun x -> x) @@ L.zipf (<>) s1 s2 in

  let rec min_diff m sl =
    if L.len sl < len then m
    else
      let d = diff t (L.take len sl) in
      if d < m then min_diff d (L.tl sl) else min_diff m (L.tl sl)
  in

  puti @@ min_diff 10000 s

Score : 200 points

Problem Statement

Given are two strings S and T.

Let us change some of the characters in S so that T will be a substring of S.

At least how many characters do we need to change?

Here, a substring is a consecutive subsequence. For example, xxx is a substring of yxxxy, but not a substring of xxyxx.

Constraints

The lengths of S and T are each at least 1 and at most 1000.

The length of T is at most that of S.

S and T consist of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S
T

Output

Print the minimum number of characters in S that need to be changed.

Sample Input 1

cabacc
abc

Sample Output 1

1

For example, changing the fourth character a in S to c will match the second through fourth characters in S to T.

Since S itself does not have T as its substring, this number of changes - one - is the minimum needed.

Sample Input 2

codeforces
atcoder

Sample Output 2

6


let () =
  let rec charlist_of_string str n i =
    if i = n then [] else str.[i] :: charlist_of_string str n (i+1) in
  Scanf.scanf "%s\n%s\n" @@ fun s t ->
  let slst = charlist_of_string s (String.length s) 0 in
  let tlst = charlist_of_string t (String.length t) 0 in
  let ans = ref max_int in
  let rec check lst1 lst2 ans = match lst1, lst2 with
    | [], [] -> ans
    | _,  [] -> raise Not_found
    | [], _  -> raise Not_found
    | h1 :: t1, h2 :: t2 -> if h1 = h2 then check t1 t2 ans else check t1 t2 (ans + 1) in
  for start = 0 to (String.length s) - (String.length t) - 1 do
    let buf = check (Array.to_list (Array.sub (Array.of_list slst) start (String.length t))) tlst 0 in
    if buf < !ans then ans := buf
  done;
  Printf.printf "%d\n" !ans


let () = Scanf.scanf "%d %d\n" @@ fun h w ->
  let as_ = Array.make h 0 in
  let bs = Array.make h 0 in
  for i = 0 to h - 1 do
    Scanf.scanf "%d %d\n" @@ fun a b ->
      as_.(i) <- a;
      bs.(i) <- b
  done;
  let dp = Array.make (h + 1) 1 in
  for i = 0 to h - 1 do
    dp.(i + 1) <- if dp.(i) < as_.(i) then dp.(i) else bs.(i) + 1
  done;
  let dp' = Array.make (h + 1) w in
  for i = h - 1 downto 0 do
    dp'.(i) <- if bs.(i) < dp.(i + 1) then dp.(i + 1) else as_.(i) - 1
  done;
  for i = 1 to h do
    Printf.printf "%d\n" @@
    if w < dp.(i)
    then -1
    else i + min (dp.(i) - 1) (dp'.(i) - dp'.(0))
  done

Score : 600 points

Problem Statement

There is a grid of squares with H+1 horizontal rows and W vertical columns.

You will start at one of the squares in the top row and repeat moving one square right or down. However, for each integer i from 1 through H, you cannot move down from the A_i-th, (A_i + 1)-th, \ldots, B_i-th squares from the left in the i-th row from the top.

For each integer k from 1 through H, find the minimum number of moves needed to reach one of the squares in the (k+1)-th row from the top. (The starting square can be chosen individually for each case.) If, starting from any square in the top row, none of the squares in the (k+1)-th row can be reached, print -1 instead.

Constraints

1 \leq H,W \leq 2\times 10^5

1 \leq A_i \leq B_i \leq W

Input

Input is given from Standard Input in the following format:

H W
A_1 B_1
A_2 B_2
:
A_H B_H

Output

Print H lines. The i-th line should contain the answer for the case k=i.

Sample Input 1

4 4
2 4
1 1
2 3
2 4

Sample Output 1

1
3
6
-1

Let (i,j) denote the square at the i-th row from the top and j-th column from the left.

For k=1, we need one move such as (1,1) → (2,1).

For k=2, we need three moves such as (1,1) → (2,1) → (2,2) → (3,2).

For k=3, we need six moves such as (1,1) → (2,1) → (2,2) → (3,2) → (3,3) → (3,4) → (4,4).

For k=4, it is impossible to reach any square in the fifth row from the top.


let () =
  Scanf.scanf "%d %d %d\n" @@ fun n x t ->
  Printf.printf "%d\n" (if n mod x = 0 then t * (n / x) else t * (n / x + 1))

Score : 100 points

Problem Statement

Takahashi loves takoyaki - a ball-shaped snack.

With a takoyaki machine, he can make at most X pieces of takoyaki at a time, taking T minutes regardless of the number of pieces to make.

How long does it take to make N takoyaki?

Constraints

1 \leq N,X,T \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X T

Output

Print an integer representing the minimum number of minutes needed to make N pieces of takoyaki.

Sample Input 1

20 12 6

Sample Output 1

12

He can make 12 pieces of takoyaki in the first 6 minutes and 8 more in the next 6 minutes, so he can make 20 in a total of 12 minutes.

Note that being able to make 12 in 6 minutes does not mean he can make 2 in 1 minute.

Sample Input 2

1000 1 1000

Sample Output 2

1000000

It seems to take a long time to make this kind of takoyaki.


let () =
  let rec solve n ans =
    if n / 10 = 0 then ans+n else solve (n / 10) (ans + (n mod 10)) in
  Scanf.scanf "%d\n" @@ fun n ->
  Printf.printf "%s\n" (if (solve n 0) mod 9 = 0 then "Yes" else "No")

Score : 200 points

Problem Statement

An integer N is a multiple of 9 if and only if the sum of the digits in the decimal representation of N is a multiple of 9.

Determine whether N is a multiple of 9.

Constraints

0 \leq N < 10^{200000}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If N is a multiple of 9, print Yes; otherwise, print No.

Sample Input 1

123456789

Sample Output 1

Yes

The sum of these digits is 1+2+3+4+5+6+7+8+9=45, which is a multiple of 9, so 123456789 is a multiple of 9.

Sample Input 2

0

Sample Output 2

Yes

Sample Input 3

31415926535897932384626433832795028841971693993751058209749445923078164062862089986280

Sample Output 3

No


open Printf
open Scanf

let solve n =
  let aa = Array.init n @@ fun _ -> scanf "%d " @@ fun x -> x in
  let f (tc, mh) a = if mh <= a then (tc, a) else (tc + mh - a, mh) in
  fst @@ Array.fold_left f (0, 0) aa

let () =
  scanf "%d " solve |> printf "%d\n"

Score : 300 points

Problem Statement

N persons are standing in a row. The height of the i-th person from the front is A_i.

We want to have each person stand on a stool of some heights - at least zero - so that the following condition is satisfied for every person:

Condition: Nobody in front of the person is taller than the person. Here, the height of a person includes the stool.

Find the minimum total height of the stools needed to meet this goal.

Constraints

1 \leq N \leq 2\times 10^5

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print the minimum total height of the stools needed to meet the goal.

Sample Input 1

5
2 1 5 4 3

Sample Output 1

4

If the persons stand on stools of heights 0, 1, 0, 1, and 2, respectively, their heights will be 2, 2, 5, 5, and 5, satisfying the condition.

We cannot meet the goal with a smaller total height of the stools.

Sample Input 2

5
3 3 3 3 3

Sample Output 2

0

Giving a stool of height 0 to everyone will work.


let readNInt () =
  let temp = read_line () in
  let digits = String.split_on_char ' ' temp in
  List.map int_of_string digits

let rec findDifSum acc l =
  match l with
    [] -> acc
  | a :: [] -> acc
  | a :: b :: rest ->
     if a > b
     then (findDifSum (a - b + acc) rest)
     else (findDifSum acc rest)

let main () =
  let _ = read_int () in
  let l = readNInt () in
  let sum = findDifSum 0 (List.rev l) in
  (
    print_int sum;
    print_newline ()
  )

let _ = main ()


Scanf.scanf "%d" (fun n ->
    let a = Array.init n (fun _ -> Scanf.scanf " %d" (fun a -> a)) in

    let rec loop i prev acc =
        if i = n then acc else
            if a.(i) >= prev then loop (i + 1) a.(i) acc else
                let d = prev - a.(i) in
                loop (i + 1) prev (acc + d)
    in
    loop 0 0 0 |> Printf.printf "%d\n"
)


Scanf.scanf "%d" (fun n ->
    let n3 = 3 * n in
    let a = Array.init n3 (fun _ -> Scanf.scanf " %d" (fun a -> a - 1)) in
    let m = 100000 in
    let make_key a b = if a < b then a * m + b else b * m + a in
    let module M = Map.Make (struct type t = int let compare = compare end) in

    let add a b c d e v newmap =
        let key = make_key a b in
        let v = if c = d && d = e then v + 1 else v in
        M.add key (max v (try M.find key newmap with _ -> 0)) newmap
    in

    let rec loop i map =
        if i = n3 - 1 then map else
            let k3 = a.(i) in
            let k4 = a.(i + 1) in
            let k5 = a.(i + 2) in
            let newmap = M.fold (fun key v newmap ->
                let k1 = key / m in
                let k2 = key mod m in
                let newmap = add k1 k2 k3 k4 k5 v newmap in
                let newmap = add k1 k3 k2 k4 k5 v newmap in
                let newmap = add k1 k4 k2 k3 k5 v newmap in
                let newmap = add k1 k5 k2 k3 k4 v newmap in
                let newmap = add k2 k3 k1 k4 k5 v newmap in
                let newmap = add k2 k4 k1 k3 k5 v newmap in
                let newmap = add k2 k5 k1 k3 k4 v newmap in
                let newmap = add k3 k4 k1 k2 k5 v newmap in
                let newmap = add k3 k5 k1 k2 k4 v newmap in
                let newmap = add k4 k5 k1 k2 k5 v newmap in
                newmap
            ) map M.empty in
            loop (i + 3) newmap
    in
    let map = loop 2 (M.singleton (make_key a.(0) a.(1)) 0) in
    M.fold (fun key v acc ->
        let k1 = key / m in
        let k2 = key mod m in
        let v = if k1 = k2 && k2 = a.(n3 - 1) then v + 1 else v in
        max acc v
    ) map 0 |> Printf.printf "%d\n"
)

Score : 600 points

Problem Statement

We have 3N cards arranged in a row from left to right, where each card has an integer between 1 and N (inclusive) written on it. The integer written on the i-th card from the left is A_i.

You will do the following operation N-1 times:

Rearrange the five leftmost cards in any order you like, then remove the three leftmost cards. If the integers written on those three cards are all equal, you gain 1 point.

After these N-1 operations, if the integers written on the remaining three cards are all equal, you will gain 1 additional point.

Find the maximum number of points you can gain.

Constraints

1 \leq N \leq 2000

1 \leq A_i \leq N

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_{3N}

Output

Print the maximum number of points you can gain.

Sample Input 1

2
1 2 1 2 2 1

Sample Output 1

2

Let us rearrange the five leftmost cards so that the integers written on the six cards will be 2\ 2\ 2\ 1\ 1\ 1 from left to right.

Then, remove the three leftmost cards, all of which have the same integer 2, gaining 1 point.

Now, the integers written on the remaining cards are 1\ 1\ 1.

Since these three cards have the same integer 1, we gain 1 more point.

In this way, we can gain 2 points - which is the maximum possible.

Sample Input 2

3
1 1 2 2 3 3 3 2 1

Sample Output 2

1

Sample Input 3

3
1 1 2 2 2 3 3 3 1

Sample Output 3

3


Score : 100 points

Problem Statement

We have weather records at AtCoder Town for some consecutive three days. A string of length 3, S, represents the records - if the i-th character is S, it means it was sunny on the i-th day; if that character is R, it means it was rainy on that day.

Find the maximum number of consecutive rainy days in this period.

Constraints

|S| = 3

Each character of S is S or R.

Input

Input is given from Standard Input in the following format:

S

Output

Print the maximum number of consecutive rainy days in the period.

Sample Input 1

RRS

Sample Output 1

2

We had rain on the 1-st and 2-nd days in the period. Here, the maximum number of consecutive rainy days is 2, so we should print 2.

Sample Input 2

SSS

Sample Output 2

0

It was sunny throughout the period. We had no rainy days, so we should print 0.

Sample Input 3

RSR

Sample Output 3

1

We had rain on the 1-st and 3-rd days - two "streaks" of one rainy day, so we should print 1.


(*
ocamlfind ocamlopt -package batteries -linkpkg main.ml -o a.out
*)
open Batteries

let ans =
        Str.split (Str.regexp "S") (read_line ())
        |> List.map (fun str -> String.length str)
        |> List.max

let () = Printf.printf "%d" ans


let () =
  Scanf.scanf "%d\n" @@ fun n ->
  let arr = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun d -> d in
  let _ = Array.fast_sort compare arr in
  let ans = ref 0 in
  for i = 0 to Array.length arr - 1 do
    for j = i + 1 to Array.length arr - 1 do
      for k = j + 1 to Array.length arr - 1 do
        if arr.(i) + arr.(j) > arr.(k) then ans := !ans + 1
      done;
    done;
  done;
  Printf.printf "%d\n" !ans

Score : 200 points

Problem Statement

We have sticks numbered 1, \cdots, N. The length of Stick i (1 \leq i \leq N) is L_i.

In how many ways can we choose three of the sticks with different lengths that can form a triangle?

That is, find the number of triples of integers (i, j, k) (1 \leq i < j < k \leq N) that satisfy both of the following conditions:

L_i, L_j, and L_k are all different.

There exists a triangle whose sides have lengths L_i, L_j, and L_k.

Constraints

1 \leq N \leq 100

1 \leq L_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
L_1 L_2 \cdots L_N

Output

Print the number of ways to choose three of the sticks with different lengths that can form a triangle.

Sample Input 1

5
4 4 9 7 5

Sample Output 1

5

The following five triples (i, j, k) satisfy the conditions: (1, 3, 4), (1, 4, 5), (2, 3, 4), (2, 4, 5), and (3, 4, 5).

Sample Input 2

6
4 5 4 3 3 5

Sample Output 2

8

We have two sticks for each of the lengths 3, 4, and 5. To satisfy the first condition, we have to choose one from each length.

There is a triangle whose sides have lengths 3, 4, and 5, so we have 2 ^ 3 = 8 triples (i, j, k) that satisfy the conditions.

Sample Input 3

10
9 4 6 1 9 6 10 6 6 8

Sample Output 3

39

Sample Input 4

2
1 1

Sample Output 4

0

No triple (i, j, k) satisfies 1 \leq i < j < k \leq N, so we should print 0.


open Batteries
open Printf

let ($) g f x = g (f x)

let swap = Tuple2.swap

let s2i = int_of_string
let i2s = string_of_int
let s2f = float_of_string
let f2s = string_of_float
let c2i = int_of_char
let i2c = char_of_int
let f2i = int_of_float
let i2f = float_of_int

let c2s = String.of_char
let s2cl = String.to_list
let cl2s = String.of_list

let puts s = print_endline s
let putw ?yn:(yn=("Yes", "No")) b = puts (if b then fst yn else snd yn)
let puti i = puts @@ i2s i

module StaleList = struct
  include List

  let nmem x l = not @@ mem x l

  let len = length
  let size = length
  let nempty l = not @@ is_empty l

  let hdop l = if nempty l then Some (hd l) else None

  (* let taker = drop *)
  let takewh = take_while

  (* let dropr = take *)
  let dropwh = drop_while

  let split_by = span

  let chunk = ntake

  let foldl = fold_left
  let foldli = fold_lefti
  let foldr f z l = fold_right f l z
  let foldri f z l = fold_righti f l z

  let partition_to_map f l =
    foldr (fun x m -> Map.modify_opt (f x) (function
      | None -> Some [x]
      | Some [] -> Some [x]
      | Some vl -> Some (x::vl)) m) Map.empty l;;

  let scanl f z ls =
    let rec loop acl acc = function
      | [] -> rev acl
      | h::t ->
        let r = f acc h in
        loop (r::acl) r t
    in loop [] z ls

  let scanr f z ls =
    let rec loop acl acc = function
      | [] -> acl
      | h::t ->
        let r = f h acc in
        loop (r::acl) r t
    in loop [] z (rev ls)

  (* let scanli = scan_lefti *)
  (* let scanri = scan_righti *)

  let flatmap = concat_map

  let zipf = map2
  let zipfi = map2i

end

module L = StaleList

module StaleArray = struct
  include Array

  let nmem x l = not @@ mem x l

  let len = length
  let size = length
  let is_empty r = len r = 0
  let nempty r = len r > 0

  let take n r = left r n
  let taker n r = right r n

  let takeb x r =
    let l = len r in
    let rec loop i =
      if i >= l then r
      else if r.(i) = x then take i r
      else loop (i + 1)
    in loop 0

  (* let takewh = take_while *)

  let drop n r = tail r n
  let dropr n r = take ((len r) - n) r
  (* let dropwh = drop_while *)

  let index_of x r =
    let l = len r in
    let rec loop i =
      if i >= l then None
      else if r.(i) = x then Some i
      else loop (i + 1)
    in loop 0

  (* let split_by = span *)

  (* let chunk = ntake *)

  let foldl = fold_left
  let foldli = fold_lefti
  let foldr f z l = fold_right f l z
  let foldri f z l = fold_righti f l z

  (* let partition_to_map f l = *)
  (*   foldr (fun x m -> Map.modify_opt (f x) (function *)
  (*     | None -> Some [x]  *)
  (*     | Some [] -> Some [x]  *)
  (*     | Some vl -> Some (x::vl)) m) Map.empty l;; *)

  (* let scanl = scan_left *)
  (* let scanli = scan_lefti *)
  (* let scanr = scan_right *)
  (* let scanri = scan_righti *)

  let concat2 = append

  let flatmap (f : 'a -> 'b array) a =
    map f a |> enum |> L.of_enum |> concat

  let zipf = map2
  (* let zipfi = map2i *)

end

module A = StaleArray

module StaleString = struct
  include String

  let len = length

  let replace_chars = map
  let map = replace

  let maptol f s = L.map f (s2cl s)
  let maptoli f s = L.map f (s2cl s)

  let zipf f a b = L.zipf f (s2cl a) (s2cl b)
  let zipfi f a b = L.zipfi f (s2cl a) (s2cl b)

  let mkstr f sep ls =
    L.foldl (fun acc x -> acc ^ sep ^ (f x)) (f @@ L.hd ls) (List.tl ls)

end

module S = StaleString

let spsp s = S.split_on_char ' ' s

module StaleSortedSet = struct
  include Set

  module Make (Ord : Set.OrderedType) = struct
    include Set.Make(Ord)

    let nmem x st = not @@ mem x st

    let foldl f s z = fold (fun x a -> f a x) z s

    let size = cardinal
  end

  let nmem x st = not @@ mem x st

  let foldl f s z = fold (fun x a -> f a x) z s

  let size = cardinal
end

module Ss = StaleSortedSet

module StaleSortedMap  = struct
  include Map

  module Make (Ord : Map.OrderedType) = struct
    include Map.Make(Ord)

    let nmem x st = not @@ mem x st

    let get = find
    let get_or x d m = find_default d x m

    let size = cardinal
  end

  let nmem x st = not @@ mem x st

  let get = find
  let get_or x d m = find_default d x m

  let size = cardinal
end

module Ms = StaleSortedMap

module StaleRange = struct

  type t = Range of int * int

  let make lb ub = Range (lb, ub)

  let to_list r =
    let Range (lb, ub) = r in
    L.make (ub - lb) ((+) lb)

  let to_array r =
    let Range (lb, ub) = r in
      A.make (ub - lb) ((+) lb)

  let iter r f =
    let Range (lb, ub) = r in
    for i = lb to ub do f i done

  let iter2 r1 r2 f =
    let Range (lb1, ub1) = r1 and Range (lb2, ub2) = r2 in
      for i = lb1 to ub2 do
        for j = lb2 to ub2 do
          f i j
        done
      done
end

module R = StaleRange

let (---) lb ub = R.make lb ub
let (--^) lb ub = R.make lb (ub - 1)

module StaleGenericAlgorithms = struct

  let set_power ls =
    let rec loop ls pls =
      match ls with
      | [] -> pls
      | hd::tl -> loop tl (L.flatmap (fun p -> [p; hd::p]) pls)
    in loop ls [[]]

  let rec bsearch_max_int f lb ub =
    if lb >= ub then (if f lb then lb else (lb - 1))
    else (
      let m = (lb + ub) / 2 in
      if f m then bsearch_max_int f (m + 1) ub
      else bsearch_max_int f lb m
    )

  let partial_sum n ls =
    let rec loop s k = function
      | [] -> s
      | h::t ->
        if k >= n then s
        else loop (s + h) (k + 1) t
    in
    loop 0 0 ls

end

module Gal = StaleGenericAlgorithms

module StaleIntArithmetic = struct

  let rec power x e =
    if e = 0 then x
    else
      let rec loop r x2 e' =
        if e' = 0 then r
        else if e' land 1 = 0 then loop r (x2 * x2) (e' lsr 1)
        else loop (r * x2) (x2 * x2) (e' lsr 1)
      in loop 1 x e

  let rec powers_le_1000 x =
    if x > 32 then [x]
    else
      L.init 9 (fun e -> power x (e + 1))
      |> L.filter (fun y -> y < 1000)

  let primes_le_1000 = [2;3;5;7;11;13;17;19;23;29;31;37;41;
    43;47;53;59;61;67;71;73;79;83;89;97;101;
    103;107;109;113;127;131;137;139;149;151;157;163;167;
    173;179;181;191;193;197;199;211;223;227;229;233;239;
    241;251;257;263;269;271;277;281;283;293;307;311;313;
    317;331;337;347;349;353;359;367;373;379;383;389;397;
    401;409;419;421;431;433;439;443;449;457;461;463;467;
    479;487;491;499;503;509;521;523;541;547;557;563;569;
    571;577;587;593;599;601;607;613;617;619;631;641;643;
    647;653;659;661;673;677;683;691;701;709;719;727;733;
    739;743;751;757;761;769;773;787;797;809;811;821;823;
    827;829;839;853;857;859;863;877;881;883;887;907;911;
    919;929;937;941;947;953;967;971;977;983;991;997]

    let primes_and_powers_le_1000 =
      [2;3;4;5;7;8;9;11;13;16;17;19;23;25;27;29;31;32;37;41;
      43;47;49;53;59;61;64;67;71;73;79;81;83;89;97;
      101;103;107;109;113;121;125;127;128;131;137;139;149;151;
      157;163;167;169;173;179;181;191;193;197;199;211;223;227;
      229;233;239;241;243;251;256;257;263;269;271;277;281;283;
      289;293;307;311;313;317;331;337;343;347;349;353;359;361;
      367;373;379;383;389;397;401;409;419;421;431;433;439;443;
      449;457;461;463;467;479;487;491;499;503;509;512;521;523;
      529;541;547;557;563;569;571;577;587;593;599;601;607;613;
      617;619;625;631;641;643;647;653;659;661;673;677;683;691;
      701;709;719;727;729;733;739;743;751;757;761;769;773;787;
      797;809;811;821;823;827;829;839;841;853;857;859;863;877;
      881;883;887;907;911;919;929;937;941;947;953;961;967;971;
      977;983;991;997]

  let factorize_with ps n =
    let rec loop acc ps e n' =
      if n' <= 1 then ([], n')
      else
        match ps with
        | [] -> (acc, n')
        | p::t ->
          let r = n' mod p in
          if r = 0 then (
            if n' = p then ((p, e + 1) :: acc, 1)
            else loop acc ps (e + 1) (n' / p)
          ) else
            loop (if e = 0 then acc else (p, e) :: acc) t 0 n'
    in
    let (fs, r) = loop [] ps 0 n in
    (L.rev fs, r)

  let factorize_le_million n =
    factorize_with primes_le_1000 n

  let rec to_bits_le n =
    if n = 0 then []
    else (n mod 2) :: to_bits_le (n lsr 1)

  let rec gcd x y =
    match x mod y with
    | 0 -> y
    | z -> gcd y z

  let ext_euclid a b =
    let rec next (r0, s0, t0) (r1, s1, t1) =
      match r1 with
      | 0 -> (r0, s0, t0)
      | r2 ->
        let q = r0 / r1 in
        next (r1, s1, t1) (r0 - q * r1, s0 - q * s1, t0 - q * t1)
    in
    if a < b then
      let (g, y, x) = next (b, 1, 0) (a, 0, 1) in (g, x, y)
    else
      next (a, 1, 0) (b, 0, 1)

  let modinv x m =
    let (g, y, z) = ext_euclid x m in
    match g with
    | 1 -> y mod m
    | _ -> invalid_arg "Not relatively prime"

end

module N = StaleIntArithmetic

let rds () = read_line ()

let rdi () = s2i @@ rds ()

let rdhs () = spsp @@ rds ()
let rdhi () = rdhs () |> L.map s2i

let rdhf () = rdhs () |> L.map s2f

let rdf2 () = match rdhf () with
| a::b::_ -> (a, b)
| _ -> (0., 0.)

let rdf3 () = match rdhf () with
| a::b::c::_ -> (a, b, c)
| _ -> (0., 0., 0.)

let rdf4 () = match rdhf () with
| a::b::c::d::_ -> (a, b, c, d)
| _ -> (0., 0., 0., 0.)

let rds2 () = match rdhs () with
  | a::b::_ -> (a, b)
  | _ -> ("", "")

let rdi2 () = match rdhi () with
  | a::b::_ -> (a, b)
  | _ -> (0, 0)

let rdi3 () = match rdhi () with
| a::b::c::_ -> (a, b, c)
| _ -> (0, 0, 0)

let rdi4 () = match rdhi () with
| a::b::c::d::_ -> (a, b, c, d)
| _ -> (0, 0, 0, 0)

let rdi5 () = match rdhi () with
| a::b::c::d::e::_ -> (a, b, c, d, e)
| _ -> (0, 0, 0, 0, 0)

let rdv n rf =
  let rec loop n =
    if n <= 0 then []
    else (
      let s = rf () in
      s::(loop (n - 1))
    )
  in loop n

let rdvi n = rdv n rdi
let rdvi2 n = rdv n rdi2
let rdvi3 n = rdv n rdi3
let rdvi4 n = rdv n rdi4

let print_list aa =
  printf "[ "; aa |> L.iter (fun a -> printf "%d " a); puts "]"

let print_array aa =
  printf "[ "; aa |> A.iter (fun a -> printf "%d " a); puts "]"

let print_carray aa =
  printf "[ "; aa |> A.iter (fun a -> printf "%c " a); puts "]"

let print_matrix mat =
  puts "----";
  mat |> A.iter (fun r -> print_carray r);
  puts "----"

let _ =
  let (x, k, d) = rdi3 () in
  let xa = abs x in
  let k1 = xa / d and m1 = xa mod d and m2 = d - xa mod d in
  let m =
    if k < k1 then
      abs (if x >= 0 then abs x - k * d else abs x + k * d)
    else if (k - k1) mod 2 = 0 then m1
    else m2
  in
  puti @@ abs m

Score : 300 points

Problem Statement

Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.

More specifically, in one move, he can go from coordinate x to x + D or x - D.

He wants to make K moves so that the absolute value of the coordinate of the destination will be the smallest possible.

Find the minimum possible absolute value of the coordinate of the destination.

Constraints

-10^{15} \leq X \leq 10^{15}

1 \leq K \leq 10^{15}

1 \leq D \leq 10^{15}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

X K D

Output

Print the minimum possible absolute value of the coordinate of the destination.

Sample Input 1

6 2 4

Sample Output 1

2

Takahashi is now at coordinate 6. It is optimal to make the following moves:

Move from coordinate 6 to (6 - 4 =) 2.

Move from coordinate 2 to (2 - 4 =) -2.

Here, the absolute value of the coordinate of the destination is 2, and we cannot make it smaller.

Sample Input 2

7 4 3

Sample Output 2

1

Takahashi is now at coordinate 7. It is optimal to make, for example, the following moves:

Move from coordinate 7 to 4.

Move from coordinate 4 to 7.

Move from coordinate 7 to 4.

Move from coordinate 4 to 1.

Here, the absolute value of the coordinate of the destination is 1, and we cannot make it smaller.

Sample Input 3

10 1 2

Sample Output 3

8

Sample Input 4

1000000000000000 1000000000000000 1000000000000000

Sample Output 4

1000000000000000

The answer can be enormous.