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

let id = fun x -> x
let tuple2 x y = (x,y)

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

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

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

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

let scan_array n conv =
  let b = Scanf.Scanning.from_string @@ read_line () in
  Array.init n (fun _ -> Scanf.bscanf b " %s" conv)

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

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

let (n,m) = scanf "%d %d" tuple2
let coins = scan_array m int_of_string

let () =
  let memo = Array.make_matrix (m+1) (n+1) max_int in
  memo.(0).(0) <- 0;
  List.iter (fun i ->
      let c = coins.(i-1) in
      List.iter (fun j ->
          memo.(i).(j) <-
            if j -c >= 0 then
              let x = if memo.(i-1).(j-c) <> max_int
                then memo.(i-1).(j-c) + 1 else max_int in
              let y = if memo.(i).(j-c) <> max_int
                then memo.(i).(j-c) + 1 else max_int in
              min memo.(i-1).(j) @@ min x y
            else
              memo.(i-1).(j)
        ) (0++n)
    ) (1++m);
  Printf.printf "%d\n" memo.(m).(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
  for _ = 0 to n - 1 do
    let a = read_int () in
    dp.(lower_bound dp 0 n a) <- a
  done;
  lower_bound dp 0 n max_int |> Printf.printf "%d\n"

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.


let solve n w d =
  let v0 = Array.make (w + 1) 0 in
  let v1 = Array.make (w + 1) 0 in
  let rec doit = function
    | (i, _) when i > n -> v1.(w)
    | (i, x) when x > w ->
      Array.iteri (fun i e -> v0.(i) <- e) v1;
      doit (i + 1, 1)
    | (i, x) ->
      let (vi, wi) = d.(i-1) in
      v1.(x) <- if wi <= x && v0.(x-wi) + vi > v0.(x) then v0.(x-wi) + vi else v0.(x);
      doit (i, x + 1) in
  doit (1, 1)

let read () = Scanf.scanf "%d %d\n" (fun x y -> (x, y))

let () =
  let (n, w) = read () in
  let d = Array.init n (fun _ -> read ()) in
  Printf.printf "%d\n" (solve n w d)

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
  Array.iteri (fun i _ -> if c.(0).(i) = 0 then begin v0.(i) <- 1; r := 1 end) v0;
  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 () =
  let (h, w) = Scanf.scanf "%d %d\n" (fun h w -> (h, w)) in
  let c = Array.make_matrix h w 0 in
  let rec read = function
    | (i, _) when i = h -> ()
    | (i, j) when j = w -> read (i + 1, 0)
    | (i, j) ->
      c.(i).(j) <- Scanf.scanf "%d " (fun i -> i);
      read (i, j + 1) in
  read (0, 0);
  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 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 () =
  let (h, w) = Scanf.scanf "%d %d\n" (fun h w -> (h, w)) in
  let c = Array.make_matrix h w 0 in
  let rec read = function
    | (i, _) when i = h -> ()
    | (i, j) when j = w -> read (i + 1, 0)
    | (i, j) ->
      c.(i).(j) <- Scanf.scanf "%d " (fun i -> i);
      read (i, j + 1) in
  read (0, 0);
  Printf.printf "%d\n" (solve h w c)


let solve h w c =
  let s = Array.make w 0 in
  let t = 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
      s.(j) <- 1;
      r := 1
    end
  done;
  for i = 1 to h - 1 do
    if c.(i).(0) = 0 then t.(0) <- 1;
    for j = 1 to w - 1 do
      if c.(i).(j) = 1 then t.(j) <- 0
      else begin
        let d = if s.(j) < t.(j-1) then s.(j) else t.(j-1) in
        t.(j) <- 1 + if s.(j-1) < d then s.(j-1) else d;
        if t.(j) > !r then r := t.(j)
      end
    done;
    Array.iteri (fun i e -> s.(i) <- e) t
  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
      read () |> doit 0
    done;
    solve h w c |> Printf.printf "%d\n"
  | _ -> assert false


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 h w c =
  let s = Array.make w 0 in
  let t = Array.make w 0 in
  let r = ref 0 in
  for j = 0 to w - 1 do
    if c.(0).(j) then begin
      s.(j) <- 1;
      r := 1;
    end
  done;
  if !r = 0 then begin
    let rec doit i =
      if i = h then ()
      else if c.(i).(0) then r := 1
      else doit (i + 1) in
    doit 0
  end;
  for i = 1 to h - 1 do
    if c.(i).(0) then t.(0) <- 1;
    for j = 1 to w - 1 do
      if not c.(i).(j) then t.(j) <- 0
      else begin
        let d = if s.(j) < t.(j-1) then s.(j) else t.(j-1) in
        t.(j) <- 1 + if s.(j-1) < d then s.(j-1) else d;
        if t.(j) > !r then r := t.(j)
      end
    done;
    Array.iteri (fun i e -> s.(i) <- e) t
  done;
  !r * !r

let () =
  match IO.read_ns () with
  | [h; w] ->
    let c = Array.make_matrix h w false in
    for i = 0 to h - 1 do
      IO.read_ns () |> List.iteri (fun j e -> c.(i).(j) <- e = 0);
    done;
    solve h w c |> Printf.printf "%d\n"
  | _ -> assert false


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 h w c =
  let s = Array.make w 0 in
  let t = Array.make w 0 in
  let r = ref 0 in
  List.iteri (fun j e -> if e = 0 then begin
    s.(j) <- 1;
    r := 1;
  end) c.(0);
  if !r = 0 then begin
    let rec doit i =
      if i = h then ()
      else begin
        match c.(i) with
        | [] -> ()
        | hd :: _ ->
          if hd = 0 then r := 1
          else doit (i + 1)
      end in
    doit 0
  end;
  Array.iteri (fun i l ->
    if i = 0 then ()
    else begin
      match l with
      | [] -> assert false
      | x :: xs ->
        if x = 0 then t.(0) <- 1;
        List.iteri (fun j e ->
          let j = j + 1 in
          if e = 1 then t.(j) <- 0
          else begin
            let d = if s.(j) < t.(j-1) then s.(j) else t.(j-1) in
            t.(j) <- 1 + if s.(j-1) < d then s.(j-1) else d;
            if t.(j) > !r then r := t.(j)
          end) xs;
        Array.iteri (fun i e -> s.(i) <- e) t
    end)
    c;
  !r * !r

let () =
  match IO.read_ns () with
  | [h; w] ->
    Array.init h (fun _ -> IO.read_ns ()) |> solve h w |> Printf.printf "%d\n"
  | _ -> assert false


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 rec g ans j xs =
    if j = w then (ans, xs)
    else
      match xs with
      | [] -> g ans (j + 1) [(v.(j), j)]
      | (ch, _) :: _ ->
        if ch = v.(j) then g ans (j + 1) xs
        else if ch < v.(j) then g ans (j + 1) ((v.(j), j) :: xs)
        else
          let rec f ans k = function
            | [] -> g ans (j + 1) [(v.(j), k)]
            | (ch, cj) :: tl as ys ->
              if ch >= v.(j) then f (if ch * (j - cj) > ans then ch * (j - cj) else ans) cj tl
              else g ans (j + 1) ((v.(j), k) :: ys) in
          f ans j xs in
  let (ans, xs) = g ans 0 [] 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

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


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

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 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
        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


type t = { mutable x : int; mutable y : 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_set s x =
  let rec doit x =
    if x <> s.(x).x then s.(x).x <- doit (s.(x).x);
    s.(x).x in
  doit x

let unite s x y =
  let (a, b) = (find_set s x, find_set s y) in
  if s.(a).y > s.(b).y then s.(b).x <- a
  else begin
    s.(a).x <- b;
    if s.(a).y = s.(b).y then s.(b).y <- s.(b).y + 1
  end

let solve n q =
  let s = Array.init n (fun i -> { x = i; y = 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 find_set s x = find_set s y then "1" else "0")
    | _ -> assert false
  done

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

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


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_ss () = read_line () |> split_on_char ' '

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

end

module SeguementTree = struct

  let default_val = ref 0

  let size = ref 0

  let make n init =
    default_val := init;
    let rec pow_of_2 i =
      if i >= n then i
      else pow_of_2 (2 * i) in
    size := pow_of_2 1;
    Array.make (2 * (!size) - 1) init

  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 update (s : int array) i x =
    let j = !size + i - 1 in
    s.(j) <- x;
    let rec doit j =
      if j <= 0 then () else
      begin
        let p = parent j in
        let l = s.(left p) in
        let r = s.(right p) in
        s.(p) <- if l < r then l else r;
        doit p
      end in
    doit j

  let find s a b =
    let rec doit a b k l r =
      if r <= a || b <= l then !default_val
      else if a <= l && r <= b then s.(k)
      else begin
        let v = doit a b (left k) l ((l + r) / 2) in
        let w = doit a b (right k) ((l + r) / 2) r in
        if v < w then v else w
      end in
    doit a b 0 0 !size

end

module S = SeguementTree

let solve n q =
  let s = S.make n 2147483647 in
  for _ = 0 to q - 1 do
    match IO.read_ns () with
    | c :: x :: y :: _ ->
      if c = 0 then S.update s x y
      else Printf.printf "%d\n" (S.find s x (y + 1))
    | _ -> assert false
  done

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

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 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 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 : int array) 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 (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 (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_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 -> Printf.printf "%d\n" e) (List.sort (-) !ans);
      Printf.printf "\n";
      ans := []
    | _ -> assert false
  done

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


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 rec pow_mod x e m =
  let rec loop a e' =
    if e' = 0 then a mod m
    else loop ((a * x) mod m) (e'-1)
  in
  loop 1 e

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"

let rec fact_mod x m =
  let rec loop a x' =
    if x' <= 0 then a
    else loop ((x' * a) mod m) (x' - 1)
  in loop 1 x

let binom_mod n k m =
  let a = fact_mod n m in
  let b = fact_mod k m in
  let c = fact_mod (n - k) m in
  (a * modinv (b * c) m) mod m

module StaleFFT = struct

  let complex_cooley_tukey ps ar =

    let rec part e d ba =
     ()
    in

  ()
end

module StaleGraph = struct

  type iset_t = int Ss.t
  type 'a v_t = { i : int; nb : iset_t; data : 'a }
  type 'a t = 'a v_t array

  let empty nv vd =
    A.init (nv + 1) (fun i -> { i = i; nb = Ss.empty; data = vd })

  let add_edge (e : int * int) g =
    let (v1, v2) = e in
    g.(v1) <- { g.(v1) with nb = Ss.add v2 g.(v1).nb };
    g

  let add_uedge e g =
    add_edge e @@ add_edge (swap e) g

  let from_edges nv vd es =
    es |> L.foldl (fun g e -> add_edge e g) (empty nv vd)

  let from_uedges nv vd es =
    es |> L.foldl (fun g e -> add_uedge e g) (empty nv vd)

  let setd g v d = g.(v.i) <- { g.(v.i) with data = d }
  let getd g v = g.(v.i).data

  let setdi g i d = g.(i) <- { g.(i) with data = d }
  let getdi g i = g.(i).data

  let sort_by_data cmp g =
    g |> A.sort (fun v1 v2 -> cmp v1.data v2.data)

  type ('a, 'b) update_t = 'a v_t -> iset_t -> 'a t -> 'b

  let rec frontier (upd : ('a, bool) update_t)
    (fr : iset_t) (cls : iset_t) (g : 'a t) =

    let (fr_next, cls_next) =
      fr |> Ss.foldl (fun (fr_next, cls_cur) i ->
        let v = g.(i) in
        let opnb = Ss.diff v.nb cls_cur in
        let cl = upd v opnb g in
        (Ss.union fr_next opnb |> Ss.remove i,
          if cl then Ss.add i cls_cur else cls_cur)
      ) (Ss.empty, cls)
    in

    if Ss.is_empty fr then cls
    else frontier upd fr_next cls_next g

  let bfs (upd : ('a, unit) update_t) s g =
    frontier (fun v opnb g -> upd v opnb g; true)
      (Ss.sing s) Ss.empty g

  let steps_by (f : ('a, unit) update_t -> int -> 'a t -> iset_t) s g =
    f (fun v nb g -> nb |> Ss.iter (fun i -> setdi g i (getd g v + 1))) s g

end

module G = StaleGraph

let _ =
  let prim = 1000000007 in

  let n,m = rdi2 () in
  let es = rdvi2 m in
  let g = G.from_uedges n false es in
  G.setdi g 0 true;

  let rec decomp rvs ops cls =
    let v0 = Ss.choose ops in
    (* G.setdi g v0 true; *)
    (* puti v0; *)
    let opsr = ref (Ss.remove v0 ops) in
    let cls_next = g |> G.frontier (fun v opnb g ->
      opnb |> Ss.iter (fun w -> (* G.setdi g w true; *)
      (* puti w; *)
      opsr := Ss.remove w !opsr); true
      ) (Ss.sing v0) cls in
    (* print_list @@ Ss.to_list cls_next; *)
    (* print_list @@ Ss.to_list !opsr; *)
    if Ss.size cls_next = n then (Ss.add v0 rvs)
    else decomp (Ss.add v0 rvs) !opsr cls_next
  in

  let ops_init = Ss.of_list @@ L.range 1 `To n in
  let rvs = decomp Ss.empty ops_init Ss.empty in
  puti @@ Ss.size rvs - 1;
  ()

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
let s = read_line ()
let ss = (if s.[(String.length s)-1] = 's' then "es" else "s")
let () = print_endline (s ^ ss)

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


open Printf
open Scanf

let primes = Array.make 1000000 0;;
let np = ref 0;;

let input_int () =
  scanf "%d\n" (fun k -> k)

let is_prime k =
  let n = !np in
  let rec loop i =
    if i=n then
      true
    else if k mod primes.(i) = 0 then
      false
    else
      loop (i+1)
  in
  loop 0

let next_prime () =
  let n = !np in
  let rec loop k =
    if is_prime k then
      begin
        primes.(n) <- k;
        np := n + 1;
        k
      end
    else
      loop (k+2)
  in
  loop primes.(n-1)

let find_pow n p =
  let rec loop c k =
    if k mod p = 0 then
      loop (c+1) (k / p)
    else
      (c, k)
  in
  loop 0 n

let find_factor m =
  let n = !np in
  let rec loop2 () =
    let x = next_prime () in
    if m mod x = 0 then
      x
    else
      loop2 ()
  in
  let rec loop i =
    if i=n then
      loop2 ()
    else if m mod primes.(i) = 0 then
      primes.(i)
    else
      loop (i+1)
  in
  loop 0

let h n =
  let rec loop c k =
    if k=1 then
      c
    else
      let p = find_factor k in
      let (m, k) = find_pow k p in
      loop ((m + 1) * c) k
  in
  if n mod 2 = 0 then
    let (m, n) = find_pow n 2 in
    loop (m + 1) n
  else
    loop 1 n

let f () =
  let n = input_int () in
  let rec loop tot c =
    (* printf "%d\n" c; *)
    if c = n then
      tot
    else
      loop (tot + h (n - c)) (c+1)
  in
  loop 0 1

let () =
  primes.(0) <- 2;
  primes.(1) <- 3;
  np := 2;
  let tot = f () in
  printf "%d\n" tot

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


let () = Scanf.scanf "%d %d %d %d\n" @@ fun a b c d ->
  Printf.printf "%d\n" @@
  List.fold_left max min_int
  [a * c; a * d; 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 %d %d %d\n" @@ fun a b c d ->
  Printf.printf "%d\n"
    (if a < 0 && c < 0 then
       if b > 0 && d > 0 then max (a*c) (b*d)
       else a*c
     else if a > 0 && c > 0 || b > 0 && d > 0 then b*d
     else if a <= 0 && 0 <= b || c <= 0 && 0 <= d then 0
     else max (a*d) (b*c))


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)-(powmod 9 n 1)+(powmod 8 n 1)-(powmod 9 n 1) mod 1000000007)
     +1000000007) mod 1000000007)

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 () =
  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) - (powmod 9 n 1) - (powmod 9 n 1) + (powmod 8 n 1) + 1000000007) mod 1000000007)


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)) mod 1000000007)


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 rec pow_mod x e m =
  let rec loop a e' =
    if e' = 0 then a mod m
    else loop ((a * x) mod m) (e'-1)
  in
  loop 1 e

let _ =
  let n = rdi () in
  let m = 1000000007 in
  let a = (pow_mod 10 n m) - 2 * (pow_mod 9 n m) + (pow_mod 8 n m) in
  let ans = if a >= 0 then a mod m else (m - (-a) mod m) in
  puti a;
  ()


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

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

module type S = sig
    type t
    type cap

    val create      : int -> int -> t
    val add_edge    : t -> int -> int -> cap -> t
    val get_edge    : t -> int -> int * int * cap * cap
    val edges       : t -> (int * int * cap * cap) array
    val change_edge : t -> int -> cap -> cap -> unit
    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 change_edge (n, idx, g, pos) i new_cap new_flow =
            let _e = pos.(i * 2) in
            let _re = pos.(_e.rev) in
            _e.cap <- Cap.sub new_cap new_flow;
            _re.cap <- new_flow

        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 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
                            flow_loop (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;
    Array.iter (fun arr ->
        Array.iter print_char arr;
        print_newline ()
    ) map
)

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.#
^><


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 get_edge    : t -> int -> int * int * cap * cap
    val edges       : t -> (int * int * cap * cap) array
    val change_edge : t -> int -> cap -> cap -> unit
    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 change_edge (n, idx, g, pos) i new_cap new_flow =
            let _e = pos.(i * 2) in
            let _re = pos.(_e.rev) in
            _e.cap <- Cap.sub new_cap new_flow;
            _re.cap <- new_flow

        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 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
                            flow_loop (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
)


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

module CapInt : CapType with type t = int = struct
    type t = int
    let zero = 0
    let cap_max = max_int
    let add = (+)
    let sub = (-)
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 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 (
                    let mf = if (x + y) mod 2 = 0 then MF.add_edge mf s pivot 1
                                                  else MF.add_edge mf pivot t 1
                    in
                    if (x + y) mod 2 <> 0 then mf else (
                        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 + 1 = to_  then prt from '>' to_ '<' else
        if to_  + 1 = from then prt from '<' to_ '>' else
        if from + m = to_  then prt from 'v' to_ '^' else
        if to_  + m = from then prt from '^' to_ 'v'
    )) 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
)


open Core;;

let s = In_channel.(input_line_exn stdin)
let t = In_channel.(input_line_exn stdin)

let () =
  let res =
    let n = String.length s in
    let m = String.length t in
    let dist x y =
      let rec cnt i = if (i < 0) then 0 else (if (Char.equal (String.get x i) (String.get y i)) then 0 else 1) + cnt (i - 1) in
      cnt ((String.length x) - 1)
    in
    List.range 0 (n - m + 1) |>
    List.map ~f:(fun i -> dist (String.sub ~pos:i ~len:m s) t) |>
    List.reduce_exn ~f:Int.min
  in
  printf "%d\n" res
;;

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


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 n = rdi () in
  let aa = rdhi () in

  let rec steps sum mx = function
  | [] -> sum
  | h::t ->
    if h < mx then
      let r = mx - h in
      steps (sum + r) mx t
    else
      steps sum h t
  in

  puti @@ steps 0 0 aa

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 s = read_line ()
let () = (if s = "SSS" then 3 else
if s = "RSS" then 2 else
if s = "SSR" then 2 else 1) |> Printf.printf "%d\n"

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.


open Batteries
let get_max a b c = max a @@ max b c
let get_others a b c =
  let max_ = get_max a b c in
    if a = max_ then (b, c) else
    if b = max_ then (a, c) else (a, b)

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

let is_triangle a b c =
  let cosa = (float_of_int @@ b * b + c * c - a * a) /. (float_of_int @@ 2 * b * c) in
  -1. < cosa && cosa < 1.

let rec i_loop i result_i =

  let rec j_loop j result_j =

    let rec k_loop k result_k =
      if k >= n then result_k else (
        if l.(i) = l.(j) || l.(j) = l.(k) || l.(i) = l.(k) then k_loop (k+1) result_k else
        if is_triangle l.(i) l.(j) l.(k) then k_loop (k+1) (result_k+1) else k_loop (k+1) result_k
      )
    in if j >= n then result_j else j_loop (j+1) (result_j + k_loop (j+1) 0)
  in if i >= n then result_i else i_loop (i+1) (result_i + j_loop (i+1) 0)

let _ = Printf.printf "%d\n" @@ i_loop 0 0

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.


Scanf.scanf "%d %d %d" (fun rr cc k ->
    let mat = Array.make_matrix rr cc 0 in
    for i = 1 to k do
        Scanf.scanf " %d %d %d" (fun rr cc v ->
            mat.(rr - 1).(cc - 1) <- v
        )
    done;
    let max (a:int) (b:int) = if a < b then b else a in

    let prev = Array.make cc 0 in
    for y = 0 to rr - 1 do
        let m = mat.(y) in
        let rec loop x work0 work1 work2 work3 =
            if x < cc then (
                let work0 = max work0 prev.(x) in
                let v = m.(x) in
                let work3 = max work3 (work2 + v) in
                let work2 = max work2 (work1 + v) in
                let work1 = max work1 (work0 + v) in
                prev.(x) <- max (max work3 work2) (max work1 work0);
                loop (x + 1) work0 work1 work2 work3
            )
        in
        loop 0 0 0 0 0
    done;
    Printf.printf "%d\n" (prev.(cc - 1))
)

Score : 500 points

Problem Statement

There are K items placed on a grid of squares with R rows and C columns. Let (i, j) denote the square at the i-th row (1 \leq i \leq R) and the j-th column (1 \leq j \leq C). The i-th item is at (r_i, c_i) and has the value v_i.

Takahashi will begin at (1, 1), the start, and get to (R, C), the goal. When he is at (i, j), he can move to (i + 1, j) or (i, j + 1) (but cannot move to a non-existent square).

He can pick up items on the squares he visits, including the start and the goal, but at most three for each row. It is allowed to ignore the item on a square he visits.

Find the maximum possible sum of the values of items he picks up.

Constraints

1 \leq R, C \leq 3000

1 \leq K \leq \min(2 \times 10^5, R \times C)

1 \leq r_i \leq R

1 \leq c_i \leq C

(r_i, c_i) \neq (r_j, c_j) (i \neq j)

1 \leq v_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

R C K
r_1 c_1 v_1
r_2 c_2 v_2
:
r_K c_K v_K

Output

Print the maximum possible sum of the values of items Takahashi picks up.

Sample Input 1

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

Sample Output 1

8

He has two ways to get to the goal:

Visit (1, 1), (1, 2), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 5 = 8.

Visit (1, 1), (2, 1), and (2, 2), in this order. In this case, the total value of the items he can pick up is 3 + 4 = 7.

Thus, the maximum possible sum of the values of items he picks up is 8.

Sample Input 2

2 5 5
1 1 3
2 4 20
1 2 1
1 3 4
1 4 2

Sample Output 2

29

We have four items in the 1-st row. The optimal choices are as follows:

Visit (1, 1) (1, 2), (1, 3), (1, 4), (2, 4), and (2, 5), in this order, and pick up all items except the one on (1, 2). Then, the total value of the items he picks up will be 3 + 4 + 2 + 20 = 29.

Sample Input 3

4 5 10
2 5 12
1 5 12
2 3 15
1 2 20
1 1 28
2 4 26
3 2 27
4 5 21
3 5 10
1 3 10

Sample Output 3

142


open Printf
open Scanf

let solve x =
  if x >= 30 then "Yes" else "No"

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

Score : 100 points

Problem Statement

You will turn on the air conditioner if, and only if, the temperature of the room is 30 degrees Celsius or above.

The current temperature of the room is X degrees Celsius. Will you turn on the air conditioner?

Constraints

-40 \leq X \leq 40

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print Yes if you will turn on the air conditioner; print No otherwise.

Sample Input 1

25

Sample Output 1

No

Sample Input 2

30

Sample Output 2

Yes


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

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 n = rdi () in
  putw (n = 30);
  ()


open Printf
open Scanf

let id x = x

let n, d = scanf "%d %d\n" (fun n d -> n, float d)
let ary = Array.init n (fun _ -> scanf "%d %d\n" (fun x y -> float x, float y))

let run () =
    let n = Array.fold_left (fun n (x, y) -> if x *. x +. y *. y <= d *. d then n + 1 else n) 0 ary in
    printf "%d\n" n

let () = run ()

Score : 200 points

Problem Statement

We have N points in the two-dimensional plane. The coordinates of the i-th point are (X_i,Y_i).

Among them, we are looking for the points such that the distance from the origin is at most D. How many such points are there?

We remind you that the distance between the origin and the point (p, q) can be represented as \sqrt{p^2+q^2}.

Constraints

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

0 \leq D \leq 2\times 10^5

|X_i|,|Y_i| \leq 2\times 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N D
X_1 Y_1
\vdots
X_N Y_N

Output

Print an integer representing the number of points such that the distance from the origin is at most D.

Sample Input 1

4 5
0 5
-2 4
3 4
4 -4

Sample Output 1

3

The distance between the origin and each of the given points is as follows:

\sqrt{0^2+5^2}=5

\sqrt{(-2)^2+4^2}=4.472\ldots

\sqrt{3^2+4^2}=5

\sqrt{4^2+(-4)^2}=5.656\ldots

Thus, we have three points such that the distance from the origin is at most 5.

Sample Input 2

12 3
1 1
1 1
1 1
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3

Sample Output 2

7

Multiple points may exist at the same coordinates.

Sample Input 3

20 100000
14309 -32939
-56855 100340
151364 25430
103789 -113141
147404 -136977
-37006 -30929
188810 -49557
13419 70401
-88280 165170
-196399 137941
-176527 -61904
46659 115261
-153551 114185
98784 -6820
94111 -86268
-30401 61477
-55056 7872
5901 -163796
138819 -185986
-69848 -96669

Sample Output 3

6