You are going to the beach with the idea to build the greatest sand castle ever in your head! The beach is not as three-dimensional as you could have imagined, it can be decribed as a line of spots to pile up sand pillars. Spots are numbered 1 through infinity from left to right. Obviously, there is not enough sand on the beach, so you brought n packs of sand with you. Let height hi of the sand pillar on some spot i be the number of sand packs you spent on it. You can't split a sand pack to multiple pillars, all the sand from it should go to a single one. There is a fence of height equal to the height of pillar with H sand packs to the left of the first spot and you should prevent sand from going over it. Finally you ended up with the following conditions to building the castle:  h1 ≤ H: no sand from the leftmost spot should go over the fence;  For any  |hi - hi + 1| ≤ 1: large difference in heights of two neighboring pillars can lead sand to fall down from the higher one to the lower, you really don't want this to happen;  : you want to spend all the sand you brought with you. As you have infinite spots to build, it is always possible to come up with some valid castle structure. Though you want the castle to be as compact as possible. Your task is to calculate the minimum number of spots you can occupy so that all the aforementioned conditions hold.

The only line contains two integer numbers n and H (1 ≤ n, H ≤ 1018) — the number of sand packs you have and the height of the fence, respectively.

Print the minimum number of spots you can occupy so the all the castle building conditions hold.

NoteHere are the heights of some valid castles:   n = 5, H = 2, [2, 2, 1, 0, ...], [2, 1, 1, 1, 0, ...], [1, 0, 1, 2, 1, 0, ...]  n = 6, H = 8, [3, 2, 1, 0, ...], [2, 2, 1, 1, 0, ...], [0, 1, 0, 1, 2, 1, 1, 0...] (this one has 5 spots occupied) The first list for both cases is the optimal answer, 3 spots are occupied in them.And here are some invalid ones:  n = 5, H = 2, [3, 2, 0, ...], [2, 3, 0, ...], [1, 0, 2, 2, ...]  n = 6, H = 8, [2, 2, 2, 0, ...], [6, 0, ...], [1, 4, 1, 0...], [2, 2, 1, 0, ...]

module type Idx = sig
  type t
  val to_string: t -> string
  val of_int: int -> t
  val (+): t -> t -> t
  val (-): t -> t -> t
  val (/): t -> t -> t
end

module IdxI64 = struct
  type t = int64
  let to_string = Int64.to_string
  let of_int = Int64.of_int
  let compare = Int64.compare
  let (+) = Int64.add
  let (/) = Int64.div
  let (-) = Int64.sub
  let ( * ) = Int64.mul
  let rem = Int64.rem
end

(* find the first one that makes callback returns true *)
module Bisearch_first (Idx: Idx) = struct
  let perform
      (callback: 'a -> bool)
      ((l, r): Idx.t * Idx.t) (* range is closed *)
      (get: Idx.t -> 'a): Idx.t option =
    let open Idx in
    let rec f (l, r) =
      if l = r
      then if l |> get |> callback then Some l else None
      else
        let m = (l + r) / (Idx.of_int 2) in
        if m |> get |> callback
        then f (l, m)
        else f (m + (Idx.of_int 1), r)
    in
    f (l, r)
end

let option_get (src: 'a option): 'a =
  match src with
  | Some a -> a
  | None -> raise Not_found

let log2 (v: float): float = log v /. log 2.

module Bisearch_first_i64 = Bisearch_first(IdxI64)

let max_capacity (h: int64) (i: int64): int64 =
  let open IdxI64 in
  if h >= i
  then
    if i |> Int64.to_float |> log2 >= 31.
    then Int64.max_int
    else (i * (i + 1L)) / 2L
  else
    let sum = h + i in
    let m = sum / 2L in
    if m |> Int64.to_float |> log2 >= 31.
    then Int64.max_int
    else
      (((m + h - 1L) * (m - h)) / 2L) +
      (((m + 1L) * m) / 2L) +
      (if rem sum 2L = 1L then m else 0L)

(* module Bigint = struct
 *   type t = Big_int.big_int
 *   let of_int = Big_int.big_int_of_int
 *   let to_int = Big_int.int_of_big_int
 *   let of_int64 = Big_int.big_int_of_int64
 *   let to_int64 = Big_int.int64_of_big_int
 *   let (+) = Big_int.add_big_int
 *   let (/) = Big_int.div_big_int
 *   let (-) = Big_int.sub_big_int
 *   let ( * ) = Big_int.mult_big_int
 *   let rem = Big_int.mod_big_int
 *   let compare = Big_int.compare_big_int
 *   let equal = Big_int.eq_big_int
 *   let min = Big_int.min_big_int
 * end
 *
 * let max_capacity_big (h: int64) (i: int64): int64 =
 *   let open Bigint in
 *   let h = of_int64 h in
 *   let i = of_int64 i in
 *   let one = of_int 1 in
 *   let two = of_int 2 in
 *   let ret =
 *     if compare h i >= 0
 *     then (i * (i + one)) / two
 *     else
 *       let sum = h + i in
 *       let m = sum / two in
 *       (((m + h - one) * (m - h)) / two) +
 *       (((m + one) * m) / two) +
 *       (if equal (rem sum two) one then m else (of_int 0)) in
 *   min ret (of_int64 Int64.max_int) |> to_int64 *)

(* 1000000000000000000 1000000000000000000 -> 1414213562 *)
(* 1000000000000000000 1 -> 1999999999 *)
(* 1036191544337895 1 -> 64379858 *)

let compute (n: int64) (h: int64): int64 =
  let f i = (max_capacity h i) >= n in
  Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get

let _ =
  let (n, h) = Scanf.scanf " %Ld %Ld" (fun a b -> (a, b)) in
  compute n h |> IdxI64.to_string |> print_endline

module type Idx = sig
  type t
  val to_string: t -> string
  val of_int: int -> t
  val (+): t -> t -> t
  val (-): t -> t -> t
  val (/): t -> t -> t
end

module IdxI64 = struct
  type t = int64
  let to_string = Int64.to_string
  let of_int = Int64.of_int
  let compare = Int64.compare
  let (+) = Int64.add
  let (/) = Int64.div
  let (-) = Int64.sub
  let ( * ) = Int64.mul
  let rem = Int64.rem
end

(* find the first one that makes callback returns true *)
module Bisearch_first (Idx: Idx) = struct
  let perform
      (callback: 'a -> bool)
      ((l, r): Idx.t * Idx.t) (* range is closed *)
      (get: Idx.t -> 'a): Idx.t option =
    let open Idx in
    let rec f (l, r) =
      if l = r
      then if l |> get |> callback then Some l else None
      else
        let m = (l + r) / (Idx.of_int 2) in
        if m |> get |> callback
        then f (l, m)
        else f (m + (Idx.of_int 1), r)
    in
    f (l, r)
end

let option_get (src: 'a option): 'a =
  match src with
  | Some a -> a
  | None -> raise Not_found

let log2 (v: float): float = log v /. log 2.

module Bisearch_first_i64 = Bisearch_first(IdxI64)

let max_capacity (h: int64) (i: int64): int64 =
  let open IdxI64 in
  if h >= i
  then
    if i |> Int64.to_float |> log2 >= 31.
    then Int64.max_int
    else (i * (i + 1L)) / 2L
  else
    let sum = h + i in
    let m = sum / 2L in
    if m |> Int64.to_float |> log2 >= 31.
    then Int64.max_int
    else
      (((m + h - 1L) * (m - h)) / 2L) +
      (((m + 1L) * m) / 2L) +
      (if rem sum 2L = 1L then m else 0L)

module Bigint = struct
  type t = Big_int.big_int
  let of_int = Big_int.big_int_of_int
  let to_int = Big_int.int_of_big_int
  let of_int64 = Big_int.big_int_of_int64
  let to_int64 = Big_int.int64_of_big_int
  let (+) = Big_int.add_big_int
  let (/) = Big_int.div_big_int
  let (-) = Big_int.sub_big_int
  let ( * ) = Big_int.mult_big_int
  let rem = Big_int.mod_big_int
  let compare = Big_int.compare_big_int
  let equal = Big_int.eq_big_int
  let min = Big_int.min_big_int
end

let max_capacity_big (h: int64) (i: int64): int64 =
  let open Bigint in
  let h = of_int64 h in
  let i = of_int64 i in
  let one = of_int 1 in
  let two = of_int 2 in
  let ret =
    if compare h i >= 0
    then (i * (i + one)) / two
    else
      let sum = h + i in
      let m = sum / two in
      (((m + h - one) * (m - h)) / two) +
      (((m + one) * m) / two) +
      (if equal (rem sum two) one then m else (of_int 0)) in
  min ret (of_int64 Int64.max_int) |> to_int64

let max_capacity_big h i =
  let ret = max_capacity_big h i in
  (* Printf.printf "mc %Ld %Ld -> %Ld\n" h i ret; *)
  ret

let compute (n: int64) (h: int64): int64 =
  let f i = (max_capacity_big h i) >= n in
  (* let f i = let ret = f i in Printf.printf "f %Ld %Ld %b\n" h i ret; ret in *)
  Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get

(* 1000000000000000000 1000000000000000000 -> 1414213562 *)
(* 1000000000000000000 1 -> 1999999999 *)
(* 1036191544337895 1 -> 64379858 *)

let _ =
  (* max_capacity 1000000000000000000L 62500000000000000L |> IdxI64.to_string |> print_endline;
   * max_capacity 1000000000000000000L 1414213562L |> IdxI64.to_string |> print_endline; *)
  Printexc.record_backtrace true;
  let (n, h) = Scanf.scanf " %Ld %Ld" (fun a b -> (a, b)) in
  compute n h |> IdxI64.to_string |> print_endline

module type Idx = sig
  type t
  val to_string: t -> string
  val of_int: int -> t
  val (+): t -> t -> t
  val (-): t -> t -> t
  val (/): t -> t -> t
end

module IdxI64 = struct
  type t = int64
  let to_string = Int64.to_string
  let of_int = Int64.of_int
  let compare = Int64.compare
  let (+) = Int64.add
  let (/) = Int64.div
  let (-) = Int64.sub
  let ( * ) = Int64.mul
  let rem = Int64.rem
end

(* find the first one that makes callback returns true *)
module Bisearch_first (Idx: Idx) = struct
  let perform
      (callback: 'a -> bool)
      ((l, r): Idx.t * Idx.t) (* range is closed *)
      (get: Idx.t -> 'a): Idx.t option =
    let open Idx in
    let rec f (l, r) =
      if l = r
      then if l |> get |> callback then Some l else None
      else
        let m = (l + r) / (Idx.of_int 2) in
        if m |> get |> callback
        then f (l, m)
        else f (m + (Idx.of_int 1), r)
    in
    f (l, r)
end

let option_get (src: 'a option): 'a =
  match src with
  | Some a -> a
  | None -> raise Not_found

module Bisearch_first_i64 = Bisearch_first(IdxI64)

let max_capacity (h: int64) (i: int64): int64 =
  let open IdxI64 in
  if h >= i
  then (i * (i + 1L)) / 2L
  else
    let sum = h + i in
    let m = sum / 2L in
    (((m + h) * (m - h)) / 2L) +
    (((m + 1L) * m) / 2L) +
    (if rem sum 2L = 1L then m else 0L)

let compute (n: int64) (h: int64): int64 =
  let f i = (max_capacity h i) >= n in
  Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get

let _ =
  let (n, h) = Scanf.scanf " %Ld %Ld" (fun a b -> (a, b)) in
  compute n h |> IdxI64.to_string |> print_endline

module type Idx = sig
  type t
  val to_string: t -> string
  val of_int: int -> t
  val (+): t -> t -> t
  val (-): t -> t -> t
  val (/): t -> t -> t
end

module IdxI64 = struct
  type t = int64
  let to_string = Int64.to_string
  let of_int = Int64.of_int
  let compare = Int64.compare
  let (+) = Int64.add
  let (/) = Int64.div
  let (-) = Int64.sub
  let ( * ) = Int64.mul
  let rem = Int64.rem
end

(* find the first one that makes callback returns true *)
module Bisearch_first (Idx: Idx) = struct
  let perform
      (callback: 'a -> bool)
      ((l, r): Idx.t * Idx.t) (* range is closed *)
      (get: Idx.t -> 'a): Idx.t option =
    let open Idx in
    let rec f (l, r) =
      if l = r
      then if l |> get |> callback then Some l else None
      else
        let m = (l + r) / (Idx.of_int 2) in
        if m |> get |> callback
        then f (l, m)
        else f (m + (Idx.of_int 1), r)
    in
    f (l, r)
end

let option_get (src: 'a option): 'a =
  match src with
  | Some a -> a
  | None -> raise Not_found

let log2 (v: float): float = log v /. log 2.

module Bisearch_first_i64 = Bisearch_first(IdxI64)

let max_capacity (h: int64) (i: int64): int64 =
  let open IdxI64 in
  if h >= i
  then
    if i |> Int64.to_float |> log2 >= 31.
    then Int64.max_int
    else (i * (i + 1L)) / 2L
  else
    let sum = h + i in
    let m = sum / 2L in
    (((m + h) * (m - h)) / 2L) +
    (((m + 1L) * m) / 2L) +
    (if rem sum 2L = 1L then m else 0L)

let compute (n: int64) (h: int64): int64 =
  let f i = (max_capacity h i) >= n in
  (* let f i = let ret = f i in Printf.printf "f %Ld %b\n" i ret; ret in *)
  Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get

(* 1000000000000000000 1000000000000000000 -> 1414213562 *)

let _ =
  max_capacity 1000000000000000000L 62500000000000000L |> IdxI64.to_string |> print_endline;
  max_capacity 1000000000000000000L 1414213562L |> IdxI64.to_string |> print_endline;
  let (n, h) = Scanf.scanf " %Ld %Ld" (fun a b -> (a, b)) in
  compute n h |> IdxI64.to_string |> print_endline

module type Idx = sig
  type t
  val to_string: t -> string
  val of_int: int -> t
  val (+): t -> t -> t
  val (-): t -> t -> t
  val (/): t -> t -> t
end

module IdxI64 = struct
  type t = int64
  let to_string = Int64.to_string
  let of_int = Int64.of_int
  let compare = Int64.compare
  let (+) = Int64.add
  let (/) = Int64.div
  let (-) = Int64.sub
  let ( * ) = Int64.mul
  let rem = Int64.rem
end

(* find the first one that makes callback returns true *)
module Bisearch_first (Idx: Idx) = struct
  let perform
      (callback: 'a -> bool)
      ((l, r): Idx.t * Idx.t) (* range is closed *)
      (get: Idx.t -> 'a): Idx.t option =
    let open Idx in
    let rec f (l, r) =
      if l = r
      then if l |> get |> callback then Some l else None
      else
        let m = (l + r) / (Idx.of_int 2) in
        if m |> get |> callback
        then f (l, m)
        else f (m + (Idx.of_int 1), r)
    in
    f (l, r)
end

let option_get (src: 'a option): 'a =
  match src with
  | Some a -> a
  | None -> raise Not_found

let log2 (v: float): float = log v /. log 2.

module Bisearch_first_i64 = Bisearch_first(IdxI64)

let max_capacity (h: int64) (i: int64): int64 =
  let open IdxI64 in
  if h >= i
  then
    if i |> Int64.to_float |> log2 >= 31.
    then Int64.max_int
    else (i * (i + 1L)) / 2L
  else
    let sum = h + i in
    let m = sum / 2L in
    if m |> Int64.to_float |> log2 >= 31.
    then Int64.max_int
    else
      (((m + h) * (m - h)) / 2L) +
      (((m + 1L) * m) / 2L) +
      (if rem sum 2L = 1L then m else 0L)

let compute (n: int64) (h: int64): int64 =
  let f i = (max_capacity h i) >= n in
  (* let f i = let ret = f i in Printf.printf "f %Ld %b\n" i ret; ret in *)
  Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get

(* 1000000000000000000 1000000000000000000 -> 1414213562 *)
(* 1000000000000000000 1 -> 1999999999 *)

let _ =
  (* max_capacity 1000000000000000000L 62500000000000000L |> IdxI64.to_string |> print_endline;
   * max_capacity 1000000000000000000L 1414213562L |> IdxI64.to_string |> print_endline; *)
  let (n, h) = Scanf.scanf " %Ld %Ld" (fun a b -> (a, b)) in
  compute n h |> IdxI64.to_string |> print_endline

module type Idx = sig
  type t
  val to_string: t -> string
  val of_int: int -> t
  val (+): t -> t -> t
  val (-): t -> t -> t
  val (/): t -> t -> t
end

module IdxI64 = struct
  type t = int64
  let to_string = Int64.to_string
  let of_int = Int64.of_int
  let compare = Int64.compare
  let (+) = Int64.add
  let (/) = Int64.div
  let (-) = Int64.sub
  let ( * ) = Int64.mul
  let rem = Int64.rem
end

(* find the first one that makes callback returns true *)
module Bisearch_first (Idx: Idx) = struct
  let perform
      (callback: 'a -> bool)
      ((l, r): Idx.t * Idx.t) (* range is closed *)
      (get: Idx.t -> 'a): Idx.t option =
    let open Idx in
    let rec f (l, r) =
      if l = r
      then if l |> get |> callback then Some l else None
      else
        let m = (l + r) / (Idx.of_int 2) in
        if m |> get |> callback
        then f (l, m)
        else f (m + (Idx.of_int 1), r)
    in
    f (l, r)
end

let option_get (src: 'a option): 'a =
  match src with
  | Some a -> a
  | None -> raise Not_found

let log2 (v: float): float = log v /. log 2.

module Bisearch_first_i64 = Bisearch_first(IdxI64)

let max_capacity (h: int64) (i: int64): int64 =
  let open IdxI64 in
  if h >= i
  then
    if i |> Int64.to_float |> log2 >= 31.
    then Int64.max_int
    else (i * (i + 1L)) / 2L
  else
    let sum = h + i in
    let m = sum / 2L in
    (((m + h) * (m - h)) / 2L) +
    (((m + 1L) * m) / 2L) +
    (if rem sum 2L = 1L then m else 0L)

let compute (n: int64) (h: int64): int64 =
  let f i = (max_capacity h i) >= n in
  (* let f i = let ret = f i in Printf.printf "f %Ld %b\n" i ret; ret in *)
  Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get

(* 1000000000000000000 1000000000000000000 -> 1414213562 *)

let _ =
  (* max_capacity 1000000000000000000L 62500000000000000L |> IdxI64.to_string |> print_endline;
   * max_capacity 1000000000000000000L 1414213562L |> IdxI64.to_string |> print_endline; *)
  let (n, h) = Scanf.scanf " %Ld %Ld" (fun a b -> (a, b)) in
  compute n h |> IdxI64.to_string |> print_endline

module type Idx = sig
  type t
  val to_string: t -> string
  val of_int: int -> t
  val (+): t -> t -> t
  val (-): t -> t -> t
  val (/): t -> t -> t
end

module IdxI64 = struct
  type t = int64
  let to_string = Int64.to_string
  let of_int = Int64.of_int
  let compare = Int64.compare
  let (+) = Int64.add
  let (/) = Int64.div
  let (-) = Int64.sub
  let ( * ) = Int64.mul
  let rem = Int64.rem
end

(* find the first one that makes callback returns true *)
module Bisearch_first (Idx: Idx) = struct
  let perform
      (callback: 'a -> bool)
      ((l, r): Idx.t * Idx.t) (* range is closed *)
      (get: Idx.t -> 'a): Idx.t option =
    let open Idx in
    let rec f (l, r) =
      if l = r
      then if l |> get |> callback then Some l else None
      else
        let m = (l + r) / (Idx.of_int 2) in
        if m |> get |> callback
        then f (l, m)
        else f (m + (Idx.of_int 1), r)
    in
    f (l, r)
end

let option_get (src: 'a option): 'a =
  match src with
  | Some a -> a
  | None -> raise Not_found

let log2 (v: float): float = log v /. log 2.

module Bisearch_first_i64 = Bisearch_first(IdxI64)

let max_capacity (h: int64) (i: int64): int64 =
  let open IdxI64 in
  if h >= i
  then
    if i |> Int64.to_float |> log2 >= 31.
    then Int64.max_int
    else (i * (i + 1L)) / 2L
  else
    let sum = h + i in
    let m = sum / 2L in
    if m |> Int64.to_float |> log2 >= 31.
    then Int64.max_int
    else
      (((m + h - 1L) * (m - h)) / 2L) +
      (((m + 1L) * m) / 2L) +
      (if rem sum 2L = 1L then m else 0L)

module Bigint = struct
  type t = Big_int.big_int
  let of_int = Big_int.big_int_of_int
  let to_int = Big_int.int_of_big_int
  let of_int64 = Big_int.big_int_of_int64
  let to_int64 = Big_int.int64_of_big_int
  let (+) = Big_int.add_big_int
  let (/) = Big_int.div_big_int
  let (-) = Big_int.sub_big_int
  let ( * ) = Big_int.mult_big_int
  let rem = Big_int.mod_big_int
  let compare = Big_int.compare_big_int
  let equal = Big_int.eq_big_int
  let min = Big_int.min_big_int
end

let max_capacity_big (h: int64) (i: int64): int64 =
  let open Bigint in
  let h = of_int64 h in
  let i = of_int64 i in
  let one = of_int 1 in
  let two = of_int 2 in
  let ret =
    if compare h i >= 0
    then (i * (i + one)) / two
    else
      let sum = h + i in
      let m = sum / two in
      (((m + h - one) * (m - h)) / two) +
      (((m + one) * m) / two) +
      (if equal (rem sum two) one then m else (of_int 0)) in
  min ret (of_int64 Int64.max_int) |> to_int64

let max_capacity_big h i =
  let ret = max_capacity_big h i in
  Printf.printf "mc %Ld %Ld -> %Ld\n" h i ret;
  ret

let compute (n: int64) (h: int64): int64 =
  let f i = (max_capacity_big h i) >= n in
  let f i = let ret = f i in Printf.printf "f %Ld %Ld %b\n" h i ret; ret in
  Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get

(* 1000000000000000000 1000000000000000000 -> 1414213562 *)
(* 1000000000000000000 1 -> 1999999999 *)
(* 1036191544337895 1 -> 64379858 *)

let _ =
  (* max_capacity 1000000000000000000L 62500000000000000L |> IdxI64.to_string |> print_endline;
   * max_capacity 1000000000000000000L 1414213562L |> IdxI64.to_string |> print_endline; *)
  Printexc.record_backtrace true;
  let (n, h) = Scanf.scanf " %Ld %Ld" (fun a b -> (a, b)) in
  compute n h |> IdxI64.to_string |> print_endline


The Olympic Games have just started and Federico is eager to watch the marathon race.There will be $$$n$$$ athletes, numbered from $$$1$$$ to $$$n$$$, competing in the marathon, and all of them have taken part in $$$5$$$ important marathons, numbered from $$$1$$$ to $$$5$$$, in the past. For each $$$1\le i\le n$$$ and $$$1\le j\le 5$$$, Federico remembers that athlete $$$i$$$ ranked $$$r_{i,j}$$$-th in marathon $$$j$$$ (e.g., $$$r_{2,4}=3$$$ means that athlete $$$2$$$ was third in marathon $$$4$$$).Federico considers athlete $$$x$$$ superior to athlete $$$y$$$ if athlete $$$x$$$ ranked better than athlete $$$y$$$ in at least $$$3$$$ past marathons, i.e., $$$r_{x,j}<r_{y,j}$$$ for at least $$$3$$$ distinct values of $$$j$$$.Federico believes that an athlete is likely to get the gold medal at the Olympics if he is superior to all other athletes.Find any athlete who is likely to get the gold medal (that is, an athlete who is superior to all other athletes), or determine that there is no such athlete.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1\le n\le 50\,000$$$) — the number of athletes. Then $$$n$$$ lines follow, each describing the ranking positions of one athlete. The $$$i$$$-th of these lines contains the $$$5$$$ integers $$$r_{i,1},\,r_{i,2},\,r_{i,3},\,r_{i,4},\, r_{i,5}$$$ ($$$1\le r_{i,j}\le 50\,000$$$) — the ranking positions of athlete $$$i$$$ in the past $$$5$$$ marathons. It is guaranteed that, in each of the $$$5$$$ past marathons, the $$$n$$$ athletes have distinct ranking positions, i.e., for each $$$1\le j\le 5$$$, the $$$n$$$ values $$$r_{1,j},\, r_{2, j},\, \dots,\, r_{n, j}$$$ are distinct. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$50\,000$$$.

For each test case, print a single integer — the number of an athlete who is likely to get the gold medal (that is, an athlete who is superior to all other athletes). If there are no such athletes, print $$$-1$$$. If there is more than such one athlete, print any of them.

NoteExplanation of the first test case: There is only one athlete, therefore he is superior to everyone else (since there is no one else), and thus he is likely to get the gold medal.Explanation of the second test case: There are $$$n=3$$$ athletes.   Athlete $$$1$$$ is superior to athlete $$$2$$$. Indeed athlete $$$1$$$ ranks better than athlete $$$2$$$ in the marathons $$$1$$$, $$$2$$$ and $$$3$$$.  Athlete $$$2$$$ is superior to athlete $$$3$$$. Indeed athlete $$$2$$$ ranks better than athlete $$$3$$$ in the marathons $$$1$$$, $$$2$$$, $$$4$$$ and $$$5$$$.  Athlete $$$3$$$ is superior to athlete $$$1$$$. Indeed athlete $$$3$$$ ranks better than athlete $$$1$$$ in the marathons $$$3$$$, $$$4$$$ and $$$5$$$. Explanation of the third test case: There are $$$n=3$$$ athletes.   Athlete $$$1$$$ is superior to athletes $$$2$$$ and $$$3$$$. Since he is superior to all other athletes, he is likely to get the gold medal.  Athlete $$$2$$$ is superior to athlete $$$3$$$.  Athlete $$$3$$$ is not superior to any other athlete. Explanation of the fourth test case: There are $$$n=6$$$ athletes.   Athlete $$$1$$$ is superior to athletes $$$3$$$, $$$4$$$, $$$6$$$.  Athlete $$$2$$$ is superior to athletes $$$1$$$, $$$4$$$, $$$6$$$.  Athlete $$$3$$$ is superior to athletes $$$2$$$, $$$4$$$, $$$6$$$.  Athlete $$$4$$$ is not superior to any other athlete.  Athlete $$$5$$$ is superior to athletes $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$, $$$6$$$. Since he is superior to all other athletes, he is likely to get the gold medal.  Athlete $$$6$$$ is only superior to athlete $$$4$$$.

(* Codeforces 1552 B Running for Gold, train  *)

(* you can use either gr or rdln but not both *)
let gr () = Scanf.scanf " %d" (fun i -> i);;
let grf () = Scanf.scanf " %f" (fun i -> i);;
let grl () = Scanf.scanf " %Ld" (fun i -> i);;
let rdln() = input_line stdin;;
(* let spli s = Str.split (Str.regexp " ") s;; *)
let printlisti li = List.iter (fun i -> (print_int i; print_string " ")) li;;
let printarri ai = Array.iter (fun i -> (print_int i; print_string " ")) ai;;
let debug = false;;

(* reading reversed list *)
let rec readlist n acc = match n with
	| 0 -> acc
	| _ -> readlist (n -1) (gr() :: acc);;
let printlisti li = List.iter (fun i -> (print_int i; print_string " ")) li;;
let printlists ls = List.iter (fun s -> (print_string s; print_string " ")) ls;;

(* end my library. below concrete program *)

type player = { ord: int; res: int list };;

let rec count_more cnt al bl = match al with
	| [] -> cnt
	| h :: t ->
		let ncnt = if h <(List.hd bl) then (cnt + 1) else cnt in
		count_more ncnt t (List.tl bl);;

let win ap bp =
	let cnta = count_more 0 ap.res bp.res in
	let cntb = count_more 0 bp.res ap.res in
	(cnta > cntb);;

let winner ap bp =
	let cnta = count_more 0 ap.res bp.res in
	let cntb = count_more 0 bp.res ap.res in
	if cnta > cntb then ap
		else bp;;

let rec select_winner w = function
	| [] -> w
	| a :: t ->
			let nw = winner w a in
			select_winner nw t;;

let rec check_winner w pl = match pl with
	| [] -> true
	| a :: t ->
			if (win a w) && (a.ord != w.ord) then false
			else
			  check_winner w t;;

let read_player o =
	let a = readlist 5 [] in
	{ ord=o; res = a};;

let rec read_players lp idx n = match n with
	| 0 -> lp
	| _ -> let p = read_player idx in
					read_players (p :: lp) (idx + 1) (n - 1);;

let do_one () =
    let n = gr() in
    let lp = read_players [] 1 n in
		let w = select_winner (List.hd lp) (List.tl lp) in
		let ans = if check_winner w lp then w.ord else -1 in
    Printf.printf "%d\n" ans;;

let do_all t =
    for i = 1 to t do
        do_one ()
    done;;

let main() =
	let st = rdln () in
	let t = int_of_string st in
	do_all t;;

main();;


Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.

The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.

Print a single integer — the required sum modulo 109 + 7.

NoteThere are three non-empty subsets in the first sample test:,  and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.

open Printf
open Scanf

let p = 1_000_000_007L

let ( %% ) a b = Int64.rem a b
let ( ** ) a b = (Int64.mul a b) %% p
let ( ++ ) a b = (Int64.add a b) %% p
let ( -- ) a b = (Int64.sub a b) ++ p

let long x = Int64.of_int x

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let sum i j f = fold i j (fun i a -> (f i) ++ a) 0L

let read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)

let () =
  let n = read_int () in
  let x = Array.init (n+1) (fun i -> if i=0 then 0L else long (read_int())) in
  Array.sort compare x;

  let pow2 = Array.make (n+1) 1L in

  for i=1 to n do
    pow2.(i) <- 2L ** pow2.(i-1)
  done;

  let part1 = sum 2 n (fun j -> (x.(j) ** pow2.(j-1)) -- x.(j)) in
  let part2 = sum 1 (n-1) (fun i -> (x.(i) ** pow2.(n-i)) -- x.(i)) in

  printf "%Ld\n" (part1 -- part2)


The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index.At the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index.Determine who will win the elections.

The first line of the input contains two integers n, m (1 ≤ n, m ≤ 100) — the number of candidates and of cities, respectively. Each of the next m lines contains n non-negative integers, the j-th number in the i-th line aij (1 ≤ j ≤ n, 1 ≤ i ≤ m, 0 ≤ aij ≤ 109) denotes the number of votes for candidate j in city i. It is guaranteed that the total number of people in all the cities does not exceed 109.

Print a single number — the index of the candidate who won the elections. The candidates are indexed starting from one.

NoteNote to the first sample test. At the first stage city 1 chosen candidate 3, city 2 chosen candidate 2, city 3 chosen candidate 2. The winner is candidate 2, he gained 2 votes.Note to the second sample test. At the first stage in city 1 candidates 1 and 2 got the same maximum number of votes, but candidate 1 has a smaller index, so the city chose candidate 1. City 2 chosen candidate 3. City 3 chosen candidate 1, due to the fact that everyone has the same number of votes, and 1 has the smallest index. City 4 chosen the candidate 3. On the second stage the same number of cities chose candidates 1 and 3. The winner is candidate 1, the one with the smaller index.

let get a'= List.map (int_of_string) (Str.split (Str.regexp " ") (read_line ()));;
let [n; m] = get ();;
let kk = Array.make n 0 and mm = ref 0 and mj = ref 0;;
for i = 1 to m do
	let ins = get () in begin
		mm := (-1);
		for j = 0 to n - 1 do if !mm < List.nth ins j then begin
			mm := List.nth ins j;
			mj := j;
		end	done;
		Array.set kk !mj (kk.(!mj) + 1);
end done;;
mm := 0;;
for j = 0 to n - 1 do if !mm < kk.(j) then begin
	mm := kk.(j);
	mj := j;
end done;;
print_int (!mj + 1);;

let winner a =
  fst (Array.fold_left (fun (i, pos) b -> if b > a.(i) then (pos, pos + 1) else (i, pos + 1)) (0, 0) a)

let () = Scanf.scanf "%d %d\n" (fun n m ->
				(* candidates *)
				let c = Array.make n 0 in
				for i = 1 to m do
				  let e = Array.init n (fun _ -> Scanf.scanf "%d%_c" (fun x -> x)) in
				  let w = winner e in
				  c.(w) <- c.(w) + 1
				done;
				Printf.printf "%d\n" (winner c + 1))

let get a'= List.map (int_of_string) (Str.split (Str.regexp " ") (read_line ()));;
let [n; m] = get ();;
let kk = Array.make n 0 and mm = ref 0 and mj = ref 0;;
for i = 1 to m do
	let ins = get () in begin
		mm := 0;
		for j = 0 to n - 1 do if !mm < List.nth ins j then begin
			mm := List.nth ins j;
			mj := j;
		end	done;
		Array.set kk !mj (kk.(!mj) + 1);
end done;;
mm := 0;;
for j = 0 to n - 1 do if !mm < kk.(j) then begin
	mm := kk.(j);
	mj := j;
end done;;
print_int (!mj + 1);;

let get a'= List.map (int_of_string) (Str.split (Str.regexp " ") (read_line ()));;
let [n; m] = get ();;
let kk = Array.make n 0 and mm = ref 0 and mj = ref 0;;
for i = 1 to m do
	let ins = get () in begin
		mm := (-1);
		for j = 0 to n - 1 do if !mm < List.nth ins j then begin
			mm := List.nth ins j;
			mj := j;
		end	done;
end done;;
mm := 0;;
for j = 0 to n - 1 do if !mm < kk.(j) then begin
	mm := kk.(j);
	mj := j;
end done;;
print_int (!mj + 1);;


One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.

The only line of the input contains one integer n (7 ≤ n ≤ 777) — the number of potential employees that sent resumes.

Output one integer — the number of different variants of group composition.

open Big_int

let (+|) = add_big_int
let (-|) = sub_big_int
let ( *| ) = mult_big_int
let (/|) = div_big_int
let bmod = mod_big_int
let (=|) = eq_big_int
let (/=|) a b = not (a =| b)
let (>|) = gt_big_int
let (<|) = lt_big_int
let (>=|) = ge_big_int
let (<=|) = le_big_int

let n0 = zero_big_int
let n1 = unit_big_int
let n2 = big_int_of_int 2

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let n = big_int_of_int n in
  let res =
    (n -| big_int_of_int 4) *|
	(n -| big_int_of_int 3) *|
	    (n -| big_int_of_int 2) *|
		(n -| big_int_of_int 1) *| n *|
		    (n *| n -| big_int_of_int 4 *| n +| big_int_of_int 37) /|
			big_int_of_int 5040
  in
    Printf.printf "%s\n" (string_of_big_int res)


Stanley defines the beauty of an array $$$a$$$ of length $$$n$$$, which contains non-negative integers, as follows: $$$$$$\sum\limits_{i = 1}^{n} \left \lfloor \frac{a_{i}}{k} \right \rfloor,$$$$$$ which means that we divide each element by $$$k$$$, round it down, and sum up the resulting values.Stanley told Sam the integer $$$k$$$ and asked him to find an array $$$a$$$ of $$$n$$$ non-negative integers, such that the beauty is equal to $$$b$$$ and the sum of elements is equal to $$$s$$$. Help Sam — find any of the arrays satisfying the conditions above.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains integers $$$n$$$, $$$k$$$, $$$b$$$, $$$s$$$ ($$$1 \leq n \leq 10^{5}$$$, $$$1 \leq k \leq 10^{9}$$$, $$$0 \leq b \leq 10^{9}$$$, $$$0 \leq s \leq 10^{18}$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print $$$-1$$$ if such array $$$a$$$ does not exist. Otherwise print $$$n$$$ non-negative integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_{i} \leq 10^{18}$$$) — the answer.

NoteIn the first, the second, the fifth and the sixth test cases of the example it is possible to show that such array does not exist.In the third testcase of the example $$$a = [0, 0, 19]$$$. The sum of elements in it is equal to 19, the beauty of it is equal to $$$\left ( \left \lfloor \frac{0}{6} \right \rfloor + \left \lfloor \frac{0}{6} \right \rfloor + \left \lfloor \frac{19}{6} \right \rfloor \right ) = (0 + 0 + 3) = 3$$$.In the fourth testcase of the example $$$a = [0, 3, 3, 3, 29]$$$. The sum of elements in it is equal to $$$38$$$, the beauty of it is equal to $$$(0 + 0 + 0 + 0 + 7) = 7$$$.

module A = Array
module L = List
module I = Int64
module B = Big_int

module Opt = struct
  let get = function
    | None -> assert false
    | Some v -> v
end

let pf = Printf.printf
let sf = Scanf.scanf
let read_int () = sf " %d" (fun x -> x)

let read_long () = sf " %Ld" (fun x -> x)

let read_array read n = A.init n (fun _ -> read ())

let i_bit x i = (x lsr i) land 1

let () =
  let t = read_int () in

  for _ = 1 to t do
    let n0 = read_int () in
    let k = read_long () in
    let b = read_long () in
    let s = read_long () in
    let one = I.of_int 1 in
    let n = I.of_int n0 in
    let k1 = I.sub k one in
    if (I.mul b k <= s && s <= I.add (I.mul k1 n) (I.mul b k)) then begin
      let a = Array.make n0 I.zero in
      a.(0) <- I.mul b k;
      let sm = ref (I.sub s (I.mul b k)) in
      for i = 0 to n0 - 1 do
        if (!sm >= k1) then begin
          a.(i) <- I.add a.(i) k1;
          sm := I.sub (!sm) k1;
        end else begin
          a.(i) <- I.add a.(i) !sm;
          sm := I.zero;
        end;
      done;

      A.iter (pf "%Ld ") a;
      pf "\n";

    end else pf "-1\n"
  done;


Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms.Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions:   Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units;  Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items.

The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100).

In the single line print a single number — the answer to the problem.

NoteConsider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units.The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units.

let (@@) f x = f x ;;
let (|>) x f = f x ;;
let ident x = x ;;

let char_to_int x = int_of_char x - int_of_char '0' ;;
let int_to_char x = char_of_int (x + int_of_char '0') ;;

module List = struct
  include ListLabels ;;

  let rec iteri i f = function
    | [] -> ()
    | a::l -> f i a; iteri (i + 1) f l

  let iteri ~f l = iteri 0 f l
end
;;

module Array = struct
  include ArrayLabels ;;

  let reduce ~f xs =
    let acc = ref xs.(0) in
    for i = 1 to length xs - 1 do
      acc := f !acc xs.(i)
    done;
    !acc
  ;;
end
;;

module String = struct
  include StringLabels ;;

  let map_to_list ~f ss =
    let res = ref [] in
    iter ss ~f:(fun c -> res := f c :: !res);
    List.rev !res
  ;;

  let of_char_list ss =
    let res = String.create @@ List.length ss in
    List.iteri ss ~f:(fun i c -> res.[i] <- c);
    res
  ;;

  let iteri ~f a =
    for i = 0 to length a - 1 do f i (unsafe_get a i) done
  ;;
end
;;

module Float = struct
  let (+) = (+.)
  let (-) = (-.)
  let ( * ) = ( *. )
  let (/) = (/.)
end
;;

module Int64 = struct
  include Int64
  let (+) = add
  let (-) = sub
  let ( * ) = mul
  let (/) = div
end
;;

let fold_for ?(skip=1) min max ~init ~f =
  let acc = ref init in
  let cur = ref min in
  while !cur < max do
    acc := f !acc !cur;
    cur := !cur + skip;
  done;
  !acc
;;

let iter_for ?(skip=1) min max ~f =
  let cur = ref min in
  while !cur < max do
    f !cur;
    cur := !cur + skip;
  done
;;

let input () =
  let n, l, r, ql, qr = Scanf.scanf "%d %Ld %Ld %Ld %Ld " (fun n l r ql qr -> n, l, r, ql, qr) in
  let arr = Array.create n 0L in
  iter_for 0 n ~f:(fun i ->
    let w = Scanf.scanf "%Ld " ident in
    arr.(i) <- w);
  (n, l, r, ql, qr, arr)
;;

let solve n l r ql qr ws =
  let sum_l = Array.create (n + 1) 0L in
  let sum_r = Array.create (n + 1)
    (Array.fold_left ws ~init:0L ~f:(fun acc i -> Int64.(acc + i * r))) in
  Array.iter sum_l ~f:(Printf.eprintf "%Ld ");
  prerr_endline "";
  Array.iter sum_r ~f:(Printf.eprintf "%Ld ");
  prerr_endline "";
  let (+/) = Int64.(+) in
  let ( */ ) = Int64.( * ) in
  iter_for 1 (n + 1) ~f:(fun i ->
    let (+/) = Int64.(+) in
    let (-/) = Int64.(-) in
    let ( */ ) = Int64.( * ) in
    sum_l.(i) <- sum_l.(i - 1) +/ ws.(i - 1) */ l;
    sum_r.(i) <- sum_r.(i - 1) -/ ws.(i - 1) */ r);
  Array.iter sum_l ~f:(Printf.eprintf "%Ld ");
  prerr_endline "";
  Array.iter sum_r ~f:(Printf.eprintf "%Ld ");
  prerr_endline "";
  fold_for 0 n ~init:(Int64.of_int max_int) ~f:(fun acc i ->
    let nl = i and nr = n - i - 1 in
    let r =
      if nl = nr then
        sum_l.(i) +/ sum_r.(i + 1) +/ min (ws.(i) */ l) (ws.(i) */ r)
      else if nl > nr then
        sum_l.(i) +/ sum_r.(i + 1) +/ ql */ Int64.of_int (nl - nr - 1) +/ min (ws.(i) */ l +/ ql) (ws.(i) */ r)
      else
        sum_l.(i) +/ sum_r.(i + 1) +/ qr */ Int64.of_int (nr - nl - 1) +/ min (ws.(i) */ l) (ws.(i) */ r +/ qr) in
    Printf.eprintf "i = %d, sum = %Ld\n" i r;
    min acc r)
;;

let () =
  let n, l, r, ql, qr, arr = input () in
  Printf.printf "%Ld\n" @@ solve n l r ql qr arr
;;

let (@@) f x = f x ;;
let (|>) x f = f x ;;
let ident x = x ;;

let char_to_int x = int_of_char x - int_of_char '0' ;;
let int_to_char x = char_of_int (x + int_of_char '0') ;;

module List = struct
  include ListLabels ;;

  let rec iteri i f = function
    | [] -> ()
    | a::l -> f i a; iteri (i + 1) f l

  let iteri ~f l = iteri 0 f l
end
;;

module Array = struct
  include ArrayLabels ;;

  let reduce ~f xs =
    let acc = ref xs.(0) in
    for i = 1 to length xs - 1 do
      acc := f !acc xs.(i)
    done;
    !acc
  ;;
end
;;

module String = struct
  include StringLabels ;;

  let map_to_list ~f ss =
    let res = ref [] in
    iter ss ~f:(fun c -> res := f c :: !res);
    List.rev !res
  ;;

  let of_char_list ss =
    let res = String.create @@ List.length ss in
    List.iteri ss ~f:(fun i c -> res.[i] <- c);
    res
  ;;

  let iteri ~f a =
    for i = 0 to length a - 1 do f i (unsafe_get a i) done
  ;;
end
;;

module Float = struct
  let (+) = (+.)
  let (-) = (-.)
  let ( * ) = ( *. )
  let (/) = (/.)
end
;;

module Int64 = struct
  include Int64
  let (+) = add
  let (-) = sub
  let ( * ) = mul
  let (/) = div
end
;;

let fold_for ?(skip=1) min max ~init ~f =
  let acc = ref init in
  let cur = ref min in
  while !cur < max do
    acc := f !acc !cur;
    cur := !cur + skip;
  done;
  !acc
;;

let iter_for ?(skip=1) min max ~f =
  let cur = ref min in
  while !cur < max do
    f !cur;
    cur := !cur + skip;
  done
;;

let input () =
  let n, l, r, ql, qr = Scanf.scanf "%d %d %d %d %d " (fun n l r ql qr -> n, l, r, ql, qr) in
  let arr = Array.create n 0 in
  iter_for 0 n ~f:(fun i ->
    let w = Scanf.scanf "%d " ident in
    arr.(i) <- w);
  (n, l, r, ql, qr, arr)
;;

let solve n l r ql qr ws =
  let sum_l = Array.create (n + 1) 0 in
  let sum_r = Array.create (n + 1) (Array.fold_left ws ~init:0 ~f:(fun acc i -> acc + i * r)) in
  Array.iter sum_l ~f:(Printf.eprintf "%d ");
  prerr_endline "";
  Array.iter sum_r ~f:(Printf.eprintf "%d ");
  prerr_endline "";
  iter_for 1 (n + 1) ~f:(fun i ->
    sum_l.(i) <- sum_l.(i - 1) + ws.(i - 1) * l;
    sum_r.(i) <- sum_r.(i - 1) - ws.(i - 1) * r);
  Array.iter sum_l ~f:(Printf.eprintf "%d ");
  prerr_endline "";
  Array.iter sum_r ~f:(Printf.eprintf "%d ");
  prerr_endline "";
  fold_for 0 n ~init:max_int ~f:(fun acc i ->
    let nl = i and nr = n - i - 1 in
    let r =
      if nl = nr then
        sum_l.(i) + sum_r.(i + 1) + min (ws.(i) * l) (ws.(i) * r)
      else if nl > nr then
        sum_l.(i) + sum_r.(i + 1) + ql * (nl - nr - 1) + min (ws.(i) * l + ql) (ws.(i) * r)
      else
        sum_l.(i) + sum_r.(i + 1) + qr * (nr - nl - 1) + min (ws.(i) * l) (ws.(i) * r + qr) in
    Printf.eprintf "i = %d, sum = %d\n" i r;
    min acc r)
;;

let () =
  let n, l, r, ql, qr, arr = input () in
  Printf.printf "%d\n" @@ solve n l r ql qr arr
;;

let (|>) x f = f x ;;
let (@@) f x = f x ;;

let ident x = x ;;

let char_to_int x = int_of_char x - int_of_char '0' ;;
let int_to_char x = char_of_int (x + int_of_char '0') ;;

module List = struct
  include ListLabels ;;

  let rec iteri i f = function
    | [] -> ()
    | a::l -> f i a; iteri (i + 1) f l

  let iteri ~f l = iteri 0 f l
end
;;

module Array = struct
  include ArrayLabels ;;

  let reduce ~f xs =
    let acc = ref xs.(0) in
    for i = 1 to length xs - 1 do
      acc := f !acc xs.(i)
    done;
    !acc
  ;;
end
;;

module String = struct
  include StringLabels ;;

  let map_to_list ~f ss =
    let res = ref [] in
    iter ss ~f:(fun c -> res := f c :: !res);
    List.rev !res
  ;;

  let of_char_list ss =
    let res = String.create @@ List.length ss in
    List.iteri ss ~f:(fun i c -> res.[i] <- c);
    res
  ;;

  let iteri ~f a =
    for i = 0 to length a - 1 do f i (unsafe_get a i) done
  ;;
end
;;

module Float = struct
  let (+) = (+.)
  let (-) = (-.)
  let ( * ) = ( *. )
  let (/) = (/.)
end
;;

module Int64 = struct
  include Int64
  let (+) = add
  let (-) = sub
  let ( * ) = mul
  let (/) = div
end
;;

let fold_for ?(skip=1) min max ~init ~f =
  let acc = ref init in
  let cur = ref min in
  while !cur < max do
    acc := f !acc !cur;
    cur := !cur + skip;
  done;
  !acc
;;

let iter_for ?(skip=1) min max ~f =
  let cur = ref min in
  while !cur < max do
    f !cur;
    cur := !cur + skip;
  done
;;

let () =
  let n = Scanf.scanf "%d " ident in
  let arr = Array.make_matrix (n + 2) (n + 2) ' ' in
  iter_for 1 (n + 1) ~f:(fun i ->
    iter_for 1 (n + 1) ~f:(fun j ->
      arr.(i).(j) <- Scanf.scanf "%c " ident));
  let memo = Array.make_matrix (n + 2) (n + 2) 0 in
  iter_for 1 (n + 1) ~f:(fun i ->
    iter_for 1 (n + 1) ~f:(fun j ->
      let i = (n + 1) - i in
      let j = (n + 1) - j in
      Printf.eprintf "i, j, c = %d, %d, %c\n" i j arr.(i).(j);
      let d = if arr.(i).(j) = 'a' then 1 else if arr.(i).(j) = 'b' then -1 else 0 in
      if i = n then
        memo.(i).(j) <- memo.(i).(j + 1) + d
      else if j = n then
        memo.(i).(j) <- memo.(i + 1).(j) + d
      else if (i + j) mod 2 = 1 then
        memo.(i).(j) <- max memo.(i + 1).(j) memo.(i).(j + 1) + d
      else
        memo.(i).(j) <- min memo.(i + 1).(j) memo.(i).(j + 1) + d));
  Array.iter memo ~f:(fun x ->
    Array.iter x ~f:(fun k -> Printf.eprintf "%d " k);
    prerr_endline "");
  if memo.(1).(1) = 0 then print_endline "DRAW"
  else if memo.(1).(1) > 0 then print_endline "FIRST"
  else print_endline "SECOND"
;;


You are given two integers $$$n$$$ and $$$m$$$. You have to construct the array $$$a$$$ of length $$$n$$$ consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly $$$m$$$ and the value $$$\sum\limits_{i=1}^{n-1} |a_i - a_{i+1}|$$$ is the maximum possible. Recall that $$$|x|$$$ is the absolute value of $$$x$$$.In other words, you have to maximize the sum of absolute differences between adjacent (consecutive) elements. For example, if the array $$$a=[1, 3, 2, 5, 5, 0]$$$ then the value above for this array is $$$|1-3| + |3-2| + |2-5| + |5-5| + |5-0| = 2 + 1 + 3 + 0 + 5 = 11$$$. Note that this example doesn't show the optimal answer but it shows how the required value for some array is calculated.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^9$$$) — the length of the array and its sum correspondingly.

For each test case, print the answer — the maximum possible value of $$$\sum\limits_{i=1}^{n-1} |a_i - a_{i+1}|$$$ for the array $$$a$$$ consisting of $$$n$$$ non-negative integers with the sum $$$m$$$.

NoteIn the first test case of the example, the only possible array is $$$[100]$$$ and the answer is obviously $$$0$$$.In the second test case of the example, one of the possible arrays is $$$[2, 0]$$$ and the answer is $$$|2-0| = 2$$$.In the third test case of the example, one of the possible arrays is $$$[0, 2, 0, 3, 0]$$$ and the answer is $$$|0-2| + |2-0| + |0-3| + |3-0| = 10$$$.

open Scanf;;

let read () = Scanf.scanf " %d" (fun x -> x) in

let nbTests = read () in
for iTest = 1 to nbTests do
   let nbEntiers = read() in
   let somme = read() in

   if nbEntiers = 1 then
      print_int 0
   else if nbEntiers = 2 then
      print_int somme
   else
      print_string (Int64.to_string (Int64.mul 2L (Int64.of_int somme)))
   ;
   print_newline ()
done;

open Scanf;;

let read () = Scanf.scanf " %d" (fun x -> x) in

let nbTests = read () in
for iTest = 1 to nbTests do
   let nbEntiers = read() in
   let somme = read() in

   if nbEntiers = 1 then
      print_int 0
   else if nbEntiers = 2 then
      print_int somme
   else
      print_int (2 * somme)
   ;
   print_newline ()
done;


Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left.There were $$$n$$$ classes of that subject during the semester and on $$$i$$$-th class professor mentioned some non-negative integer $$$a_i$$$ to the students. It turned out, the exam was to tell the whole sequence back to the professor. Sounds easy enough for those who attended every class, doesn't it?Obviously Mishka didn't attend any classes. However, professor left some clues on the values of $$$a$$$ to help out students like Mishka:   $$$a$$$ was sorted in non-decreasing order ($$$a_1 \le a_2 \le \dots \le a_n$$$);  $$$n$$$ was even;  the following sequence $$$b$$$, consisting of $$$\frac n 2$$$ elements, was formed and given out to students: $$$b_i = a_i + a_{n - i + 1}$$$. Professor also mentioned that any sequence $$$a$$$, which produces sequence $$$b$$$ with the presented technique, will be acceptable.Help Mishka to pass that last exam. Restore any sorted sequence $$$a$$$ of non-negative integers, which produces sequence $$$b$$$ with the presented technique. It is guaranteed that there exists at least one correct sequence $$$a$$$, which produces the given sequence $$$b$$$.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the length of sequence $$$a$$$. $$$n$$$ is always even. The second line contains $$$\frac n 2$$$ integers $$$b_1, b_2, \dots, b_{\frac n 2}$$$ ($$$0 \le b_i \le 10^{18}$$$) — sequence $$$b$$$, where $$$b_i = a_i + a_{n - i + 1}$$$. It is guaranteed that there exists at least one correct sequence $$$a$$$, which produces the given sequence $$$b$$$.

Print $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{18}$$$) in a single line. $$$a_1 \le a_2 \le \dots \le a_n$$$ should be satisfied. $$$b_i = a_i + a_{n - i + 1}$$$ should be satisfied for all valid $$$i$$$.

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

let () =
  let n = gi 0 in let a = iia (n/2L) in
  let res = make (i32 n) 0L in
  let l,r = ref 0L,ref a.(0) in
  iteri (fun i sum ->
    let ll = binary_search !l !r (fun v -> sum-v <= !r) in
    let rr = sum - ll in
    res.(i) <- ll;
    res.(i32 n-$i-$1) <- rr;
    l := ll; r := rr;
  ) a;
  print_array ist res


After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.

The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one.  The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1.

Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.

open Scanf;;
open Printf;;

let rec change list target cur value = (* listのtarget番目をvalueに変えたlistを返す *)
    if cur = target then value::( List.tl list )
    else ( List.hd list )::( change (List.tl list ) target ( cur + 1 ) value );;

let rec init size =
    if size <= 0 then []
    else 0::( init ( size - 1 ) ) ;;

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

let rec solve s i list =
  if i >= ( String.length s ) then 0
  else begin
    if ( 'a' <= s.[i] && s.[i] <= 'z' ) then begin
      solve s ( i + 1 ) ( change list ( ( Char.code s.[i] ) - ( Char.code 'a' ) ) 0 ( 1 + ( List.nth list ( ( Char.code s.[i] ) - ( Char.code 'a' ) ) ) ) )
    end else begin
      if ( List.nth list ( ( Char.code s.[i] ) - ( Char.code 'A' ) ) ) = 0 then begin
        1 + solve s ( i + 1 ) list
      end else begin
        solve s ( i + 1 ) ( change list ( ( Char.code s.[i] ) - ( Char.code 'A' ) ) 0 ( ( List.nth list ( ( Char.code s.[i] ) - ( Char.code 'A' ) ) ) - 1 ) )
      end
    end
  end
;;

let s = scanf "%s\n" ( fun s -> s ) in
  printf "%d\n" ( solve s 0 ( init 26 ) );;

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let a = Array.make 26 0 in
  let res = ref 0 in
    for i = 0 to n - 2 do
      let k = Char.code s.[2 * i] - Char.code 'a' in
	a.(k) <- a.(k) + 1;
	let k = Char.code s.[2 * i + 1] - Char.code 'A' in
	  if a.(k) > 0
	  then a.(k) <- a.(k) - 1
	  else incr res
    done;
    Printf.printf "%d\n" !res;


You are given a 0-1 rectangular matrix. What is the number of squares in it? A square is a solid square frame (border) with linewidth equal to 1. A square should be at least 2 × 2. We are only interested in two types of squares:   squares with each side parallel to a side of the matrix;  squares with each side parallel to a diagonal of the matrix. For example the following matrix contains only one square of the first type: 0000000 0111100 0100100 0100100 0111100The following matrix contains only one square of the second type:00000000010000010100000100000000000Regardless of type, a square must contain at least one 1 and can't touch (by side or corner) any foreign 1. Of course, the lengths of the sides of each square should be equal.How many squares are in the given matrix?

The first line contains integer t (1 ≤ t ≤ 10000), where t is the number of test cases in the input. Then test cases follow. Each case starts with a line containing integers n and m (2 ≤ n, m ≤ 250), where n is the number of rows and m is the number of columns. The following n lines contain m characters each (0 or 1). The total number of characters in all test cases doesn't exceed 106 for any input file.

You should output exactly t lines, with the answer to the i-th test case on the i-th line.

let read_int _ = Scanf.bscanf Scanf.Scanning.stdib " %d" (fun x -> x)
let read_str _ = Scanf.bscanf Scanf.Scanning.stdib " %s" (fun x -> x)
let (|>) x f = f x

let ds = [|0,1; 1,0; 0,-1; -1,0; 1,-1; 1,1; -1,1; -1,-1|]

exception No

let () =
  for cc = 1 to read_int 0 do
    let n = read_int 0 in
    let m = read_int 0 in
    let a = Array.init n read_str in

    let rec dfs i j =
      let s = ref 0 in
      let rec go i j =
        if 0 <= i && i < n && 0 <= j && j < m && a.(i).[j] = '1' then (
          a.(i).[j] <- '2';
          incr s;
          Array.iter (fun (dx,dy) -> go (i+dx) (j+dy)) ds
        )
      in
      go i j;
      !s
    in

    let span i j l u v =
      try
        for d = u to v-1 do
          let x = ref i and y = ref j in
          for k = 0 to l do
            if not (0 <= !x && !x < n && 0 <= !y && !y < m && a.(!x).[!y] = '2') then
              raise No;
            x := !x + fst ds.(d);
            y := !y + snd ds.(d)
          done
        done;
        true
      with No ->
        false
    in

    let ans = ref 0 in
    for i = 0 to n-1 do
      for j = 0 to m-1 do
        if a.(i).[j] = '1' then (
          let s = dfs i j in
          if s mod 4 = 0 && s <= (n-1)*4 then (
            if span i j (s/4) 0 2 && span (i+s/4) (j+s/4) (s/4) 2 4 then
              incr ans;
            if span i j (s/4) 4 6 && span (i+s/2) j (s/4) 6 8 then
              incr ans;
          )
        )
      done
    done;
    Printf.printf "%d\n" !ans
  done

let read_int _ = Scanf.bscanf Scanf.Scanning.stdib " %d" (fun x -> x)
let read_str _ = Scanf.bscanf Scanf.Scanning.stdib " %s" (fun x -> x)
let (|>) x f = f x

let ds = [|0,1; 1,0; 0,-1; -1,0; 1,-1; 1,1; -1,1; -1,-1|]

exception No

let () =
  for cc = 1 to read_int 0 do
    let n = read_int 0 in
    let m = read_int 0 in
    let a = Array.init n read_str in

    let rec dfs i j =
      let s = ref 0 in
      let rec go i j =
        if 0 <= i && i < n && 0 <= j && j < m && a.(i).[j] = '1' then (
          a.(i).[j] <- '2';
          incr s;
          Array.iter (fun (dx,dy) -> go (i+dx) (j+dy)) ds
        )
      in
      go i j;
      !s
    in

    let span i j l u v =
      try
        for d = u to v-1 do
          let x = ref i and y = ref j in
          for k = 0 to l do
            if not (0 <= !x && !x < n && 0 <= !y && !y < m && a.(!x).[!y] = '2') then
              raise No;
            x := !x + fst ds.(u);
            y := !y + snd ds.(u)
          done
        done;
        true
      with No ->
        false
    in

    let ans = ref 0 in
    for i = 0 to n-1 do
      for j = 0 to m-1 do
        if a.(i).[j] = '1' then (
          let s = dfs i j in
          if s mod 4 = 0 && s <= (n-1)*4 then (
            if span i j (s/4) 0 2 && span (i+s/4) (j+s/4) (s/4) 2 4 then
              incr ans;
            if span i j (s/4) 4 6 && span (i+s/2) j (s/4) 6 8 then
              incr ans;
          )
        )
      done
    done;
    Printf.printf "%d\n" !ans
  done


Suppose you have two polynomials  and . Then polynomial  can be uniquely represented in the following way:This can be done using long division. Here,  denotes the degree of polynomial P(x).  is called the remainder of division of polynomial  by polynomial , it is also denoted as . Since there is a way to divide polynomials with remainder, we can define Euclid's algorithm of finding the greatest common divisor of two polynomials. The algorithm takes two polynomials . If the polynomial  is zero, the result is , otherwise the result is the value the algorithm returns for pair . On each step the degree of the second argument decreases, so the algorithm works in finite number of steps. But how large that number could be? You are to answer this question. You are given an integer n. You have to build two polynomials with degrees not greater than n, such that their coefficients are integers not exceeding 1 by their absolute value, the leading coefficients (ones with the greatest power of x) are equal to one, and the described Euclid's algorithm performs exactly n steps finding their greatest common divisor. Moreover, the degree of the first polynomial should be greater than the degree of the second. By a step of the algorithm we mean the transition from pair  to pair .

You are given a single integer n (1 ≤ n ≤ 150) — the number of steps of the algorithm you need to reach.

Print two polynomials in the following format. In the first line print a single integer m (0 ≤ m ≤ n) — the degree of the polynomial.  In the second line print m + 1 integers between  - 1 and 1 — the coefficients of the polynomial, from constant to leading.  The degree of the first polynomial should be greater than the degree of the second polynomial, the leading coefficients should be equal to 1. Euclid's algorithm should perform exactly n steps when called using these polynomials. If there is no answer for the given n, print -1. If there are multiple answer, print any of them.

NoteIn the second example you can print polynomials x2 - 1 and x. The sequence of transitions is(x2 - 1, x) → (x,  - 1) → ( - 1, 0).There are two steps in it.

open Printf
open Scanf

let read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)

let () =
  let n = read_int () in

  let zero() = Array.make (n+1) 0 in

  let shift p =
    if p.(n) <> 0 then failwith "overflow";
    Array.init (n+1) (fun i -> if i>0 then p.(i-1) else 0)
  in

  let sum p q =
    Array.init (n+1) (fun i -> (p.(i) + q.(i)) mod 3)
  in

  let scalar_mult d p =
    Array.init (n+1) (fun i -> (d * p.(i)) mod 3)
  in

  let mult (d0,d1) p =
    let p1 = scalar_mult d1 (shift p) in
    let p2 = scalar_mult d0 p in
    sum p1 p2
  in

  let rec build i (curr,prev) = if i=n then (curr,prev)
    else build (i+1) (sum (mult (0,1) curr) prev, curr)
  in

  let a0 = zero() in
  let a1 = zero() in
  a1.(0) <- 1;

  let (curr,prev) = build 0 (a1,a0) in

  let printpoly p =
    let rec find i = if i<0 then failwith "not found"
      else if p.(i) = 0 then find (i-1)
      else i
    in
    let degree = find n in
    printf "%d\n" degree;
    for i=0 to degree do
      printf "%d " (if p.(i) = 2 then -1 else p.(i))
    done;
    print_newline()
  in

  printpoly curr;
  printpoly prev


Anton came to a chocolate factory. There he found a working conveyor and decided to run on it from the beginning to the end.The conveyor is a looped belt with a total length of 2l meters, of which l meters are located on the surface and are arranged in a straight line. The part of the belt which turns at any moment (the part which emerges from under the floor to the surface and returns from the surface under the floor) is assumed to be negligibly short.The belt is moving uniformly at speed v1 meters per second. Anton will be moving on it in the same direction at the constant speed of v2 meters per second, so his speed relatively to the floor will be v1 + v2 meters per second. Anton will neither stop nor change the speed or the direction of movement.Here and there there are chocolates stuck to the belt (n chocolates). They move together with the belt, and do not come off it. Anton is keen on the chocolates, but he is more keen to move forward. So he will pick up all the chocolates he will pass by, but nothing more. If a chocolate is at the beginning of the belt at the moment when Anton starts running, he will take it, and if a chocolate is at the end of the belt at the moment when Anton comes off the belt, he will leave it.     The figure shows an example with two chocolates. One is located   in the position a1 = l - d, and is now on the top half of the belt, the second one   is in the position a2 = 2l - d, and is now on the bottom half of the belt.  You are given the positions of the chocolates relative to the initial start position of the belt 0 ≤ a1 < a2 < ... < an < 2l. The positions on the belt from 0 to l correspond to the top, and from l to 2l — to the the bottom half of the belt (see example). All coordinates are given in meters.Anton begins to run along the belt at a random moment of time. This means that all possible positions of the belt at the moment he starts running are equiprobable. For each i from 0 to n calculate the probability that Anton will pick up exactly i chocolates.

The first line contains space-separated integers n, l, v1 and v2 (1 ≤ n ≤ 105, 1 ≤ l, v1, v2 ≤ 109) — the number of the chocolates, the length of the conveyor's visible part, the conveyor's speed and Anton's speed. The second line contains a sequence of space-separated integers a1, a2, ..., an (0 ≤ a1 < a2 < ... < an < 2l) — the coordinates of the chocolates.

Print n + 1 numbers (one per line): the probabilities that Anton picks up exactly i chocolates, for each i from 0 (the first line) to n (the last line). The answer will be considered correct if each number will have absolute or relative error of at most than 10 - 9.

NoteIn the first sample test Anton can pick up a chocolate if by the moment he starts running its coordinate is less than 0.5; but if by the moment the boy starts running the chocolate's coordinate is greater than or equal to 0.5, then Anton won't be able to pick it up. As all positions of the belt are equiprobable, the probability of picking up the chocolate equals , and the probability of not picking it up equals .

open Num
open Big_int

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let l = Scanf.bscanf sb "%d " (fun s -> s) in
  let v1 = Scanf.bscanf sb "%d " (fun s -> s) in
  let v2 = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0.0 in
  let () =
    for i = 0 to n - 1 do
      let k = Scanf.bscanf sb "%ld " (fun s -> s) in
	a.(i) <- Int32.to_float k
    done;
  in
  let d =
    num_of_int l // (num_of_int v1 +/ num_of_int v2)
    */ num_of_int v2
  in
  let d = float_of_num d in
  let l2 = 2.0 *. float_of_int l in
  let eps = 10e-7 in
  let e = ref [] in
  let () =
    e := (d, 0) :: !e;
    e := (d +. l2, 0) :: !e;
    for i = 0 to n - 1 do
      e := (a.(i), 1) :: !e;
      e := (a.(i) +. l2, 1) :: !e;
      e := (a.(i) +. d, -1) :: !e;
      e := (a.(i) +. d +. l2, -1) :: !e;
    done;
  in
  let e = Array.of_list !e in
  let () = Array.sort compare e in
  let j = ref 0 in
  let c = ref 0 in
  let prev = ref 0.0 in
  let res = Array.make (n + 1) 0.0 in
    while !j < Array.length e && fst e.(!j) <= d +. eps do
      c := !c + snd e.(!j);
      incr j
    done;
    prev := d;
    while !j < Array.length e && fst e.(!j) <= d +. l2 +. eps do
      res.(!c) <- res.(!c) +. fst e.(!j) -. !prev;
      prev := fst e.(!j);
      c := !c + snd e.(!j);
      incr j
    done;
    for i = 0 to n do
      Printf.printf "%.9f\n" (res.(i) /. l2);
    done;

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let l = Scanf.bscanf sb "%d " (fun s -> s) in
  let v1 = Scanf.bscanf sb "%d " (fun s -> s) in
  let v2 = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0.0 in
  let () =
    for i = 0 to n - 1 do
      let k = Scanf.bscanf sb "%ld " (fun s -> s) in
	a.(i) <- Int32.to_float k
    done;
  in
  let d =
    float_of_int l /. (float_of_int v1 +. float_of_int v2)
    *. float_of_int v2
  in
  let l2 = 2.0 *. float_of_int l in
  let e = ref [] in
  let () =
    e := (d, 0) :: !e;
    e := (d +. l2, 0) :: !e;
    for i = 0 to n - 1 do
      e := (a.(i), 1) :: !e;
      e := (a.(i) +. l2, 1) :: !e;
      e := (a.(i) +. d, -1) :: !e;
      e := (a.(i) +. d +. l2, -1) :: !e;
    done;
  in
  let e = Array.of_list !e in
  let () = Array.sort compare e in
  let j = ref 0 in
  let c = ref 0 in
  let prev = ref 0.0 in
  let res = Array.make (n + 1) 0.0 in
    while !j < Array.length e && fst e.(!j) < d do
      c := !c + snd e.(!j);
      incr j
    done;
    prev := d;
    while !j < Array.length e && fst e.(!j) <= d +. l2 do
      res.(!c) <- res.(!c) +. fst e.(!j) -. !prev;
      prev := fst e.(!j);
      c := !c + snd e.(!j);
      incr j
    done;
    for i = 0 to n do
      Printf.printf "%.9f\n" (res.(i) /. l2);
    done;


Gerald has n younger brothers and their number happens to be even. One day he bought n2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer k from 1 to n2 he has exactly one bag with k candies. Help him give n bags of candies to each brother so that all brothers got the same number of candies.

The single line contains a single integer n (n is even, 2 ≤ n ≤ 100) — the number of Gerald's brothers.

Let's assume that Gerald indexes his brothers with numbers from 1 to n. You need to print n lines, on the i-th line print n integers — the numbers of candies in the bags for the i-th brother. Naturally, all these numbers should be distinct and be within limits from 1 to n2. You can print the numbers in the lines in any order.  It is guaranteed that the solution exists at the given limits.

NoteThe sample shows Gerald's actions if he has two brothers. In this case, his bags contain 1, 2, 3 and 4 candies. He can give the bags with 1 and 4 candies to one brother and the bags with 2 and 3 to the other brother.

let n = read_int () in
for i = 1 to n do
    for j = 0 to n/2 - 1 do
        Printf.printf "%d %d " (i + j*n) (n*(n-j) - i + 1)
    done ;
    print_newline ()
done ;;


Let's call beauty of an array $$$b_1, b_2, \ldots, b_n$$$ ($$$n > 1$$$)  — $$$\min\limits_{1 \leq i < j \leq n} |b_i - b_j|$$$.You're given an array $$$a_1, a_2, \ldots a_n$$$ and a number $$$k$$$. Calculate the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.A sequence $$$a$$$ is a subsequence of an array $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements.

The first line contains integers $$$n, k$$$ ($$$2 \le k \le n \le 1000$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^5$$$).

Output one integer — the sum of beauty over all subsequences of the array of length exactly $$$k$$$. As this number can be very large, output it modulo $$$998244353$$$.

NoteIn the first example, there are $$$4$$$ subsequences of length $$$3$$$ — $$$[1, 7, 3]$$$, $$$[1, 3, 5]$$$, $$$[7, 3, 5]$$$, $$$[1, 7, 5]$$$, each of which has beauty $$$2$$$, so answer is $$$8$$$.In the second example, there is only one subsequence of length $$$5$$$ — the whole array, which has the beauty equal to $$$|10-1| = 9$$$.

let modulo = 998244353l;;
let (+%) a b = let sum = Int32.add a b in if sum >= modulo then Int32.sub sum modulo else sum;;

let read_int_list() = read_line() |> Str.(split (regexp " ")) |> List.map (fun x -> Int32.of_string x);;
let n_sub = List.nth (read_int_list()) 1;;
let nums = List.sort compare (read_int_list());;

let rec generate_list len value =
  if len == 0
    then []
    else value :: (generate_list (len - 1) value)
;;

let compute_num_subseq_least_diff nums k x =
  let rec compute_dp_one x cur_nums suffix_nums suffix_dp sum_prefix =
    (* Printf.printf "%ld %d %d %d %ld\n" x (List.length cur_nums) (List.length suffix_nums) (List.length suffix_dp) sum_prefix; *)
    if cur_nums == []
      then []
      else if suffix_dp == [] || (Int32.add (List.hd suffix_nums) x) > (List.hd cur_nums)
        then sum_prefix :: compute_dp_one x (List.tl cur_nums) suffix_nums suffix_dp sum_prefix
        else compute_dp_one x cur_nums (List.tl suffix_nums) (List.tl suffix_dp) (sum_prefix +% (List.hd suffix_dp))
  in
  let rec compute_dp_all nums k x =
    (* Printf.printf "%ld\n" k; *)
    if k = 1l
      then generate_list (List.length nums) 1l
      else compute_dp_one x nums nums (compute_dp_all nums (Int32.sub k 1l) x) 0l
  in
    List.fold_left (fun a b -> a +% b) 0l (compute_dp_all nums k x)
;;

let rec compute_result nums k i =
  let count = compute_num_subseq_least_diff nums k i
  in
    if count = 0l
      then 0l
      else count +% (compute_result nums k (Int32.add i 1l))
in
  Printf.printf "%ld\n" (compute_result nums n_sub 1l)
;;

let modulo = 998244353;;
let (+%) a b = if a + b >= modulo then a + b - modulo else a + b;;

let read_int_list() = read_line() |> Str.(split (regexp " ")) |> List.map (fun x -> int_of_string x);;
let n_sub = List.nth (read_int_list()) 1;;
let nums = List.sort compare (read_int_list());;

let rec generate_list len value =
  if len == 0
    then []
    else value :: (generate_list (len - 1) value)
;;

let compute_num_subseq_least_diff nums k x =
  let rec compute_dp_one x cur_nums suffix_nums suffix_dp sum_prefix =
    (* Printf.printf "%d %d %d %d %d\n" x (List.length cur_nums) (List.length suffix_nums) (List.length suffix_dp) sum_prefix; *)
    if cur_nums == []
      then []
      else if suffix_dp == [] || (List.hd suffix_nums) + x > (List.hd cur_nums)
        then sum_prefix :: compute_dp_one x (List.tl cur_nums) suffix_nums suffix_dp sum_prefix
        else compute_dp_one x cur_nums (List.tl suffix_nums) (List.tl suffix_dp) (sum_prefix +% (List.hd suffix_dp))
  in
  let rec compute_dp_all nums k x =
    match k with
      | 1 -> generate_list (List.length nums) 1
      | _ -> compute_dp_one x nums nums (compute_dp_all nums (k - 1) x) 0
  in
    List.fold_left (fun a b -> a +% b) 0 (compute_dp_all nums k x)
;;

let rec compute_result nums k i =
  (* Printf.printf "\n"; *)
  let count = compute_num_subseq_least_diff nums k i
  in
    if count == 0
      then 0
      else count +% (compute_result nums k (i + 1))
in
  Printf.printf "%d\n" (compute_result nums n_sub 1)
;;


Drazil created a following problem about putting 1 × 2 tiles into an n × m grid:"There is a grid with some cells that are empty and some cells that are occupied. You should use 1 × 2 tiles to cover all empty cells and no two tiles should cover each other. And you should print a solution about how to do it."But Drazil doesn't like to write special checking program for this task. His friend, Varda advised him: "how about asking contestant only to print the solution when it exists and it is unique? Otherwise contestant may print 'Not unique' ".Drazil found that the constraints for this task may be much larger than for the original task!Can you solve this new problem?Note that you should print 'Not unique' either when there exists no solution or when there exists several different solutions for the original task.

The first line contains two integers n and m (1 ≤ n, m ≤ 2000). The following n lines describe the grid rows. Character '.' denotes an empty cell, and the character '*' denotes a cell that is occupied.

If there is no solution or the solution is not unique, you should print the string "Not unique". Otherwise you should print how to cover all empty cells with 1 × 2 tiles. Use characters "<>" to denote horizontal tiles and characters "^v" to denote vertical tiles. Refer to the sample test for the output format example.

NoteIn the first case, there are indeed two solutions:<>^^*vv<>and^<>v*^<>vso the answer is "Not unique".

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_string () = bscanf Scanning.stdib " %s " (fun x -> x)
let () =
  let n = read_int () in
  let m = read_int () in
  let board = Array.init n (fun _ -> read_string()) in

  let is_empty i j = board.(i).[j] = '.' in   (* return true if empty *)

  let empty = ref 0 in
  for i=0 to n-1 do
    for j=0 to m-1 do
      if is_empty i j then empty := !empty + 1
    done
  done;

  (* algorithm:

     (1) make a list of all force points
     (2) pick one and put a piece in
            look at all empty neighbors, if any of
            them has become a force point add it to
            the list of force points

  *)

  let count_empty_neighbors (i,j) =
    List.fold_left (fun ac (i,j) ->
      if i<0 || i>=n || j<0 || j>=m then ac
      else if is_empty i j then ac+1 else ac
    ) 0 [(i,j+1);(i,j-1);(i+1,j);(i-1,j)]
  in

  let empty_neighbor_direction (i,j) =
    List.fold_left (fun ac ((i,j),d) ->
      if i<0 || i>=n || j<0 || j>=m then ac
      else if is_empty i j then ((i,j),d) else ac
    ) ((0,0),0) [((i,j+1),0);((i,j-1),1);((i+1,j),2);((i-1,j),3)]
  in

  let next (i,j) = if i<n-1 then (i+1,j) else (0, j+1) in
  let rec find_force_points (i,j) ac = if j=m then ac else
    let ac = if count_empty_neighbors (i,j) = 1 then (i,j)::ac else ac in
    find_force_points (next (i,j)) ac
  in

  let fpl = find_force_points (0,0) [] in
(*
  List.iter (fun (i,j) -> printf "force point (%d,%d)\n" i j) fpl;
*)
  let rec fill_in fpl nempty =
    if nempty=0 then true else if fpl = [] then false else (
      let (i,j) = List.hd fpl in
      let fpl = List.tl fpl in
      if not (is_empty i j) then fill_in fpl nempty else (
	if count_empty_neighbors (i,j) <> 1 then fill_in fpl nempty else (
	  let ((i',j'),d) = empty_neighbor_direction (i,j) in
(*	  printf "empty neighbor direction = ((%d,%d),%d)\n" i' j' d; *)
	  let (c1,c2) = match d with
	    | 0 -> ('<','>')
	    | 1 -> ('>','<')
	    | 2 -> ('^','v')
	    | 3 -> ('v','^')
	    | _ -> failwith "bad dir"
	  in
	  board.(i).[j] <- c1;
	  board.(i').[j'] <- c2;

	  let nempty = nempty - 2 in

	  let (i,j) = (i',j') in
	  let fpl = List.fold_left (fun ac (i,j) ->
	    if i<0 || i>=n || j<0 || j>=m then ac
	    else if count_empty_neighbors (i,j) = 1 then (i,j)::ac else ac
	  ) fpl [(i,j+1);(i,j-1);(i+1,j);(i-1,j)]
	  in
	  fill_in fpl nempty
	)
      )
    )
  in

  if fill_in fpl !empty then (
    for i=0 to n-1 do
      printf "%s\n" board.(i)
    done;
  ) else (
    printf "Not unique\n"
  )


"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I pledge my life and honor to the Night's Watch, for this night and all the nights to come." — The Night's Watch oath.With that begins the watch of Jon Snow. He is assigned the task to support the stewards.This time he has n stewards with him whom he has to provide support. Each steward has his own strength. Jon Snow likes to support a steward only if there exists at least one steward who has strength strictly less than him and at least one steward who has strength strictly greater than him.Can you find how many stewards will Jon support?

First line consists of a single integer n (1 ≤ n ≤ 105) — the number of stewards with Jon Snow. Second line consists of n space separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) representing the values assigned to the stewards.

Output a single integer representing the number of stewards which Jon will feed.

NoteIn the first sample, Jon Snow cannot support steward with strength 1 because there is no steward with strength less than 1 and he cannot support steward with strength 5 because there is no steward with strength greater than 5.In the second sample, Jon Snow can support steward with strength 2 because there are stewards with strength less than 2 and greater than 2.

let () =
  let n = read_int () in
  let a = Array.init n (fun _ -> Scanf.scanf "%d%_c" (fun x -> x)) in
  (* sort ascending *)
  Array.sort compare a;
  let a = List.filter (fun x -> x <> a.(0) && x <> a.(n - 1)) (Array.to_list a) in
  print_int (List.length a);
  print_newline ()

let _ =
	Scanf.scanf "%d" @@ fun n ->
		let l = (Array.init n (fun _ -> Scanf.scanf " %d" (fun i -> i)))
			|> Array.to_list
		in
		let mini = List.fold_left min max_int l in
		let maxi = List.fold_left max min_int l in
		let l' = List.filter ((<>) mini) l in
		let l'' = List.filter ((<>) maxi) l' in
			print_int (List.length l'')


We are sum for we are manySome NumberThis version of the problem differs from the next one only in the constraint on $$$t$$$. You can make hacks only if both versions of the problem are solved.You are given two positive integers $$$l$$$ and $$$r$$$.Count the number of distinct triplets of integers $$$(i, j, k)$$$ such that $$$l \le i < j < k \le r$$$ and $$$\operatorname{lcm}(i,j,k) \ge i + j + k$$$.Here $$$\operatorname{lcm}(i, j, k)$$$ denotes the least common multiple (LCM) of integers $$$i$$$, $$$j$$$, and $$$k$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$\bf{1 \le t \le 5}$$$). Description of the test cases follows. The only line for each test case contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 2 \cdot 10^5$$$, $$$l + 2 \le r$$$).

For each test case print one integer — the number of suitable triplets.

NoteIn the first test case, there are $$$3$$$ suitable triplets:   $$$(1,2,3)$$$,  $$$(1,3,4)$$$,  $$$(2,3,4)$$$. In the second test case, there is $$$1$$$ suitable triplet:   $$$(3,4,5)$$$.

module A = Array
module L = List
module I = Int64

let pf = Printf.printf
let sf = Scanf.scanf
let read_int () = sf " %d" (fun x -> x)
let read_array read n = A.init n (fun _ -> read ())

let max_n = 200000

module SegTree = struct
  type t = int64 array

  let init n = A.make (2 * n) I.zero

  let add t i x =
    let v = ref i in
    let n = A.length t in
    while !v < n do
      t.(!v) <- I.add t.(!v) x;
      v := !v lor (!v + 1);
    done

  let pref_sum t i =
    let r = ref i in
    let res = ref I.zero in
    while !r >= 0 do
      res := I.add !res t.(!r);
      r := (!r land (!r + 1)) - 1;
    done;
    !res

  let sum t l r =  I.sub (pref_sum t r) (pref_sum t (l - 1))
end

module L_ = struct
  let filter_map f =
    let rec aux accu = function
      | [] -> L.rev accu
      | x :: l ->
          match f x with
          | None -> aux accu l
          | Some v -> aux (v :: accu) l
    in
    aux []
end

type query = {
  l: int;
  q_index: int;
}

let find_first_div n =
  let i = ref 2 in
  let found = ref (-1) in
  while !i * !i <= n && !found = -1 do
    if (n mod !i = 0) then found := !i;
    i := !i + 1;
  done;
  if (!found = -1) then n
  else !found

let () =
  let q = read_int () in
  let original_queries: (int * int) array = Array.make q (0, 0) in
  let ans = Array.make q I.zero in
  let (events: query list array) = Array.init (max_n + 1) (fun _ -> []) in
  for i = 0 to q - 1 do
    let l = read_int () in
    let r = read_int () in
    original_queries.(i) <- (l, r);
    events.(r) <- {l; q_index = i;} :: events.(r);
  done;

  let (divisors: int list array) = Array.make (max_n + 1) [] in
  let pw2 = Array.make (max_n + 1) 0 in
  divisors.(1) <- [1];

  let inc_tree = SegTree.init max_n in
  for k = 2 to max_n do
    let fd = find_first_div k in
    let divs_prev = divisors.(k / fd) in
    divisors.(k) <- L.sort_uniq compare (divs_prev @ List.map (fun x -> x * fd) divs_prev);
    if (k mod 2 = 0) then pw2.(k) <- pw2.(k / 2) + 1;

    let divs = divisors.(k) in
    let divs_num = L.length divs in
    L.iteri (fun idx i ->
      if (i <> k) then
        SegTree.add inc_tree i @@ I.of_int @@ divs_num - idx - 2;
    ) divs;
    let p = pw2.(k) in

    let new_divs =
        A.of_list @@
        L.tl @@
        L.fast_sort (fun x y -> -compare x y) @@
        divs @ L_.filter_map (fun d ->
          if (d * 2 < k && pw2.(d) == p) then Some (d * 2)
          else None
        ) divs in
    let sj_p = ref 0 and ptr_j = ref (-1) in
    A.iteri (fun idx i ->
      while (!ptr_j <> -1 && new_divs.(!ptr_j) + i <= k) do
        let cd = new_divs.(!ptr_j) in
        if (pw2.(cd) = p + 1) then sj_p := !sj_p - 1;
        ptr_j := !ptr_j - 1
      done;

      if (pw2.(i) = p + 1) then
        SegTree.add inc_tree i @@ I.of_int @@ !ptr_j + 1
      else
        SegTree.add inc_tree i @@ I.of_int !sj_p;

      while (!ptr_j + 1 <= idx && new_divs.(!ptr_j + 1) + i > k) do
        let cd = new_divs.(!ptr_j + 1) in
        if (pw2.(cd) = p + 1) then sj_p := !sj_p + 1;
        ptr_j := !ptr_j + 1
      done;
    ) new_divs;

    L.iter (fun q ->
      ans.(q.q_index) <- SegTree.sum inc_tree q.l k;
    ) events.(k)
  done;

  for i = 0 to q - 1 do
    let n = snd original_queries.(i) - fst original_queries.(i) + 1 in
    let real_ans =
      I.(sub
        (div
          (mul (mul (of_int n) (of_int @@ n - 1)) (of_int @@ n - 2))
          (of_int 6))
        ans.(i)) in
    pf "%Ld\n" real_ans;
  done;


You are given an integer $$$n$$$ ($$$n \ge 0$$$) represented with $$$k$$$ digits in base (radix) $$$b$$$. So,$$$$$$n = a_1 \cdot b^{k-1} + a_2 \cdot b^{k-2} + \ldots a_{k-1} \cdot b + a_k.$$$$$$For example, if $$$b=17, k=3$$$ and $$$a=[11, 15, 7]$$$ then $$$n=11\cdot17^2+15\cdot17+7=3179+255+7=3441$$$.Determine whether $$$n$$$ is even or odd.

The first line contains two integers $$$b$$$ and $$$k$$$ ($$$2\le b\le 100$$$, $$$1\le k\le 10^5$$$) — the base of the number and the number of digits. The second line contains $$$k$$$ integers $$$a_1, a_2, \ldots, a_k$$$ ($$$0\le a_i < b$$$) — the digits of $$$n$$$. The representation of $$$n$$$ contains no unnecessary leading zero. That is, $$$a_1$$$ can be equal to $$$0$$$ only if $$$k = 1$$$.

Print "even" if $$$n$$$ is even, otherwise print "odd". You can print each letter in any case (upper or lower).

NoteIn the first example, $$$n = 3 \cdot 13^2 + 2 \cdot 13 + 7 = 540$$$, which is even.In the second example, $$$n = 123456789$$$ is odd.In the third example, $$$n = 32 \cdot 99^4 + 92 \cdot 99^3 + 85 \cdot 99^2 + 74 \cdot 99 + 4 = 3164015155$$$ is odd.In the fourth example $$$n = 2$$$.

let rec sum acc base digits = match digits with
| [] -> acc
| first :: digits -> sum (acc + first * base) base digits in

let is_even base digits = match digits with
| [] -> false
| first :: digits -> ((sum first base digits) mod 2 == 0) in

let main b a = if is_even b a then "even" else "odd" in

let rec read (acc: int list) k = if k == 0
  then acc
  else read ((Scanf.scanf " %s" (fun a -> (int_of_string (String.trim a)))) :: acc) (k - 1) in

Scanf.scanf "%s %s\n" (fun b k ->
  print_string(main (int_of_string (String.trim b)) (read [] (int_of_string (String.trim k))))
)


There is an array $$$a$$$ of length $$$n$$$. You may perform the following operation any number of times:  Choose two indices $$$l$$$ and $$$r$$$ where $$$1 \le l < r \le n$$$ and $$$a_l = a_r$$$. Then, set $$$a[l \ldots r] = [a_{l+1}, a_{l+2}, \ldots, a_r, a_l]$$$. You are also given another array $$$b$$$ of length $$$n$$$ which is a permutation of $$$a$$$. Determine whether it is possible to transform array $$$a$$$ into an array $$$b$$$ using the above operation some number of times.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10 ^ 5$$$)  — the length of array $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$)  — elements of the array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$)  — elements of the array $$$b$$$. It is guaranteed that $$$b$$$ is a permutation of $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10 ^ 5$$$

For each test case, print "YES" (without quotes) if it is possible to transform array $$$a$$$ to $$$b$$$, and "NO" (without quotes) otherwise. You can output "YES" and "NO" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case, we can choose $$$l=2$$$ and $$$r=5$$$ to form $$$[1, 3, 3, 2, 2]$$$.In the second test case, we can choose $$$l=2$$$ and $$$r=4$$$ to form $$$[1, 4, 2, 2, 1]$$$. Then, we can choose $$$l=1$$$ and $$$r=5$$$ to form $$$[4, 2, 2, 1, 1]$$$.In the third test case, it can be proven that it is not possible to transform array $$$a$$$ to $$$b$$$ using the operation.

let parse len str = let rep = Array.make len (-1) in
  let temp = ref "" in
  let j = ref 0 in
  for i = 0 to String.length str -1 do
    if str.[i] = ' ' then
      (rep.(!j) <- (int_of_string !temp) ; incr j ; temp:=""  )
    else
      (temp:= !temp ^ (String.make 1 str.[i]))
  done; rep.(!j) <- (int_of_string !temp) ;rep
;;

let rec update ind2 tab2 loserb len =

  if tab2.(!ind2 -1) = tab2.(!ind2) && Hashtbl.mem loserb (tab2.(!ind2)) then begin
    let num = Hashtbl.find loserb (tab2.(!ind2)) in
    if num = 1 then Hashtbl.remove loserb (tab2.(!ind2))
    else Hashtbl.replace loserb (tab2.(!ind2)) (num-1) ;
    incr ind2 ;
    if !ind2 < len then
      update ind2 tab2 loserb len
    ;
  end
;;

let n = int_of_string (input_line stdin) in
for j = 0 to n-1 do
  let len = int_of_string (input_line stdin) in
  let str1 = (input_line stdin) in
  let str2 = (input_line stdin) in
  let tab1 = parse len str1 in
  let tab2 = parse len str2 in
  let ind2 = ref 0 in
  let loserb = Hashtbl.create(len) in
  for i = 0 to len -1 do
    if tab1.(i) = tab2.(!ind2) then begin
      incr ind2;
      if !ind2 < len then
        update ind2 tab2 loserb len
      ;
    end
    else begin
      if Hashtbl.mem loserb (tab1.(i)) then
        (let num = Hashtbl.find loserb (tab1.(i)) in Hashtbl.replace loserb (tab1.(i)) (num+1))
      else Hashtbl.add loserb (tab1.(i)) 1
    end;

  done;
if !ind2 = len then print_endline "YES" else print_endline "NO"
done;;