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

let rec find (a:(string*int) array) (x,y) n =
  if (fst a.(n)) = x && (snd a.(n)) = y then n else find a (x,y) (n+1);;

let is_stable org (c:(string*int) array) n =
  let rec loop = function
      i when i = n -> "Stable"
    | i ->
       if (snd c.(i)) = (snd c.(i-1)) then
         if find org c.(i) 0 > find org c.(i-1) 0 then loop (i+1)
         else "Not stable"
       else
         loop (i+1)
  in loop 1
;;

let partition (a:(string*int) array) p r =
  let (_,x) = a.(r) and
      i = ref (p-1) in
  for j = p to (r-1) do
    if (snd a.(j)) <= x then
      begin
        i := (!i) + 1;
        swap a (!i) j;
      end;
  done;
  swap a ((!i)+1) r;
  (!i) + 1
;;

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

let () =
  let n = read_int () in
  let a1 = Array.init n (fun x -> Scanf.scanf "%s %d\n" (fun y z-> (y,z))) in
  let a2 = Array.copy a1 in
  quick_sort a2 0 (n-1);
  print_endline (is_stable a1 a2 n);
  Array.iter (fun (x,y) -> Printf.printf "%s %d\n" x y) a2
;;

Quick Sort

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

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

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

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

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

Input

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

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

Output

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

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

Constraints

1 ≤ n ≤ 100,000

1 ≤ the number of a card ≤ 109

There are no identical card in the input

Sample Input 1

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

Sample Output 1

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

Sample Input 2

2
S 1
H 1

Sample Output 2

Stable
S 1
H 1


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

let stable_p (a : (int * char * int) array) n =
  let rec doit i =
    if i = n then true
    else if (fun (xi, _, xd) (yi, _, yd) -> xd = yd && xi > yi) a.(i-1) a.(i) then false
    else doit (i + 1) in
  doit 1

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 () =
  let n = read_int () in
  let read i =
    match split (read_line ()) ' ' with
    | [c; d] -> (i, c.[0], int_of_string d)
    | _ -> exit 1 in
  let a = Array.init n read in
  quick_sort a (fun (_, _, x) (_, _, y) -> compare x y);
  print_endline (if stable_p a n then "Stable" else "Not stable");
  Array.iter (fun (_, c, d) -> Printf.printf "%c %d\n" c d) a

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

Submitted source-code file size, in bytes.

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

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


type card = { id : int; ch : char; num : int }

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

let stable_p (a : card array) n =
  let rec doit i =
    if i = n then true
    else if (fun a b -> a.num = b.num && a.id > b.id) a.(i-1) a.(i) then false
    else doit (i + 1) in
  doit 1

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 () =
  let n = read_int () in
  let read i =
    match split (read_line ()) ' ' with
    | [c; d] -> { id = i; ch = c.[0]; num = int_of_string d }
    | _ -> exit 1 in
  let a = Array.init n read in
  quick_sort a (fun a b -> a.num - b.num);
  print_endline (if stable_p a n then "Stable" else "Not stable");
  Array.iter (fun e -> Printf.printf "%c %d\n" e.ch e.num) a


let quick_sort (a : (int * char * int) array) n 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 begin
        swap !i j;
        incr i;
      end
    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 0 (n - 1)

let stable_p (a : (int * char * int) array) n =
  try
    for i = 1 to n - 1 do
      if (fun (xi, _, xd) (yi, _, yd) -> xd = yd && xi > yi) a.(i-1) a.(i) then raise Exit
    done;
    true
  with Exit -> false

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

let () =
  let n = read_int () in
  let a = Array.init n (fun i ->
    match read_line () |> split_on_char ' ' with
    | [c; d] -> (i, c.[0], int_of_string d)
    | _ -> assert false) in
  quick_sort a n (fun (_, _, x) (_, _, y) -> compare x y);
  print_endline (if stable_p a n then "Stable" else "Not stable");
  Array.iter (fun (_, c, d) -> Printf.printf "%c %d\n" c d) a


module DoublyChainedTree = struct
  let nil = -1

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

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

module T = DoublyChainedTree

let () =
  let n = read_int () in
  let t = Array.init n (fun _ -> T.make ()) in
  let rec read_tree i =
    if i < n then begin
      match List.map int_of_string (Str.split (Str.regexp " ") (read_line ())) with
      | id :: _ :: tl -> begin
          let rec read_lst j left_child = function
            | [] -> ()
            | c :: cs -> begin
                t.(c).T.parent <- id;
                if j = 0 then t.(id).T.child <- c else t.(left_child).T.bro <- c;
                read_lst (j+1) c cs
              end
          in
          read_lst 0 0 tl;
          read_tree (i + 1)
        end
      | _ -> exit 1
    end
  in
  read_tree 0;
  let rec search_root i =
    if i = n then T.nil
    else if t.(i).T.parent = T.nil then i
    else search_root (i + 1)
  in
  let root = search_root 0 in
  let rec set_depth i p =
    t.(i).T.depth <- p;
    if t.(i).T.bro <> T.nil then set_depth t.(i).T.bro p;
    if t.(i).T.child <> T.nil then set_depth t.(i).T.child (p + 1);
  in
  set_depth root 0;
  let print_node i =
    Printf.printf "node %d: parent = %d, depth = %d, " i t.(i).T.parent t.(i).T.depth;
    print_string (if t.(i).T.parent = T.nil then "root, " else if t.(i).T.child = T.nil then "leaf, " else "internal node, ");
    print_string "[";
    let rec print_children c =
      if c <> T.nil then begin
        if c <> t.(i).T.child then print_string ", ";
        print_int c;
        print_children t.(c).T.bro
      end
    in
    print_children t.(i).T.child;
    print_endline "]"
  in
  let rec print i =
    if i < n then (print_node i; print (i + 1))
  in
  print 0

Rooted Trees

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

Fig. 1

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

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

node ID of u

parent of u

depth of u

node type (root, internal node or leaf)

a list of chidlren of u

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

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

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

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

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

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

Fig. 2

Input

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

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

id k c1 c2 ... ck

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

Output

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

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

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

d is depth of the node.

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

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

Please follow the format presented in a sample output below.

Constraints

1 ≤ n ≤ 100000

Sample Input 1

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

Sample Output 1

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

Sample Input 2

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

Sample Output 2

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

Note

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

the parent of u

the leftmost child of u

the immediate right sibling of u

Reference

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


let nil = -1

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

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

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

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

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


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

let create () = Nil

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

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

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

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

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

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

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

Binary Search Tree I

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

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

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

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

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

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

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

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

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

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

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

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

Input

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

Output

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

Constraints

The number of operations $\leq 500,000$

The number of print operations $\leq 10$.

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

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

The keys in the binary search tree are all different.

Sample Input 1

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

Sample Output 1

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

Reference

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


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

let create () = Nil

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

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

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

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

let () =
  let m = read_int () in
  let rec read i t =
    if i < m then
      let op = Scanf.scanf "%s " (fun i -> i) in
      if op = "print" then (print t; read (i + 1) t)
      else read (i + 1) (insert (Scanf.scanf "%d " (fun i -> i)) t)
  in
  read 0 (create ())


let h = ref 0

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

let left i = 2*i

let right i = 2*i + 1

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

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

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

let () =
  let t = Array.make 2000001 0 in
  let rec doit () =
    match split (read_line ()) ' ' with
    | ["extract"] -> (Printf.printf "%d\n" (extract t); doit ())
    | ["insert"; n] -> (insert (int_of_string n) t; doit ())
    | _ -> ()
  in doit ()

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

Priority Queue

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

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

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

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

Input

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

The input ends with "end" operation.

Output

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

Constraints

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

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

Sample Input 1

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

Sample Output 1

8
10
11
2


let h = ref 0

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

let left i = 2*i

let right i = 2*i + 1

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

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

let insert x (t : int array) =
  let rec doit i =
    if i > 1 && t.(parent i) < t.(i) then begin
      swap i (parent i) t;
      doit (parent i)
    end in
  incr h;
  t.(!h) <- x;
  doit !h

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

let () =
  let t = Array.make 2000001 0 in
  let rec doit () =
    match split_on_char ' ' (read_line ()) with
    | ["extract"] -> Printf.printf "%d\n" (extract t); doit ()
    | ["insert"; n] -> insert (int_of_string n) t; doit ()
    | _ -> () in
  doit ()


let last_i = ref 0

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

let left i = 2*i

let right i = 2*i + 1

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

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

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

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

let () =
  let t = Array.make 2000001 0 in
  while true do
    match read_line () |> split_on_char ' ' with
    | ["extract"] -> extract t |> Printf.printf "%d\n"
    | ["insert"; n] -> insert (int_of_string n) t
    | _ -> exit 0
  done


let last_i = ref 0

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

let left i = 2*i

let right i = 2*i + 1

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

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

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

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

let () =
  let t = Array.make 2000001 0 in
  while true do
    match read_line () |> split_on_char ' ' with
    | ["extract"] -> print_int (extract t); print_newline ()
    | ["insert"; n] -> insert (int_of_string n) t
    | _ -> exit 0
  done


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

let solve a n w =
  let dp = Array.make_matrix (n + 1) (w + 1) 0 in
  for i = 1 to n do
    for j = 1 to w do
      dp.(i).(j) <-
        if j - a.(i-1).w < 0 then dp.(i-1).(j)
        else max dp.(i-1).(j) (dp.(i-1).(j - a.(i-1).w) + a.(i-1).v);
    done
  done;
  dp.(n).(w)

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

0-1 Knapsack Problem

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

1 ≤ wi ≤ 1000

1 ≤ W ≤ 10000

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


open Printf
open Scanf

module P = struct
  type path = Len of int | Inf | Unk

  let min l1 l2 =
    match l1, l2 with
      Len x, Len y when x < y -> Len x
    | Len x, Len y -> Len y
    | Len x, _ -> Len x
    | _, Len y -> Len y
    | _, _ -> Inf

  let add l1 l2 =
    match l1, l2 with
      Len x, Len y -> Len (x + y)
    | _, _ -> Inf

  let get = function
      Len x -> x
    | Inf -> (-1)
    | _ -> failwith "get"
end

let () =
  let nv, ne = scanf "%d %d " (fun x y -> (x, y)) in
  let g = Array.make_matrix nv nv P.Inf in
  let memo = Array.make_matrix (1 lsl nv) nv P.Unk in
  let set_g n =
    let rec loop x =
      if x = 0 then ()
      else let s, t, d = scanf "%d %d %d " (fun x y z -> (x, y, z)) in
           g.(s).(t) <- P.Len d;
           loop (x-1) in
    loop n in
  let rec search s v =
    match memo.(s).(v) with
      P.Unk ->
      let rec loop u l =
        if u = nv then l
        else
          if s lsr u land 1 = 0 then loop (u+1) (P.min l (P.add g.(v).(u) (search (s lor (1 lsl u)) u)))
          else loop (u+1) l
      in
      let ml = loop 0 P.Inf in
      memo.(s).(v) <- ml; ml
    | x -> x in
  set_g ne;
  memo.((1 lsl nv) - 1 ).(0) <- P.Len 0;
  printf "%d\n" (P.get (search 0 0))

Traveling Salesman Problem

For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria:

It is a closed cycle where it ends at the same point it starts.

It visits each vertex exactly once.

Input

|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1

|V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.

si and ti represent source and target vertices of i-th edge (directed) and di represents the distance between si and ti (the i-th edge).

Output

Print the shortest distance in a line. If there is no solution, print -1.

Constraints

2 ≤ |V| ≤ 15

0 ≤ di ≤ 1,000

There are no multiedge

Sample Input 1

4 6
0 1 2
1 2 3
1 3 9
2 0 1
2 3 6
3 2 4

Sample Output 1

16

Sample Input 2

3 3
0 1 1
1 2 1
0 2 1

Sample Output 2

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

end

let min (x : int) y = if x < y then x else y

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
        t.(j) <- min s.(j-1) (min s.(j) t.(j-1)) + 1;
        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

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 =
  for j = 0 to w - 1 do
    c.(0).(j) <- 1 - c.(0).(j);
    for i = 1 to h - 1 do
      c.(i).(j) <- if c.(i).(j) = 1 then 0 else c.(i-1).(j) + 1
    done
  done;
  let rec duduwa ans i j k = function
    | [] -> (ans, [(c.(i).(j), k)])
    | (ch, cj) :: y' when ch >= c.(i).(j) -> duduwa (if ch * (j - cj) > ans then ch * (j - cj) else ans) i j cj y'
    | ys -> (ans, (c.(i).(j), k) :: ys) in
  let rec doit ans = function
    | (i, _, xs) when i = h -> ans
    | (i, j, xs) when j = w -> doit (List.fold_left (fun acc (ch, cj) -> if ch * (w - cj) > acc then ch * (w - cj) else acc) ans xs) (i + 1, 0, [])
    | (i, j, []) -> doit ans (i, j + 1, [(c.(i).(j), j)])
    | (i, j, ((ch, _) :: _ as xs)) when ch < c.(i).(j) -> doit ans (i, j + 1, (c.(i).(j), j) :: xs)
    | (i, j, ((ch, _) :: _ as xs)) when ch > c.(i).(j) ->
      let (ans, ys) = duduwa ans i j j xs in
      doit ans (i, j + 1, ys)
    | (i, j, xs) -> doit ans (i, j + 1, xs) in
  doit 0 (0, 0, [])

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

let read () = List.map int_of_string (split_on_char ' ' (read_line ()))

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

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


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

type t = { h : int; i : int }

let max (x : int) y = if x > y then x else y

let solve w v =
  let (m, _, xs) = Array.fold_left (fun (m, i, xs) h -> match xs with
    | [] -> (m, i + 1, [ { h; i } ])
    | x :: _ ->
      if x.h = h then (m, i + 1, xs)
      else if x.h < h then (m, i + 1, { h; i } :: xs)
      else
        let rec doit m j = function
          | [] -> (m, i + 1, [ { h; i = j } ])
          | x :: tl as xs ->
            if x.h >= h then doit (max (x.h * (i - x.i)) m) x.i tl
            else (m, i + 1, { h; i = j } :: xs) in
        doit m i xs)
    (0, 0, [])
    v in
  List.fold_left (fun m x -> max (x.h * (w - x.i)) m) m 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;
        let m = solve w t in
        doit (i + 1) (max m ans)
      end in
    doit 0 0 |> Printf.printf "%d\n"
  | _ -> assert false


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 solve n q =
  let a = Array.init n (fun i -> (i, 0)) in
  let rec find_set x =
    if x <> fst a.(x) then a.(x) <- (find_set (fst a.(x)), snd a.(x));
    fst a.(x) in
  let link x y =
    if snd a.(x) > snd a.(y) then a.(y) <- (x, snd a.(y))
    else begin
      a.(x) <- (y, snd a.(x));
      if snd a.(x) = snd a.(y) then a.(y) <- (fst a.(y), snd a.(y) + 1)
    end in
  let unite x y = link (find_set x) (find_set y) in
  let same_p x y = find_set x = find_set y in
  let rec doit i =
    if i < q then begin
      begin match List.map int_of_string (split (read_line ()) ' ') with
      | 0 :: x :: y :: _ -> unite x y
      | 1 :: x :: y :: _ -> print_endline (if same_p x y then "1" else "0")
      | _ -> ()
      end;
      doit (i + 1)
    end in
  doit 0

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

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


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 find_set s x =
  let rec doit x =
    if x <> fst s.(x) then s.(x) <- (doit (fst s.(x)), snd s.(x));
    fst s.(x) in
  doit x

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

let same_p s x y = find_set s x = find_set s y

let solve n q =
  let s = Array.init n (fun i -> (i, 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 :: _ -> unite s x y
      | 1 :: x :: y :: _ -> print_endline (if same_p s x y then "1" else "0")
      | _ -> ()
      end;
      doit (i + 1)
    end in
  doit 0

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


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 solve n q =
  let s = Array.init n (fun i -> i) in
  let rec find u =
    if u = s.(u) then u
    else begin
      s.(u) <- find s.(u);
      s.(u)
    end in
  for _ = 0 to q - 1 do
    match readln () with
    | n :: x :: y :: _ ->
      if n = 0 then s.(find x) <- find y
      else print_endline (if find x = find y then "1" else "0")
    | _ -> assert false
  done

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


let solve (n, q) =
  let s = Array.init n (fun i -> i) in
  let rec find u =
    if u = s.(u) then u
    else begin
      s.(u) <- find s.(u);
      s.(u)
    end in
  for _ = 0 to q - 1 do
    let (n, x, y) = Scanf.scanf "%d %d %d " (fun n x y -> (n, x, y)) in
    if n = 0 then s.(find x) <- find y
    else print_endline (if find x = find y then "1" else "0")
  done

let () = Scanf.scanf "%d %d " (fun n q -> (n, q)) |> solve


open Printf
open Scanf

module type Monoid = sig
    type t
    val append : t -> t -> t
    val default : t
end

module Segtree(M : Monoid) = struct
    type elt = M.t
    type t = Leaf of elt | Node of t * elt * t * int

    let value_of = function
        | Leaf x -> x
        | Node(_, x, _, _) -> x

    let size = function
        | Leaf _ -> 1
        | Node(_, _, _, n) -> n

    let rec range_query a b = function
        | Leaf x -> if a <= 0 && 1 <= b then x else M.default
        | Node(lch, x, rch, n) ->
                if a <= 0 && n <= b then x
                else if b <= 0 || n <= a then M.default
                else
                    let l_size = size lch in
                    M.append (range_query a b lch) (range_query (a - l_size) (b - l_size) rch)

    let rec updated k x = function
        | Leaf _ -> Leaf x
        | Node(lch, _, rch, n) ->
                if k < size lch then
                    let new_lch = updated k x lch in
                    Node(new_lch, M.append (value_of new_lch) (value_of rch), rch, n)
                else
                    let new_rch = updated (k - size lch) x rch in
                    Node(lch, M.append (value_of lch) (value_of new_rch), new_rch, n)

    let rec build n =
        if n <= 1 then Leaf M.default
        else Node(build (n / 2), M.default, build (n - n / 2), n)
end

module RMQ = Segtree(
    struct
        type t = int
        let append = min
        let default = int_of_float (2. ** 31.) - 1
    end)

let _ = scanf "%d %d\n" (fun n q ->
    let rec loop tree = function
        | 0 -> ()
        | i -> scanf "%d %d %d\n" (fun com x y ->
                if com = 0 then loop (RMQ.updated x y tree) (i - 1)
                else begin
                    printf "%d\n" (RMQ.range_query x (y + 1) tree);
                    loop tree (i - 1)
                end) in
    loop (RMQ.build n) q)

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

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

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

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


open Printf
open Scanf

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

Range Update Query (RUQ)

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

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

find(i): output the value of ai.

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

Input

n q
query1
query2
:
queryq

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

0 s t x

or

1 i

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

Output

For each find operation, print the value.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

0 ≤ s ≤ t < n

0 ≤ i < n

0 ≤ x < 231−1

Sample Input 1

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

Sample Output 1

1
3

Sample Input 2

1 3
1 0
0 0 0 5
1 0

Sample Output 2

2147483647
5


open Printf
open Scanf

type ap = {a:int; p:int}

let () =
  let n, q = scanf "%d %d " (fun a b -> (a, b)) in
  let st = Array.make (4*n) {a=0; p=0} in
  let add s t x =
    let rec iter k l r =
      if r <= s || t <= l then ()
      else
        if s <= l && r <= t then
          st.(k) <- {st.(k) with a = st.(k).a + x}
        else
          begin
            let v = (min t r - max s l) * x in
            st.(k) <- {st.(k) with p = st.(k).p + v};
            let m = (l + r) / 2 in
            iter (2 * k) l m;
            iter (2 * k + 1) m r
          end
    in iter 1 0 n
  in
  let get_sum s t =
    let rec iter k l r =
      if r <= s || t <= l then 0
      else
        if s <= l && r <= t then
          (r - l) * st.(k).a + st.(k).p
        else
          let m = (l + r) / 2 in
          (min t r - max s l) * st.(k).a +
            iter (2 * k) l m + iter (2 * k + 1) m r
    in iter 1 0 n
  in
  let rec iter u =
    if u = 0 then ()
    else
      begin
        (let com = scanf "%d " (fun a -> a) in
         if com = 0 then
           let s, t, x = scanf "%d %d %d " (fun a b c -> (a-1, b, c)) in
           add s t x
         else
           let s, t = scanf "%d %d " (fun a b -> (a-1, b)) in
           get_sum s t |> printf "%d\n");
        iter (u-1)
      end
  in
  iter q

RSQ and RAQ

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

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

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

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

Input

n q
query1
query2
:
queryq

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

0 s t x

or

1 s t

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

Output

For each getSum operation, print the sum;

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

1 ≤ s ≤ t ≤ n

0 ≤ x < 1000

Sample Input 1

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

Sample Output 1

4
8

Sample Input 2

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

Sample Output 2

0
4


module ArrayL = ArrayLabels
module ListL = ListLabels

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

let max_num = 1_000_000_000

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

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

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

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

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

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

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

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

let (v,e,r) = scan "%d %d %d" tuple3
let ls = scan_lines e "%d %d %d" tuple3
let edges =
  let arr = Array.make v [] in
  ListL.iter ls ~f:(fun (s,t,d)->
      arr.(s) <- (t,d)::arr.(s));
  arr

let dists = Array.make v max_num
let visited = Array.make v false

module Heap = Set.Make(struct
    type t = int*int
    let compare (x0, y0) (x1,y1) =
      match compare y0 y1 with
      | 0 -> compare x0 x1
      | c -> c
  end)

let rec solve h =
  if Heap.is_empty h then ()
  else
    let (t, dist) = Heap.min_elt h in
    if visited.(t) then solve @@ Heap.remove (t, dist) h
    else
      begin
        visited.(t) <- true; dists.(t) <- dist;
        solve @@ ListL.fold_left edges.(t)
          ~init:(Heap.remove (t, dist) h) ~f:(fun h (s, d) ->
              if not visited.(s) then Heap.add (s, dists.(t) + d) h
              else h)
      end

let () =
  solve @@ (Heap.empty |> Heap.add (r,0));
  ArrayL.iter dists ~f:(fun v ->
      if v = max_num then print_string "INF\n"
      else Printf.printf "%d\n" v)

Single Source Shortest Path

For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path).

Input

An edge-weighted graph G (V, E) and the source r.

|V| |E| r
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1

|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the source of the graph.

si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.

Output

Print the costs of SSSP in the following format.

c0
c1
:
c|V|-1

The output consists of |V| lines. Print the cost of the shortest path from the source r to each vertex 0, 1, ... |V|-1 in order. If there is no path from the source to a vertex, print INF.

Constraints

1 ≤ |V| ≤ 100000

0 ≤ di ≤ 10000

0 ≤ |E| ≤ 500000

There are no parallel edges

There are no self-loops

Sample Input 1

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

Sample Output 1

0
1
3
4

Sample Input 2

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

Sample Output 2

3
0
2
INF


module type SEMIRING =
sig
	type t
	val add : t -> t -> t
	val mul : t -> t -> t
	val unit : t
	val zero : t

	val debug : t -> string
end

module type VECT =
	functor (T : SEMIRING) ->
		sig
			type t
			val zero : int -> t
			val list2vect : (T.t list) -> t
			val vect2list : t -> (T.t list)
			val add : t -> t -> t
			val dot : t -> t -> T.t

			val debug : t -> string
		end

module Vect : VECT =
	functor (T : SEMIRING) -> struct
		type t = (T.t list)
		let list2vect xs = xs
		let vect2list xs = xs
		let rec zero n = if n = 0 then [] else T.zero :: zero (n-1)

		let fzip f a b = List.map (fun (x,y) -> f x y) (List.combine a b)
		let add a b = fzip T.add a b
		let dot a b = List.fold_left T.add T.zero (fzip T.mul a b)

		let debug v = Printf.sprintf "[%s]" (String.concat "; " (List.map T.debug v))

	end

module type MAT =
	functor (T : SEMIRING) ->
		sig
			type t
			val unit : int -> t
			val zero : int -> t
			val trans : t -> t (* ??¢??? *)
			val add : t -> t -> t
			val mul : t -> t -> t
			val list2mat : (T.t list) list -> t
			val mat2list : t -> (T.t list) list
			val vect2mat : Vect(T).t -> t

			val debug : t -> string
		end

module IntSemiring =
struct
	type t = int
	let add a b = a + b
	let mul a b = a * b
	let unit = 1
	let zero = 0

	let debug v = Printf.sprintf "%d" v
end

module BoolSemiring =
struct
	type t = bool
	let add a b = a <> b
	let mul a b = a && b
	let unit = true
	let zero = false

	let debug v = if v then "true" else "false"
end

type tropical = Int of int | Inf

module TropicalSemiring =
struct
	type t = tropical
	let add a b =
		match a with
		| Inf -> b
		| Int ia ->
			match b with
			| Inf -> a
			| Int ib -> Int (min ia ib)
	let mul a b =
		match a with
		| Inf -> Inf
		| Int ia ->
			match b with
			| Inf -> Inf
			| Int ib -> Int (ia + ib)

	let unit = Int 0
	let zero = Inf

	let debug v =
		match v with
		| Inf -> "INF"
		| Int a -> Printf.sprintf "%d" a
end

module Mat : MAT =
	functor (T : SEMIRING) -> struct
		module Vt = Vect(T)
		type t = Vt.t list
		let fzip f a b = List.map (fun (x,y) -> f x y) (List.combine a b)
		let trans v =
			let vt = List.map Vt.vect2list v in
			let rec trans_sub a =
				match a with
				| [] -> []
				| x :: xs ->
					if x = [] then [] else
					(Vt.list2vect (List.map List.hd a)) :: trans_sub (List.map List.tl a) in
			trans_sub vt
		let add a b = fzip Vt.add a b
		let mul a b =
			let tb = trans b in
			let rec mul_sub va vb =
				match va with
				| [] -> []
				| x :: xs -> (Vt.list2vect (List.map (fun t -> Vt.dot x t) vb)) :: (mul_sub xs vb) in
			mul_sub a tb
		let zero n =
			let rec zero_sub nn = if nn = 0 then [] else Vt.zero n :: (zero_sub (nn-1))
				in zero_sub n
		let unit n =
			let rec onehot nn x =
				if nn = 0 then [] else
					(if x = nn then T.unit else T.zero) :: (onehot (nn-1) x) in
			let rec unit_sub a =
				if a = 0 then [] else
					(Vt.list2vect (onehot n a)) :: (unit_sub (a-1)) in
			unit_sub n

		let list2mat v = List.map Vt.list2vect v
		let mat2list v = List.map Vt.vect2list v
		let vect2mat v = [v]

		let debug v = Printf.sprintf "[\n%s]" (String.concat ";\n" (List.map Vt.debug v))

	end

module TropicalMat = Mat(TropicalSemiring)

let _ =
	let (n,m) = Scanf.scanf "%d %d\n" (fun a b -> (a,b)) in
	let v = (Array.make_matrix n n Inf) in
	let _ =
		for i = 0 to (n-1) do
			Array.set v.(i) i (Int 0)
		done;
		for i = 0 to (m-1) do
			let (s,t,d) = Scanf.scanf "%d %d %d\n" (fun a b c -> (a,b,c)) in
			Array.set v.(s) t (Int d)
		done in
	let mat = TropicalMat.list2mat (Array.to_list (Array.map Array.to_list v)) in
(*
	let _ = (print_string (TropicalMat.debug mat)) in
*)
	let rec matpow x y b =
		if y = 1 then b else
			let tx = matpow x (y/2) b in
			let ttx = TropicalMat.mul tx tx in
			if y mod 2 = 1 then TropicalMat.mul ttx b else ttx in
	let ansma = (matpow mat n mat) in
(*
	let _ = (print_string (TropicalMat.debug ansma)) in
*)
	let ans = Array.of_list (List.map Array.of_list (TropicalMat.mat2list ansma)) in
	let ok = ref true in
	let _ =
		for i = 0 to (n-1) do
			match ans.(i).(i) with
			| Inf -> ok := false
			| Int x -> ok := (!ok) && (x >= 0)
		done in
	if not !ok then Printf.printf "NEGATIVE CYCLE\n" else
		for i = 0 to (n-1) do
			for j = 0 to (n-1) do
				Printf.printf "%s%c" (TropicalSemiring.debug ans.(i).(j)) (if j = (n-1) then '\n' else ' ')
			done
		done

All Pairs Shortest Path

Input

An edge-weighted graph G (V, E).

|V| |E|
s0 t0 d0
s1 t1 d1
:
s|E|-1 t|E|-1 d|E|-1

|V| is the number of vertices and |E| is the number of edges in G. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively.

si and ti represent source and target vertices of i-th edge (directed) and di represents the cost of the i-th edge.

Output

If the graph contains a negative cycle (a cycle whose sum of edge costs is a negative value), print

NEGATIVE CYCLE

in a line.

Otherwise, print

D0,0 D0,1 ... D0,|V|-1
D1,0 D1,1 ... D1,|V|-1
:
D|V|-1,0 D1,1 ... D|V|-1,|V|-1

The output consists of |V| lines. For each ith line, print the cost of the shortest path from vertex i to each vertex j (j = 0, 1, ... |V|-1) respectively. If there is no path from vertex i to vertex j, print "INF". Print a space between the costs.

Constraints

1 ≤ |V| ≤ 100

0 ≤ |E| ≤ 9900

-2 × 107 ≤ di ≤ 2 × 107

There are no parallel edges

There are no self-loops

Sample Input 1

4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 7

Sample Output 1

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

Sample Input 2

4 6
0 1 1
0 2 -5
1 2 2
1 3 4
2 3 1
3 2 7

Sample Output 2

0 1 -5 -4
INF 0 2 3
INF INF 0 1
INF INF 7 0

Sample Input 3

4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 -7

Sample Output 3

NEGATIVE CYCLE


let rec f?(n=read_int())i=if n>0then f(Printf.printf"Case %d: %d
"i n;i+1);;f 1

Print Test Cases

In the online judge system, a judge file may include multiple datasets to check whether the submitted program outputs a correct answer for each test case. This task is to practice solving a problem with multiple datasets.

Write a program which reads an integer x and print it as is. Note that multiple datasets are given for this problem.

Input

The input consists of multiple datasets. Each dataset consists of an integer x in a line.

The input ends with an integer 0. You program should not process (print) for this terminal symbol.

Output

For each dataset, print x in the following format:

Case i: x

where i is the case number which starts with 1. Put a single space between "Case" and i. Also, put a single space between ':' and x.

Constraints

1 ≤ x ≤ 10000

The number of datasets ≤ 10000

Sample Input

3
5
11
7
8
19
0

Sample Output

Case 1: 3
Case 2: 5
Case 3: 11
Case 4: 7
Case 5: 8
Case 6: 19


let r()=List.map int_of_string(Str.split(Str.regexp" ")(read_line()))open Array;;match r()with[n;m;l]->(let($)s t=let a=make_matrix s t 0in for i=0to s-1do let x=of_list(r())in for j=0to t-1do a.(i).(j)<-x.(j)done done;a in let a=n$m and b=m$l in for i=0to n-1do for j=0to l-1do let c=ref 0in for k=0to m-1do c:=!c+a.(i).(k)*b.(k).(j)done;Printf.printf(if j=0then"%d"else" %d")!c done;print_newline()done)|_->()

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

Matrix Multiplication

Write a program which reads a $n \times m$ matrix $A$ and a $m \times l$ matrix $B$, and prints their product, a $n \times l$ matrix $C$. An element of matrix $C$ is obtained by the following formula:

\[
c_{ij} = \sum_{k=1}^m a_{ik}b_{kj}
\]

where $a_{ij}$, $b_{ij}$ and $c_{ij}$ are elements of $A$, $B$ and $C$ respectively.

Input

In the first line, three integers $n$, $m$ and $l$ are given separated by space characters

In the following lines, the $n \times m$ matrix $A$ and the $m \times l$ matrix $B$ are given.

Output

Print elements of the $n \times l$ matrix $C$ ($c_{ij}$). Print a single space character between adjacent elements.

Constraints

$1 \leq n, m, l \leq 100$

$0 \leq a_{ij}, b_{ij} \leq 10000$

Sample Input

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

Sample Output

1 8 5
0 9 6
4 23 14

Note

      解説


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 cls =
    let v0 = g |> A.findi (fun v -> not @@ G.getd g v) in
    G.setdi g v0 true;
    (* puti v0; *)
    let cls_next = g |> G.frontier (fun v opnb g ->
      opnb |> Ss.iter (fun w -> G.setdi g w true); true
      ) (Ss.sing v0) cls in
    (* print_list @@ Ss.to_list cls_next; *)
    if Ss.size cls_next = n then (Ss.add v0 rvs)
    else decomp (Ss.add v0 rvs) cls_next
  in

  let rvs = decomp Ss.empty 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).


module type LazySegtreeType = sig
    type s
    type f
    type t

    val make     : int -> t
    val of_array : s array -> t
    val set      : t -> int -> s -> unit
    val get      : t -> int -> s
    val prod     : t -> int -> int -> s
    val all_prod : t -> s
    val apply1   : t -> int -> f -> unit
    val apply    : t -> int -> int -> f -> unit
    val max_right: t -> int -> (s -> bool) -> int
    val min_left : t -> int -> (s -> bool) -> int
end

module type LazySegtreeParam = sig
    type s
    type f

    val op         : s -> s -> s
    val e          : s
    val mapping    : f -> s -> s
    val composition: f -> f -> f
    val id         : f
end

module LazySegtree = struct
    module Make(LSP: LazySegtreeParam) :
        LazySegtreeType with type s = LSP.s and
                             type f = LSP.f = struct
        type s = LSP.s
        type f = LSP.f
        type t = int * int * int * s array * f array

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

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

        let all_apply (n, log, size, d, lz) k f =
            d.(k) <- LSP.mapping f d.(k);
            if k < size then lz.(k) <- LSP.composition f lz.(k)

        let push ((n, log, size, d, lz) as lst) k =
            all_apply lst (2 * k)     lz.(k);
            all_apply lst (2 * k + 1) lz.(k);
            lz.(k) <- LSP.id

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

        let make n = of_array (Array.make n LSP.e)

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

        let get ((n, log, size, d, lz) as lst) p =
            let p = p + size in
            for i = log downto 1 do push lst (p lsr i) done;
            d.(p)

        let prod ((n, log, size, d, lz) as lst) l r =
            if l = r then LSP.e else (
                let l = l + size in
                let r = r + size in
                for i = log downto 1 do
                    if (l lsr i) lsl i <> l then push lst (l lsr i);
                    if (r lsr i) lsl i <> r then push lst (r lsr i);
                done;

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

        let all_prod (n, log, size, d, lz) = d.(1)

        let apply1 ((n, log, size, d, lz) as lst) p f =
            let p = p + size in
            for i = log downto 1 do push lst (p lsr i) done;
            d.(p) <- LSP.mapping f d.(p);
            for i = 1 to log do update d (p lsr i) done

        let apply ((n, log, size, d, lz) as lst) l r f =
            if l <> r then (
                let l = l + size in
                let r = r + size in
                for i = log downto 1 do
                    if (l lsr i) lsl i <> l then push lst (l lsr i);
                    if (r lsr i) lsl i <> r then push lst ((r - 1) lsr i);
                done;

                let rec loop l r =
                    if l < r then (
                        let l = if l land 1 = 0 then l else (all_apply lst l       f; l + 1) in
                        let r = if r land 1 = 0 then r else (all_apply lst (r - 1) f; r - 1) in
                        loop (l lsr 1) (r lsr 1)
                    )
                in
                loop l r;

                for i = 1 to log do
                    if (l lsr i) lsl i <> l then update d (l lsr i);
                    if (r lsr i) lsl i <> r then update d ((r - 1) lsr i);
                done
            )

        let max_right ((n, log, size, d, lz) as lst) l g =
            if l = n then n else (
                let l = l + size in
                for i = log downto 1 do push lst (l lsr i) done;
                let rec loop l sm =
                    let l =
                        let rec div2 l =
                            if l mod 2 = 0 then div2 (l lsr 1) else l
                        in
                        div2 l
                    in
                    if not (g (LSP.op sm d.(l))) then (
                        let rec loop2 l sm =
                            if l < size then (
                                push lst l;
                                let l = 2 * l in
                                if g (LSP.op sm d.(l)) then
                                    loop2 (l + 1) (LSP.op sm d.(l))
                                else loop2 l sm
                            ) else l - size
                        in
                        loop2 l sm
                    ) else (
                        let sm = LSP.op sm d.(l) in
                        let l = l + 1 in
                        if l land (-l) <> l then loop l sm else n
                    )
                in
                loop l LSP.e
            )

        let min_left ((n, log, size, d, lz) as lst) r g =
            if r = 0 then 0 else (
                let r = r + size in
                for i = log downto 1 do push lst ((r - 1) lsr i) done;
                let rec loop r sm =
                    let r =
                        let rec div2 r =
                            if r > 1 && r mod 2 = 1 then div2 (r lsr 1) else r
                        in
                        div2 (r - 1)
                    in
                    if not (g (LSP.op d.(r) sm)) then (
                        let rec loop2 r sm =
                            if r < size then (
                                push lst r;
                                let r = 2 * r + 1 in
                                if g (LSP.op d.(r) sm) then
                                    loop2 (r - 1) (LSP.op d.(r) sm)
                                else loop2 r sm
                            ) else r + 1 - size
                        in
                        loop2 r sm
                    ) else (
                        let sm = LSP.op d.(r) sm in
                        if r land (-r) <> r then loop r sm else 0
                    )
                in
                loop r LSP.e
            )
    end
end;;
Scanf.scanf "%d %d" (fun n q ->
    let z = 998244353 in
    let ten = Array.make n 1 in
    let one = Array.make n 0 in
    for i = 1 to n - 1 do ten.(i) <- (ten.(i - 1) * 10) mod z done;
    for i = 1 to n - 1 do one.(i) <- (one.(i - 1) * 10 + 1) mod z done;
    let module ST = LazySegtree.Make (struct
        type s = int * int
        let op (ll, lv) (rl, rv) = ll + rl, (lv * ten.(rl) + rv) mod z
        let e = 0, 0
        type f = int
        let mapping f ((sl, sv) as s) = if f = 0 then s else sl, (one.(sl) * f) mod z
        let composition l r = if l = 0 then r else l
        let id = 0
    end)
        in
    let seg = ST.of_array (Array.make n (1, 1)) in
    for i = 1 to q do
        Scanf.scanf " %d %d %d" (fun l r d ->
            ST.apply seg (l - 1) r d;
            let (_, v) = ST.all_prod seg in
            Printf.printf "%d\n" v
        )
    done
)

Score : 500 points

Problem Statement

You have a string S of length N.
Initially, all characters in S are 1s.

You will perform queries Q times.
In the i-th query, you are given two integers L_i, R_i and a character D_i (which is a digit).
Then, you must replace all characters from the L_i-th to the R_i-th (inclusive) with D_i.

After each query, read the string S as a decimal integer, and print its value modulo 998,244,353.

Constraints

1 \leq N, Q \leq 200,000

1 \leq L_i \leq R_i \leq N

1 \leq D_i \leq 9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
L_1 R_1 D_1
:
L_Q R_Q D_Q

Output

Print Q lines.
In the i-th line print the value of S after the i-th query, modulo 998,244,353.

Sample Input 1

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

Sample Output 1

11222211
77772211
77333333
72333333
72311333

Sample Input 2

200000 1
123 456 7

Sample Output 2

641437905

Don't forget to take the modulo.


open Printf
open Scanf

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

let g n =
  let m = int_of_float (sqrt (float_of_int n)) in
  let rec loop count k =
    if k>m then
      if m * m = n then
        2 * count - 1
      else
        2 * count
    else if n mod k = 0 then
      loop (count+1) (k+1)
    else
      loop count (k+1)
  in
  loop 0 1

let f () =
  let n = input_int () in
  let rec loop tot c =
    if c = n then
      tot
    else
      loop (tot + g (n - c)) (c+1)
  in
  loop 0 1

let () =
  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" @@ fun x -> Printf.printf "%d\n" @@ if  x = 0 then 1 else 0

Score : 100 points

Problem Statement

Given is an integer x that is greater than or equal to 0, and less than or equal to 1.
Output 1 if x is equal to 0, or 0 if x is equal to 1.

Constraints

0 \leq x \leq 1

x is an integer

Input

Input is given from Standard Input in the following format:

x

Output

Print 1 if x is equal to 0, or 0 if x is equal to 1.

Sample Input 1

1

Sample Output 1

0

Sample Input 2

0

Sample Output 2

1


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)


Scanf.scanf "%d %d %d %d" (fun a b c d ->
    let l1 = if a <= 0 && 0 <= b then [| a; 0; b |] else [| a; a; b |] in
    let l2 = if c <= 0 && 0 <= d then [| c; 0; d |] else [| c; c; d |] in

    let rec loop_i i acc =
        let rec loop_j j acc =
            if j = 3 then loop_i (i + 1) acc else
                loop_j (j + 1) (max acc (l1.(i) * l2.(j)))
        in
        if i = 3 then acc else loop_j 0 acc
    in
    loop_i 0 min_int |> Printf.printf "%d\n"
)

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


Scanf.scanf "%d" (fun n ->
    let xy = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun x y -> x, y)) in

    let calc f =
        Array.sort f xy;
        let x0, y0 = xy.(0) in
        let rec loop i acc =
            if i = n then acc else
                let x1, y1 = xy.(i) in
                let dist = abs (x1 - x0) + abs (y1 - y0) in
                loop (i + 1) (max acc dist)
        in
        let d1 = loop 0 0 in

        let x0, y0 = xy.(n - 1) in
        let rec loop i acc =
            if i = n then acc else
                let x1, y1 = xy.(i) in
                let dist = abs (x1 - x0) + abs (y1 - y0) in
                loop (i + 1) (max acc dist)
        in
        let d2 = loop 0 0 in
        max d1 d2
     in

    let m1 = calc (fun (x0, y0) (x1, y1) -> compare ( x0,  y0) ( x1,  y1)) in
    let m2 = calc (fun (x0, y0) (x1, y1) -> compare ( x0, -y0) ( x1, -y1)) in
    let m3 = calc (fun (x0, y0) (x1, y1) -> compare ( y0,  x0) ( y1,  x1)) in
    let m4 = calc (fun (x0, y0) (x1, y1) -> compare ( y0, -x0) ( y1, -x1)) in

    Printf.printf "%d\n" @@ max (max m1 m2) (max m3 m4)
)

Score : 500 points

Problem Statement

There are N points on the 2D plane, i-th of which is located on (x_i, y_i).
There can be multiple points that share the same coordinate.
What is the maximum possible Manhattan distance between two distinct points?

Here, the Manhattan distance between two points (x_i, y_i) and (x_j, y_j) is defined by |x_i-x_j| + |y_i-y_j|.

Constraints

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

1 \leq x_i,y_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print the answer.

Sample Input 1

3
1 1
2 4
3 2

Sample Output 1

4

The Manhattan distance between the first point and the second point is |1-2|+|1-4|=4, which is maximum possible.

Sample Input 2

2
1 1
1 1

Sample Output 2

0


Scanf.scanf "%d" (fun n ->
    let a = Array.make (n + 1) 0 in
    let b = Array.make (n + 1) 0 in
    let bb = Array.make n 0 in
    let module S = Set.Make (struct type t = int * int let compare = compare end) in
    for i = 1 to n do Scanf.scanf " %d" (fun j -> a.(j) <- a.(j) + 1) done;
    for i = 1 to n do Scanf.scanf " %d" (fun j -> b.(j) <- b.(j) + 1; bb.(i - 1) <- j) done;

    let rec check i =
        if i > n then true else if a.(i) + b.(i) > n then false else check (i + 1)
    in
    if check 1 then (
        let c = Array.make (n + 1) 0 in
        let d = Array.make (n + 1) 0 in
        for i = 1 to n do
            c.(i) <- c.(i - 1) + a.(i);
            d.(i) <- d.(i - 1) + b.(i);
        done;
        let rec loop i mx =
            if i > n then mx else loop (i + 1) (max mx (c.(i) - d.(i - 1)))
        in
        let x = loop 1 0 in
        print_endline "Yes";
        for i = 0 to n - 1 do
            Printf.printf "%d " bb.((i - x + n) mod n)
        done;
        print_newline ()
    ) else print_endline "No"
)

Score : 600 points

Problem Statement

Given are two sequences A and B, both of length N.
A and B are each sorted in the ascending order.
Check if it is possible to reorder the terms of B so that for each i (1 \leq i \leq N) A_i \neq B_i holds, and if it is possible, output any of the reorderings that achieve it.

Constraints

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

1\leq A_i,B_i \leq N

A and B are each sorted in the ascending order.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 \cdots A_N
B_1 B_2 \cdots B_N

Output

If there exist no reorderings that satisfy the condition, print No.

If there exists a reordering that satisfies the condition, print Yes on the first line.
After that, print a reordering of B on the second line, separating terms with a whitespace.

If there are multiple reorderings that satisfy the condition, you can print any of them.

Sample Input 1

6
1 1 1 2 2 3
1 1 1 2 2 3

Sample Output 1

Yes
2 2 3 1 1 1

Sample Input 2

3
1 1 2
1 1 3

Sample Output 2

No

Sample Input 3

4
1 1 2 3
1 2 3 3

Sample Output 3

Yes
3 3 1 2


Scanf.scanf "%d" (fun n ->
    let a = Array.make (n + 1) 0 in
    let b = Array.make (n + 1) 0 in
    let bb = Array.make n 0 in
    let module S = Set.Make (struct type t = int * int let compare = compare end) in
    for i = 1 to n do Scanf.scanf " %d" (fun j -> a.(j) <- a.(j) + 1) done;
    for i = 1 to n do Scanf.scanf " %d" (fun j -> b.(j) <- b.(j) + 1; bb.(i - 1) <- j) done;

    let rec check i =
        if i > n then true else if a.(i) + b.(i) > n then false else check (i + 1)
    in
    if check 1 then (
        let c = Array.make (n + 1) 0 in
        let d = Array.make (n + 1) 0 in
        for i = 1 to n do
            c.(i) <- c.(i) + a.(i);
            d.(i) <- d.(i) + b.(i);
        done;
        let rec loop i mx =
            if i > n then mx else loop (i + 1) (max mx (c.(i) - d.(i - 1)))
        in
        let x = loop 1 0 in
        print_endline "Yes";
        for i = 0 to n - 1 do
            Printf.printf "%d " bb.((i + x) mod n)
        done;
        print_newline ()
    ) else print_endline "No"
)


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

Score : 100 points

Problem Statement

Takahashi is meeting up with Aoki.

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

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

Will he arrive in time?

Constraints

1 \leq D \leq 10000

1 \leq T \leq 10000

1 \leq S \leq 10000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

D T S

Output

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

Sample Input 1

1000 15 80

Sample Output 1

Yes

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

Sample Input 2

2000 20 100

Sample Output 2

Yes

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

Sample Input 3

10000 1 1

Sample Output 3

No

He will be late.


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 d,t,s = rdi3 () in
  putw (s*t >= d)


open Printf
open Scanf

let num () = scanf "%d\n" (fun x -> x)
let num2 () = scanf "%d %d\n" (fun x y -> (x, y))
let num3 () = scanf "%d %d %d\n" (fun x y z -> (x, y, z))

let () =
  let (d, t, s) = num3 () in
  if s * t >= d then
    printf "yes\n"
  else
    printf "no\n"


let () = Scanf.scanf " %s %s" @@ fun s t ->
  Printf.printf "%d\n" @@
  Array.fold_left min max_int @@
  Array.init (String.length s - String.length t + 1) @@ fun i ->
    Array.fold_left ( + ) 0 @@
    Array.init (String.length t) @@ fun j -> if s.[i + j] = t.[j] then 0 else 1

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 Printf
open Scanf

let solve n x t =
  let m = (n + x - 1) / x in m * t

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

Score : 100 points

Problem Statement

Takahashi loves takoyaki - a ball-shaped snack.

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

How long does it take to make N takoyaki?

Constraints

1 \leq N,X,T \leq 1000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X T

Output

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

Sample Input 1

20 12 6

Sample Output 1

12

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

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

Sample Input 2

1000 1 1000

Sample Output 2

1000000

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


(*
 * Vicfred
 * https://atcoder.jp/contests/abc176/tasks/abc176_a
 * implementation
 * *)
Scanf.scanf "%d %d %d" (fun n x t ->
    Printf.printf "%d\n" (((n + x - 1)/ x) * t))