Valera has got a rectangle table consisting of n rows and m columns. Valera numbered the table rows starting from one, from top to bottom and the columns – starting from one, from left to right. We will represent cell that is on the intersection of row x and column y by a pair of integers (x, y).Valera wants to place exactly k tubes on his rectangle table. A tube is such sequence of table cells (x1, y1), (x2, y2), ..., (xr, yr), that:   r ≥ 2;  for any integer i (1 ≤ i ≤ r - 1) the following equation |xi - xi + 1| + |yi - yi + 1| = 1 holds;  each table cell, which belongs to the tube, must occur exactly once in the sequence. Valera thinks that the tubes are arranged in a fancy manner if the following conditions are fulfilled:   no pair of tubes has common cells;  each cell of the table belongs to some tube. Help Valera to arrange k tubes on his rectangle table in a fancy manner.

The first line contains three space-separated integers n, m, k (2 ≤ n, m ≤ 300; 2 ≤ 2k ≤ n·m) — the number of rows, the number of columns and the number of tubes, correspondingly.

Print k lines. In the i-th line print the description of the i-th tube: first print integer ri (the number of tube cells), then print 2ri integers xi1, yi1, xi2, yi2, ..., xiri, yiri (the sequence of table cells). If there are multiple solutions, you can print any of them. It is guaranteed that at least one solution exists.

NotePicture for the first sample:   Picture for the second sample:

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_pair () = let u = read_int() in (u,read_int())
let () =
  let n = read_int () in
  let m = read_int () in
  let k = read_int () in

  let cells = Array.make (n*m) (0,0) in

  let next (x,y) =
    if x land 1 = 1 (* left to right *) then
      if y<m then (x,y+1) else (x+1,m)
    else
      if y>1 then (x,y-1) else (x+1,1)
  in

  let rec loop i p = if fst p = n+1 then () else (
    cells.(i) <- p;
    loop (i+1) (next p)
  )
  in

  loop 0 (1,1);

  let small_size = (n*m)/k in
  let big_size = small_size+1 in

(*
  let rec find_mult remain sc = if remain=0 then sc else
      if remain mod big_size = 0 then sc else
	find_mult (remain-small_size) (sc+1)
  in
*)

  let rec find_count c =
    if c*small_size + (k-c)*big_size = n*m then c else find_count (c+1)
  in

  let scount = find_count 1 in

  let bcount = (n*m - scount * small_size)/big_size in

  if scount+bcount <> k then failwith "count wrong";

  let rec loop i p = if i=k then () else
      if i<scount then (
	printf "%d" small_size;
	for j=0 to small_size-1 do
	  let (x,y) = cells.(j+p) in
	  printf " %d %d" x y;
	done;
	print_newline();
	loop (i+1) (p+small_size)
      ) else (
	printf "%d" big_size;
	for j=0 to big_size-1 do
	  let (x,y) = cells.(j+p) in
	  printf " %d %d" x y;
	done;
	print_newline();
	loop (i+1) (p+big_size)
      )
  in

  loop 0 0;

let read_int()=Scanf.scanf "%d " (fun x->x);;
let n=read_int();;
let m=read_int();;
let k=read_int();;

let tab=Array.make (k+1) [];;
let a=(n*m)/k;;

let suivant i j s=
   if (s="droite")&&(j<m) then (i,j+1,s)
   else if (s="droite") then (i+1,j,"gauche")
   else if (s="gauche")&&(j>1) then (i,j-1,s)
   else (i+1,j,"droite");;

let i=ref 1;;
let j=ref 0;;
let s=ref "droite";;

for l=1 to k-1 do
   for o=1 to a do
      let (x,y,z)=suivant (!i) (!j) (!s) in
      i:=x;
      j:=y;
      s:=z;
      tab.(l)<-(!i,!j)::tab.(l)
   done
done;;
for o=1 to a+((n*m) mod k) do
   let (x,y,z)=suivant (!i) (!j) (!s) in
   i:=x;
   j:=y;
   s:=z;
   tab.(k)<-(!i, !j)::tab.(k)
done;;
let rec taille=function
|[]->0
|(_,_)::t->1+taille t;;
let rec print_list=function
|[]->print_newline()
|(h,g)::t->Printf.printf "%d %d " h g;print_list t;;
for i=1 to k do
   Printf.printf "%d " (taille tab.(i));
   print_list tab.(i)
done;;


You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character.You are playing the game on the new generation console so your gamepad have $$$26$$$ buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons are pairwise distinct.You are given a sequence of hits, the $$$i$$$-th hit deals $$$a_i$$$ units of damage to the opponent's character. To perform the $$$i$$$-th hit you have to press the button $$$s_i$$$ on your gamepad. Hits are numbered from $$$1$$$ to $$$n$$$.You know that if you press some button more than $$$k$$$ times in a row then it'll break. You cherish your gamepad and don't want to break any of its buttons.To perform a brutality you have to land some of the hits of the given sequence. You are allowed to skip any of them, however changing the initial order of the sequence is prohibited. The total damage dealt is the sum of $$$a_i$$$ over all $$$i$$$ for the hits which weren't skipped.Note that if you skip the hit then the counter of consecutive presses the button won't reset.Your task is to skip some hits to deal the maximum possible total damage to the opponent's character and not break your gamepad buttons.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — the number of hits and the maximum number of times you can push the same button in a row. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the damage of the $$$i$$$-th hit. The third line of the input contains the string $$$s$$$ consisting of exactly $$$n$$$ lowercase Latin letters — the sequence of hits (each character is the letter on the button you need to press to perform the corresponding hit).

Print one integer $$$dmg$$$ — the maximum possible damage to the opponent's character you can deal without breaking your gamepad buttons.

NoteIn the first example you can choose hits with numbers $$$[1, 3, 4, 5, 6, 7]$$$ with the total damage $$$1 + 16 + 18 + 7 + 2 + 10 = 54$$$.In the second example you can choose all hits so the total damage is $$$2 + 4 + 1 + 3 + 1000 = 1010$$$.In the third example you can choose all hits expect the third one so the total damage is $$$2 + 4 + 3 + 1000 = 1009$$$.In the fourth example you can choose hits with numbers $$$[2, 3, 6, 8]$$$. Only this way you can reach the maximum total damage $$$15 + 2 + 8 + 16 = 41$$$.In the fifth example you can choose only hits with numbers $$$[2, 4, 6]$$$ with the total damage $$$18 + 19 + 15 = 52$$$.In the sixth example you can change either first hit or the second hit (it does not matter) with the total damage $$$10$$$.

let rv f p q = f q p
let rec fix f x = f (fix f) x
let (++),( ** ),(--) = Int64.(add,mul,sub)
;;
Scanf.(Array.(scanf " %d %d" @@ fun n k ->
  let a = init n (fun _ -> scanf " %Ld" @@ fun v -> v) in
  let s = scanf " %s" @@ fun v -> v in
  let sects = fix (fun f i ls all ->
    if i=0 then
      f (i+1) (a.(i)::ls) all
    else if i=n then
      if List.length ls <> 0 then (List.sort (rv compare) ls)::all
      else all
    else
      if s.[i] = s.[i-1] then
        f (i+1) (a.(i)::ls) all
      else
        f (i+1) [a.(i)] ((List.sort (rv compare) ls)::all)
  ) 0 [] []
  in
  Printf.printf "%Ld" @@
    List.fold_left (fun sum ls ->
      if List.length ls <= k then
        sum ++ List.fold_left (++) 0L ls
      else
        sum ++ snd (List.fold_left (fun (i,sum) v ->
          if i<k then (i+1,sum++v) else (i+1,sum)
        ) (0,0L) ls)
    ) 0L sects
))

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_lim,min_i64_lim = Int64.(max_int,min_int)
  let max_i64,min_i64 = 2000000000000000000L,-2000000000000000000L
  (* 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 slen s = String.length s
  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,k = g2 0 in
  let a = iia n in
  let s = scanf " %s" @@ id in
  let r =
    let r = ref [] in
    let now = ref s.[0] in
    let cnt = ref 1L in
    let dmgs = ref [a.(0)] in
    String.iteri (fun i c ->
      if i=0 then ()
      else (
        if !now = c then (
          cnt += 1L;
          dmgs := a.(i) :: !dmgs;
        ) else (
          r := (List.sort (rv compare) !dmgs) :: !r;
          dmgs := a.(i) :: [];
          cnt := 1L;
        );
        now := c
      )
    ) s;
    if !cnt <> 0L then r := (List.sort (rv compare) !dmgs) :: !r;
    List.rev @@ !r
  in
  (* print_list (fun s -> string_of_list ist s ^ "\n") r; *)
  List.fold_left (fun sum ls ->
    if llen ls <= k then (
      sum + List.fold_left (+) 0L ls
    ) else (
      let s = ref 0L in
      List.iteri (fun i v -> if i64 i < k then s += v) ls;
      sum + !s
    )
  ) 0L r |> printf "%Ld"

let rv f p q = f q p
let (++),( ** ),(--) = Int64.(add,mul,sub);;
Scanf.(Array.(scanf " %d %d" @@ fun n k ->
  let a = init n (fun _ -> scanf " %Ld" @@ fun v -> v) in
  let b =
    let s = scanf " %s" @@ fun v -> v in
    init n (fun i -> s.[i])
  in
  let sects =
    let _,_,ls,all = fold_left (fun (i,prev,ls,all) c ->
      if i=0 then
        (i+1,c,a.(i)::ls,all)
      else
        if prev=c then
          (i+1,c,a.(i)::ls,all)
        else
          (i+1,c,[a.(i)],(List.sort (rv compare) ls)::all)
    ) (0,'_',[],[]) b
    in
    if List.length ls <> 0 then (List.sort (rv compare) ls)::all
    else all
  in
  Printf.printf "%Ld" @@
    List.fold_left (fun sum ls ->
      if List.length ls <= k then
        sum ++ List.fold_left (++) 0L ls
      else
        sum ++ snd (List.fold_left (fun (i,sum) v ->
          if i<k then (i+1,sum++v) else (i+1,sum)
        ) (0,0L) ls)
    ) 0L sects))

let rv f p q = f q p
let rec fix f x = f (fix f) x
;;
Scanf.(Array.(scanf " %d %d" @@ fun n k ->
  let a = init n (fun _ -> scanf " %d" @@ fun v -> v) in
  let s = scanf " %s" @@ fun v -> v in
  let sects = fix (fun f i ls all ->
    if i=0 then
      f (i+1) (a.(i)::ls) all
    else if i=n then
      if List.length ls <> 0 then (List.sort (rv compare) ls)::all
      else all
    else
      if s.[i] = s.[i-1] then
        f (i+1) (a.(i)::ls) all
      else
        f (i+1) [a.(i)] ((List.sort (rv compare) ls)::all)
  ) 0 [] []
  in
  print_int @@
    List.fold_left (fun sum ls ->
      if List.length ls <= k then
        sum + List.fold_left (+) 0 ls
      else
        sum + snd (List.fold_left (fun (i,sum) v ->
          if i<k then (i+1,sum+v) else (i+1,sum)
        ) (0,0) ls)
    ) 0 sects
))

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_lim,min_i64_lim = Int64.(max_int,min_int)
  let max_i64,min_i64 = 2000000000000000000L,-2000000000000000000L
  (* 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 slen s = String.length s
  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,k = g2 0 in
  let a = iia n in
  let s = scanf " %s" @@ id in
  let r =
    let r = ref [] in
    let now = ref s.[0] in
    let cnt = ref 1L in
    let dmgs = ref [a.(0)] in
    String.iteri (fun i c ->
      if i=0 then ()
      else (
        if !now = c then (
          cnt += 1L;
          dmgs := a.(i) :: !dmgs;
        ) else (
          r := (List.sort (rv compare) !dmgs) :: !r;
          dmgs := a.(i) :: [];
          cnt := 1L;
        );
        now := c
      )
    ) s;
    if !cnt <> 0L then r := (List.sort (rv compare) !dmgs) :: !r;
    List.rev @@ !r
  in
  print_list (fun s -> string_of_list ist s ^ "\n") r;
  List.fold_left (fun sum ls ->
    if llen ls <= k then (
      sum + List.fold_left (+) 0L ls
    ) else (
      let s = ref 0L in
      List.iteri (fun i v -> if i64 i < k then s += v) ls;
      sum + !s
    )
  ) 0L r |> printf "%Ld"


You are given the string s of length n and the numbers p, q. Split the string s to pieces of length p and q.For example, the string "Hello" for p = 2, q = 3 can be split to the two strings "Hel" and "lo" or to the two strings "He" and "llo".Note it is allowed to split the string s to the strings only of length p or to the strings only of length q (see the second sample test).

The first line contains three positive integers n, p, q (1 ≤ p, q ≤ n ≤ 100). The second line contains the string s consists of lowercase and uppercase latin letters and digits.

If it's impossible to split the string s to the strings of length p and q print the only number "-1". Otherwise in the first line print integer k — the number of strings in partition of s. Each of the next k lines should contain the strings in partition. Each string should be of the length p or q. The string should be in order of their appearing in string s — from left to right. If there are several solutions print any of them.

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let p = Scanf.bscanf sb "%d " (fun s -> s) in
  let q = Scanf.bscanf sb "%d " (fun s -> s) in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
    for i = 0 to n / p do
      if (n - i * p) mod q = 0 then (
	let a = i
	and b = (n - i * p) / q in
	let pos = ref 0 in
	  Printf.printf "%d\n" (a + b);
	  for i = 1 to a do
	    Printf.printf "%s\n" (String.sub s !pos p);
	    pos := !pos + p;
	  done;
	  for i = 1 to b do
	    Printf.printf "%s\n" (String.sub s !pos q);
	    pos := !pos + q;
	  done;
	  exit 0;
      )
    done;
    Printf.printf "-1\n"


You are given a set of points $$$x_1$$$, $$$x_2$$$, ..., $$$x_n$$$ on the number line.Two points $$$i$$$ and $$$j$$$ can be matched with each other if the following conditions hold:  neither $$$i$$$ nor $$$j$$$ is matched with any other point;  $$$|x_i - x_j| \ge z$$$. What is the maximum number of pairs of points you can match with each other?

The first line contains two integers $$$n$$$ and $$$z$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le z \le 10^9$$$) — the number of points and the constraint on the distance between matched points, respectively. The second line contains $$$n$$$ integers $$$x_1$$$, $$$x_2$$$, ..., $$$x_n$$$ ($$$1 \le x_i \le 10^9$$$).

Print one integer — the maximum number of pairs of points you can match with each other.

NoteIn the first example, you may match point $$$1$$$ with point $$$2$$$ ($$$|3 - 1| \ge 2$$$), and point $$$3$$$ with point $$$4$$$ ($$$|7 - 3| \ge 2$$$).In the second example, you may match point $$$1$$$ with point $$$3$$$ ($$$|5 - 10| \ge 5$$$).

let ( ++ ) = Int64.add
let ( -- ) = Int64.sub
let ( ** ) = Int64.mul
let ( // ) = Int64.div

let read_int _ = Scanf.scanf " %d " (fun n -> n)
let read_int64 _ = read_int () |> Int64.of_int

let () =
  let n = read_int () in
  let z = read_int64 () in
  let xs = Array.init n read_int64 in
  Array.fast_sort Int64.compare xs;
  let k = (n + 1) / 2 in
  let rec iter l r res =
    if r >= n || l >= k then
      res
    else if xs.(r) -- xs.(l) >= z then
      iter (l+1) (r+1) (res+1)
    else
      iter l (r+1) res in
  print_int (iter 0 k 0);
  print_newline ()

let ( ++ ) = Int64.add
let ( -- ) = Int64.sub
let ( ** ) = Int64.mul
let ( // ) = Int64.div

let () =
  let (n, z) = read_line ()
             |> Str.split (Str.regexp " ")
             |> (fun [a; b] -> (int_of_string a, Int64.of_string b)) in
  let xs = read_line ()
         |> Str.split (Str.regexp " ")
         |> Array.of_list
         |> Array.map Int64.of_string in
  Array.fast_sort Int64.compare xs;
  let k = (n + 1) / 2 in
  let l = ref 0 in
  let r = ref k in
  let res = ref 0 in
  while !l < k && !r < n do
    if xs.(!r) -- xs.(!l) >= z then
      (l := !l + 1;
       res := !res + 1;
      );
    r := !r + 1
  done;
  print_int !res;
  print_newline ()


You are given two $$$n \times m$$$ matrices containing integers. A sequence of integers is strictly increasing if each next number is greater than the previous one. A row is strictly increasing if all numbers from left to right are strictly increasing. A column is strictly increasing if all numbers from top to bottom are strictly increasing. A matrix is increasing if all rows are strictly increasing and all columns are strictly increasing. For example, the matrix $$$\begin{bmatrix} 9&10&11\\ 11&12&14\\ \end{bmatrix}$$$ is increasing because each individual row and column is strictly increasing. On the other hand, the matrix $$$\begin{bmatrix} 1&1\\ 2&3\\ \end{bmatrix}$$$ is not increasing because the first row is not strictly increasing.Let a position in the $$$i$$$-th row (from top) and $$$j$$$-th column (from left) in a matrix be denoted as $$$(i, j)$$$. In one operation, you can choose any two numbers $$$i$$$ and $$$j$$$ and swap the number located in $$$(i, j)$$$ in the first matrix with the number in $$$(i, j)$$$ in the second matrix. In other words, you can swap two numbers in different matrices if they are located in the corresponding positions.You would like to make both matrices increasing by performing some number of operations (possibly none). Determine if it is possible to do this. If it is, print "Possible", otherwise, print "Impossible".

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n,m \leq 50$$$) — the dimensions of each matrix. Each of the next $$$n$$$ lines contains $$$m$$$ integers $$$a_{i1}, a_{i2}, \ldots, a_{im}$$$ ($$$1 \leq a_{ij} \leq 10^9$$$) — the number located in position $$$(i, j)$$$ in the first matrix. Each of the next $$$n$$$ lines contains $$$m$$$ integers $$$b_{i1}, b_{i2}, \ldots, b_{im}$$$ ($$$1 \leq b_{ij} \leq 10^9$$$) — the number located in position $$$(i, j)$$$ in the second matrix.

Print a string "Impossible" or "Possible".

NoteThe first example, we can do an operation on the top left and bottom right cells of the matrices. The resulting matrices will be $$$\begin{bmatrix} 9&10\\ 11&12\\ \end{bmatrix}$$$ and $$$\begin{bmatrix} 2&4\\ 3&5\\ \end{bmatrix}$$$.In the second example, we don't need to do any operations.In the third example, no matter what we swap, we can't fix the first row to be strictly increasing in both matrices.

open Printf
open Scanf

let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))

let () =
  let (n,m) = read_pair () in

  let a = Array.make_matrix n m 0 in
  let b = Array.make_matrix n m 0 in

  for i=0 to n-1 do
    for j=0 to m-1 do
      a.(i).(j) <- read_int()
    done
  done;

  for i=0 to n-1 do
    for j=0 to m-1 do
      b.(i).(j) <- read_int()
    done
  done;

  for i=0 to n-1 do
    for j=0 to m-1 do
      let (x,y) = (a.(i).(j), b.(i).(j)) in
      a.(i).(j) <- min x y;
      b.(i).(j) <- max x y
    done
  done;

  let check1 =
    forall 0 (n-1) (fun i ->
      forall 1 (m-1) (fun j ->
	a.(i).(j-1) < a.(i).(j) && b.(i).(j-1) < b.(i).(j)
      )
    )
  in

  let check2 =
    forall 1 (n-1) (fun i ->
      forall 0 (m-1) (fun j ->
	a.(i-1).(j) < a.(i).(j) && b.(i-1).(j) < b.(i).(j)
      )
    )
  in

  if check1 && check2 then printf "Possible\n" else printf "Impossible\n"


Lunar New Year is approaching, and you bought a matrix with lots of "crosses".This matrix $$$M$$$ of size $$$n \times n$$$ contains only 'X' and '.' (without quotes). The element in the $$$i$$$-th row and the $$$j$$$-th column $$$(i, j)$$$ is defined as $$$M(i, j)$$$, where $$$1 \leq i, j \leq n$$$. We define a cross appearing in the $$$i$$$-th row and the $$$j$$$-th column ($$$1 < i, j < n$$$) if and only if $$$M(i, j) = M(i - 1, j - 1) = M(i - 1, j + 1) = M(i + 1, j - 1) = M(i + 1, j + 1) = $$$ 'X'.The following figure illustrates a cross appearing at position $$$(2, 2)$$$ in a $$$3 \times 3$$$ matrix. X.X.X.X.X Your task is to find out the number of crosses in the given matrix $$$M$$$. Two crosses are different if and only if they appear in different rows or columns.

The first line contains only one positive integer $$$n$$$ ($$$1 \leq n \leq 500$$$), denoting the size of the matrix $$$M$$$. The following $$$n$$$ lines illustrate the matrix $$$M$$$. Each line contains exactly $$$n$$$ characters, each of them is 'X' or '.'. The $$$j$$$-th element in the $$$i$$$-th line represents $$$M(i, j)$$$, where $$$1 \leq i, j \leq n$$$.

Output a single line containing only one integer number $$$k$$$ — the number of crosses in the given matrix $$$M$$$.

NoteIn the first sample, a cross appears at $$$(3, 3)$$$, so the answer is $$$1$$$.In the second sample, no crosses appear since $$$n < 3$$$, so the answer is $$$0$$$.In the third sample, crosses appear at $$$(3, 2)$$$, $$$(3, 4)$$$, $$$(4, 3)$$$, $$$(4, 5)$$$, so the answer is $$$4$$$.

let rec read_m n m = if n > 0 then let line = read_line() in List.append [line] (read_m (n - 1) m) else m in
let get m i j = String.get (List.nth m i) j in
let is_x m n i j = i >= 0 && j >= 0 && i < n && j < n && (get m i j) == 'X' in
let is_cross m n i j = (is_x m n (i - 1) (j + 1)) && (is_x m n (i + 1) (j + 1)) && (is_x m n (i - 1) (j - 1)) && (is_x m n (i + 1) (j - 1)) && (is_x m n i j) in
let rec number_of_crosses m n number i j = if i == n then number else number_of_crosses m n (number + (if is_cross m n i j then 1 else 0)) (if j == n - 1 then (i + 1) else i) (if j == n - 1 then 0 else (j + 1)) in
let n = int_of_string (read_line()) in
let m = read_m n [] in
print_string (string_of_int (number_of_crosses m n 0 0 0))


The Squareland national forest is divided into equal $$$1 \times 1$$$ square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates $$$(x, y)$$$ of its south-west corner.Three friends, Alice, Bob, and Charlie are going to buy three distinct plots of land $$$A, B, C$$$ in the forest. Initially, all plots in the forest (including the plots $$$A, B, C$$$) are covered by trees. The friends want to visit each other, so they want to clean some of the plots from trees. After cleaning, one should be able to reach any of the plots $$$A, B, C$$$ from any other one of those by moving through adjacent cleared plots. Two plots are adjacent if they share a side.    For example, $$$A=(0,0)$$$, $$$B=(1,1)$$$, $$$C=(2,2)$$$. The minimal number of plots to be cleared is $$$5$$$. One of the ways to do it is shown with the gray color. Of course, the friends don't want to strain too much. Help them find out the smallest number of plots they need to clean from trees.

The first line contains two integers $$$x_A$$$ and $$$y_A$$$ — coordinates of the plot $$$A$$$ ($$$0 \leq x_A, y_A \leq 1000$$$). The following two lines describe coordinates $$$(x_B, y_B)$$$ and $$$(x_C, y_C)$$$ of plots $$$B$$$ and $$$C$$$ respectively in the same format ($$$0 \leq x_B, y_B, x_C, y_C \leq 1000$$$). It is guaranteed that all three plots are distinct.

On the first line print a single integer $$$k$$$ — the smallest number of plots needed to be cleaned from trees. The following $$$k$$$ lines should contain coordinates of all plots needed to be cleaned. All $$$k$$$ plots should be distinct. You can output the plots in any order. If there are multiple solutions, print any of them.

NoteThe first example is shown on the picture in the legend.The second example is illustrated with the following image:

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 slen s = String.length s
  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 ps = make 3 (0L,0L) in
  repi 0 2 (fun i -> ps.(i) <- g2 0);
  let px = init 3 (fun i -> ps.(i)) in
  sort compare px;
  let py = init 3 (fun i -> ps.(i)) in
  sort (fun (p,q) (r,s) -> compare q s) py;
  let r = ref [] in
  let xx i = fst px.(i) in
  let yx i = snd px.(i) in
  rep (xx 0) (xx 1) (fun x ->
    r := (x, yx 0) :: !r
  );
  rep (xx 1) (xx 2) (fun x ->
    r := (x, yx 2) :: !r
  );
  rep (min (yx 0) (yx 1)) (max (yx 0) (yx 1)) (fun y ->
    r := (xx 1, y) :: !r
  );
  rep (min (yx 2) (yx 1)) (max (yx 2) (yx 1)) (fun y ->
    r := (xx 1, y) :: !r
  );
  r := List.sort_uniq compare !r;
  printf "%Ld\n" @@ llen !r;
  List.iter (fun (p,q) -> printf "%Ld %Ld\n" p q) !r

open Array
let p = init 3 (fun _ ->
  Scanf.scanf " %d %d" @@ fun u v -> u,v)
let () =
  let dmin = ref max_int in
  let dp,dq = ref 0,ref 0 in
  let _ =
    init 1001 (fun y ->
      init 1001 (fun x ->
        let w = fold_left (fun s (p,q) -> s + abs (x-p) + abs (y-q)) 0 p
        in if w < !dmin then (dmin := w; dp := x; dq := y)))
  in
  let res = ref [] in
  let line (p,q) (r,s) =
    let [|p,q;r,s|] = [p,q;r,s] |> List.sort compare |> of_list in
    for x=p to r do
      res := (x,q) :: !res
    done;
    for y=min q s to max q s do
      res := (r,y) :: !res
    done
  in
  let d = !dp,!dq in
  iter (fun t -> line t d) p;
  let res = List.sort_uniq compare !res in
  Printf.(
    printf "%d\n" @@ List.length res;
    List.iter (fun (p,q) ->
      printf "%d %d\n" p q
    ) res
  )


The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of $$$n$$$ haybale piles on the farm. The $$$i$$$-th pile contains $$$a_i$$$ haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) such that $$$|i-j|=1$$$ and $$$a_i>0$$$ and apply $$$a_i = a_i - 1$$$, $$$a_j = a_j + 1$$$. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile $$$1$$$ (i.e. to maximize $$$a_1$$$), and she only has $$$d$$$ days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile $$$1$$$ if she acts optimally!

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$)  — the number of test cases. Next $$$2t$$$ lines contain a description of test cases  — two lines per test case. The first line of each test case contains integers $$$n$$$ and $$$d$$$ ($$$1 \le n,d \le 100$$$) — the number of haybale piles and the number of days, respectively.  The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 100$$$)  — the number of haybales in each pile.

For each test case, output one integer: the maximum number of haybales that may be in pile $$$1$$$ after $$$d$$$ days if Bessie acts optimally.

NoteIn the first test case of the sample, this is one possible way Bessie can end up with $$$3$$$ haybales in pile $$$1$$$:   On day one, move a haybale from pile $$$3$$$ to pile $$$2$$$  On day two, move a haybale from pile $$$3$$$ to pile $$$2$$$  On day three, move a haybale from pile $$$2$$$ to pile $$$1$$$  On day four, move a haybale from pile $$$2$$$ to pile $$$1$$$  On day five, do nothing  In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile $$$2$$$ to pile $$$1$$$ on the second day.

open Scanf
open Printf
let read_int() = scanf " %d" (fun x -> x);;

let t = read_int() in
for z = 1 to t do
(
   let n = read_int() in
   let d = ref (read_int()) in
   let a = Array.make n 0 in
   for i = 0 to (n-1) do
      a.(i) <- read_int()
   done;
   for i = 1 to n-1 do (
   	   let c = min !d (i*a.(i)) in
   	   a.(0) <- a.(0) + c/i;
	   d := !d - c;
   )
   done;
   print_int a.(0);
   print_string "\n";
)
done


Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindrome numbers. Pari loves integers with even length (i.e. the numbers with even number of digits), so she tries to see a lot of big palindrome numbers with even length (like a 2-digit 11 or 6-digit 122221), so maybe she could see something in them.Now Pari asks you to write a program that gets a huge integer n from the input and tells what is the n-th even-length positive palindrome number?

The only line of the input contains a single integer n (1 ≤ n ≤ 10100 000).

Print the n-th even-length palindrome number.

NoteThe first 10 even-length palindrome numbers are 11, 22, 33, ... , 88, 99 and 1001.

let rec reverse s i j =
    if i < j then
        begin
            let c = s.[i] in
            s.[i] <- s.[j];
            s.[j] <- c;
            reverse s (i+1) (j-1);
        end
;;

let get_ans () =
    let s = read_line () in
    let () = print_string s in
    let () = reverse s 0 ((String.length s) - 1) in
    let () = print_string s in
    let () = print_string "\n" in
    ()
;;

let () = get_ans ()

let s = Scanf.scanf "%s" (fun x->x) in
    print_string s;
    for i = String.length s - 1 downto 0 do print_char s.[i] done

open Printf
open Scanf

let read_string () = bscanf Scanning.stdib " %s " (fun x -> x)

let () =
  let n = read_string () in

  let l = String.length n in

  printf "%s" n;

  for i=l-1 downto 0 do
    printf "%c" n.[i]
  done;

  print_newline()


A ticket is a string consisting of six digits. A ticket is considered lucky if the sum of the first three digits is equal to the sum of the last three digits. Given a ticket, output if it is lucky or not. Note that a ticket can have leading zeroes.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of testcases. The description of each test consists of one line containing one string consisting of six digits.

Output $$$t$$$ lines, each of which contains the answer to the corresponding test case. Output "YES" if the given ticket is lucky, and "NO" otherwise. You can output the answer in any case (for example, the strings "yEs", "yes", "Yes" and "YES" will be recognized as a positive answer).

NoteIn the first test case, the sum of the first three digits is $$$2 + 1 + 3 = 6$$$ and the sum of the last three digits is $$$1 + 3 + 2 = 6$$$, they are equal so the answer is "YES".In the second test case, the sum of the first three digits is $$$9 + 7 + 3 = 19$$$ and the sum of the last three digits is $$$8 + 9 + 4 = 21$$$, they are not equal so the answer is "NO".In the third test case, the sum of the first three digits is $$$0 + 4 + 5 = 9$$$ and the sum of the last three digits is $$$2 + 0 + 7 = 9$$$, they are equal so the answer is "YES".

(** https://codeforces.com/problemset/problem/1676/A *)

let lucky l =
    let rec sums li i sum_a sum_b =
        match li with
        | h::t ->
            if i > 2
            then sums t (i+1) sum_a (sum_b+h)
            else sums t (i+1) (sum_a+h) sum_b
        | [] -> sum_a, sum_b in
    let sum_a, sum_b = sums l 0 0 0 in
    sum_a = sum_b

let init_list i f =
    let rec helper i l =
        if i < 0
        then l
        else helper (i-1) ((f i)::l) in
    helper (i-1) []

let solve_n nb_cases =
    let rec helper i =
        if i > 0
        then (
            let ticket = read_line () in
            let ticket_list =
                init_list
                6
                (fun i -> (int_of_char ticket.[i]) - (int_of_char '0')) in
            print_endline (if lucky ticket_list then "YES" else "NO");
            helper (i-1)
        ) in
    helper nb_cases

let () =
    let nb_tickets = read_int () in
    solve_n nb_tickets


Devu being a small kid, likes to play a lot, but he only likes to play with arrays. While playing he came up with an interesting question which he could not solve, can you please solve it for him?Given an array consisting of distinct integers. Is it possible to partition the whole array into k disjoint non-empty parts such that p of the parts have even sum (each of them must have even sum) and remaining k - p have odd sum? (note that parts need not to be continuous).If it is possible to partition the array, also give any possible way of valid partitioning.

The first line will contain three space separated integers n, k, p (1 ≤ k ≤ n ≤ 105; 0 ≤ p ≤ k). The next line will contain n space-separated distinct integers representing the content of array a: a1, a2, ..., an (1 ≤ ai ≤ 109).

In the first line print "YES" (without the quotes) if it is possible to partition the array in the required way. Otherwise print "NO" (without the quotes). If the required partition exists, print k lines after the first line. The ith of them should contain the content of the ith part. Print the content of the part in the line in the following way: firstly print the number of elements of the part, then print all the elements of the part in arbitrary order. There must be exactly p parts with even sum, each of the remaining k - p parts must have odd sum. As there can be multiple partitions, you are allowed to print any valid partition.

open Printf
open Scanf

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

let () =
  let n = read_int () in
  let k = read_int () in
  let p = read_int () in
  let a = Array.init n (fun _ -> read_int()) in

  let rec loop evens odds i = if i=n then (evens, odds) else
      if a.(i) land 1 = 0 then loop (a.(i)::evens) odds (i+1) else loop evens (a.(i)::odds) (i+1)
  in

  let (evens,odds) = loop [] [] 0 in

  let evens = Array.of_list evens in
  let odds = Array.of_list odds in
  let nevens = Array.length evens in
  let nodds = Array.length odds in

  if (k-p) > nodds || p > nevens + (nodds-(k-p))/2 || (nodds-(k-p)) mod 2 = 1 then printf "NO\n" else (

    printf "YES\n";

    let oddsets = Array.make (k-p) [] in
    let evensets = Array.make p [] in

    for i=0 to k-p-1 do
      oddsets.(i) <- [odds.(i)]
    done;

    let oddsused = ref (k-p) in

    for i=0 to p-1 do
      if i<nevens then evensets.(i) <- [evens.(i)] else (
	evensets.(i) <- [odds.(!oddsused); odds.(!oddsused+1)];
	oddsused := !oddsused + 2
      )
    done;

    let remains = ref [] in

    for i = !oddsused to nodds-1 do
      remains := odds.(i) :: !remains
    done;

    for i=p to nevens-1 do
      remains := evens.(i) :: !remains
    done;

    if k-p > 0 then (
      oddsets.(0) <- !remains @ oddsets.(0)
    )else (
      evensets.(0) <- !remains @ evensets.(0)
    );

    let pset set sz =
      for i=0 to sz-1 do
	printf "%d " (List.length set.(i));
	List.iter (printf " %d") set.(i);
	print_newline ()
      done
    in

    pset oddsets (k-p);
    pset evensets p;
  )


Leo Jr. draws pictures in his notebook with checkered sheets (that is, each sheet has a regular square grid printed on it). We can assume that the sheets are infinitely large in any direction.To draw a picture, Leo Jr. colors some of the cells on a sheet gray. He considers the resulting picture beautiful if the following conditions are satisfied: The picture is connected, that is, it is possible to get from any gray cell to any other by following a chain of gray cells, with each pair of adjacent cells in the path being neighbours (that is, sharing a side). Each gray cell has an even number of gray neighbours. There are exactly $$$n$$$ gray cells with all gray neighbours. The number of other gray cells can be arbitrary (but reasonable, so that they can all be listed).Leo Jr. is now struggling to draw a beautiful picture with a particular choice of $$$n$$$. Help him, and provide any example of a beautiful picture.To output cell coordinates in your answer, assume that the sheet is provided with a Cartesian coordinate system such that one of the cells is chosen to be the origin $$$(0, 0)$$$, axes $$$0x$$$ and $$$0y$$$ are orthogonal and parallel to grid lines, and a unit step along any axis in any direction takes you to a neighbouring cell.

The only line contains a single integer $$$n$$$ ($$$1 \leq n \leq 500$$$) — the number of gray cells with all gray neighbours in a beautiful picture.

In the first line, print a single integer $$$k$$$ — the number of gray cells in your picture. For technical reasons, $$$k$$$ should not exceed $$$5 \cdot 10^5$$$. Each of the following $$$k$$$ lines should contain two integers — coordinates of a gray cell in your picture. All listed cells should be distinct, and the picture should satisdfy all the properties listed above. All coordinates should not exceed $$$10^9$$$ by absolute value. One can show that there exists an answer satisfying all requirements with a small enough $$$k$$$.

NoteThe answer for the sample is pictured below:

let rec solve (k : int) =
  if k < 0 then
    ()
  else
    (print_endline ((string_of_int k) ^ " " ^ (string_of_int k));
    print_endline ((string_of_int k) ^ " " ^ (string_of_int (k+1)));
    print_endline ((string_of_int (k+1)) ^ " " ^ (string_of_int k));
     solve (k - 1))
;;

let k = read_int() in
let () = print_endline (string_of_int (3 * (k + 1) + 1)) in
let () = solve k in
print_endline ((string_of_int (k+1)) ^ " " ^ (string_of_int (k+1)))

let rec solve (k : int) =
  if k < 0 then
    ()
  else
    (print_endline ((string_of_int k) ^ " " ^ (string_of_int k));
    print_endline ((string_of_int k) ^ " " ^ (string_of_int (k+1)));
    print_endline ((string_of_int (k+1)) ^ " " ^ (string_of_int k));
     solve (k - 1))
;;

let k = read_int() in
let () = solve k in
print_endline ((string_of_int (k+1)) ^ " " ^ (string_of_int (k+1)))


The Department of economic development of IT City created a model of city development till year 2100.To prepare report about growth perspectives it is required to get growth estimates from the model.To get the growth estimates it is required to solve a quadratic equation. Since the Department of economic development of IT City creates realistic models only, that quadratic equation has a solution, moreover there are exactly two different real roots.The greater of these roots corresponds to the optimistic scenario, the smaller one corresponds to the pessimistic one. Help to get these estimates, first the optimistic, then the pessimistic one.

The only line of the input contains three integers a, b, c ( - 1000 ≤ a, b, c ≤ 1000) — the coefficients of ax2 + bx + c = 0 equation.

In the first line output the greater of the equation roots, in the second line output the smaller one. Absolute or relative error should not be greater than 10 - 6.

let _ =
  let sb = Scanf.Scanning.stdib in
  let a = Scanf.bscanf sb "%f " (fun s -> s) in
  let b = Scanf.bscanf sb "%f " (fun s -> s) in
  let c = Scanf.bscanf sb "%f " (fun s -> s) in
  let d = b *. b -. 4.0 *. a *. c in
  let x1 = (-.b +. sqrt d) /. (2.0 *. a) in
  let x2 = (-.b -. sqrt d) /. (2.0 *. a) in
  let x1 = max x1 x2
  and x2 = min x1 x2 in
    Printf.printf "%.9f\n" x1;
    Printf.printf "%.9f\n" x2;

let _ =
  let sb = Scanf.Scanning.stdib in
  let a = Scanf.bscanf sb "%f " (fun s -> s) in
  let b = Scanf.bscanf sb "%f " (fun s -> s) in
  let c = Scanf.bscanf sb "%f " (fun s -> s) in
  let d = b *. b -. 4.0 *. a *. c in
  let x1 = (-.b +. sqrt d) /. 2.0 in
  let x2 = (-.b -. sqrt d) /. 2.0 in
  let x1 = max x1 x2
  and x2 = min x1 x2 in
    Printf.printf "%.6f\n" x1;
    Printf.printf "%.6f\n" x2;

let _ =
  let sb = Scanf.Scanning.stdib in
  let a = Scanf.bscanf sb "%f " (fun s -> s) in
  let b = Scanf.bscanf sb "%f " (fun s -> s) in
  let c = Scanf.bscanf sb "%f " (fun s -> s) in
  let d = b *. b -. 4.0 *. a *. c in
  let x1 = (-.b +. sqrt d) /. 2.0 in
  let x2 = (-.b -. sqrt d) /. 2.0 in
  let x1 = max x1 x2
  and x2 = min x1 x2 in
    Printf.printf "%.9f\n" x1;
    Printf.printf "%.9f\n" x2;


Alice guesses the strings that Bob made for her.At first, Bob came up with the secret string $$$a$$$ consisting of lowercase English letters. The string $$$a$$$ has a length of $$$2$$$ or more characters. Then, from string $$$a$$$ he builds a new string $$$b$$$ and offers Alice the string $$$b$$$ so that she can guess the string $$$a$$$.Bob builds $$$b$$$ from $$$a$$$ as follows: he writes all the substrings of length $$$2$$$ of the string $$$a$$$ in the order from left to right, and then joins them in the same order into the string $$$b$$$.For example, if Bob came up with the string $$$a$$$="abac", then all the substrings of length $$$2$$$ of the string $$$a$$$ are: "ab", "ba", "ac". Therefore, the string $$$b$$$="abbaac".You are given the string $$$b$$$. Help Alice to guess the string $$$a$$$ that Bob came up with. It is guaranteed that $$$b$$$ was built according to the algorithm given above. It can be proved that the answer to the problem is unique.

The first line contains a single positive integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case consists of one line in which the string $$$b$$$ is written, consisting of lowercase English letters ($$$2 \le |b| \le 100$$$) — the string Bob came up with, where $$$|b|$$$ is the length of the string $$$b$$$. It is guaranteed that $$$b$$$ was built according to the algorithm given above.

Output $$$t$$$ answers to test cases. Each answer is the secret string $$$a$$$, consisting of lowercase English letters, that Bob came up with.

NoteThe first test case is explained in the statement.In the second test case, Bob came up with the string $$$a$$$="ac", the string $$$a$$$ has a length $$$2$$$, so the string $$$b$$$ is equal to the string $$$a$$$.In the third test case, Bob came up with the string $$$a$$$="bcdaf", substrings of length $$$2$$$ of string $$$a$$$ are: "bc", "cd", "da", "af", so the string $$$b$$$="bccddaaf".

let rec loop (str : string) (pos : int) =
  if pos >= String.length str then
    ()
  else
    (print_char str.[pos];
     loop str (pos + 2))
;;

let rec main (t : int) =
  if t = 0 then
    ()
  else
    let st = read_line () in
    (print_char st.[0];
     loop st 1;
     print_endline "";
     main (t-1)
    )
;;

let t = read_int() in
main t


You have a sequence $$$a$$$ with $$$n$$$ elements $$$1, 2, 3, \dots, k - 1, k, k - 1, k - 2, \dots, k - (n - k)$$$ ($$$k \le n < 2k$$$).Let's call as inversion in $$$a$$$ a pair of indices $$$i < j$$$ such that $$$a[i] > a[j]$$$.Suppose, you have some permutation $$$p$$$ of size $$$k$$$ and you build a sequence $$$b$$$ of size $$$n$$$ in the following manner: $$$b[i] = p[a[i]]$$$.Your goal is to find such permutation $$$p$$$ that the total number of inversions in $$$b$$$ doesn't exceed the total number of inversions in $$$a$$$, and $$$b$$$ is lexicographically maximum.Small reminder: the sequence of $$$k$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$k$$$ exactly once.Another small reminder: a sequence $$$s$$$ is lexicographically smaller than another sequence $$$t$$$, if either $$$s$$$ is a prefix of $$$t$$$, or for the first $$$i$$$ such that $$$s_i \ne t_i$$$, $$$s_i < t_i$$$ holds (in the first position that these sequences are different, $$$s$$$ has smaller number than $$$t$$$).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$k \le n < 2k$$$; $$$1 \le k \le 10^5$$$) — the length of the sequence $$$a$$$ and its maximum. It's guaranteed that the total sum of $$$k$$$ over test cases doesn't exceed $$$10^5$$$.

For each test case, print $$$k$$$ integers — the permutation $$$p$$$ which maximizes $$$b$$$ lexicographically without increasing the total number of inversions. It can be proven that $$$p$$$ exists and is unique.

NoteIn the first test case, the sequence $$$a = [1]$$$, there is only one permutation $$$p = [1]$$$.In the second test case, the sequence $$$a = [1, 2]$$$. There is no inversion in $$$a$$$, so there is only one permutation $$$p = [1, 2]$$$ which doesn't increase the number of inversions.In the third test case, $$$a = [1, 2, 1]$$$ and has $$$1$$$ inversion. If we use $$$p = [2, 1]$$$, then $$$b = [p[a[1]], p[a[2]], p[a[3]]] = [2, 1, 2]$$$ and also has $$$1$$$ inversion.In the fourth test case, $$$a = [1, 2, 3, 2]$$$, and since $$$p = [1, 3, 2]$$$ then $$$b = [1, 3, 2, 3]$$$. Both $$$a$$$ and $$$b$$$ have $$$1$$$ inversion and $$$b$$$ is the lexicographically maximum.

open Str
open Big_int
open Num

let multitest = true

module Shortcuts = struct
  let loop n f = for i = 0 to n - 1 do f i; done

end

module Helper = struct
  open Shortcuts

  let read_s () = Scanf.scanf "%s\n" (fun x -> x)

  let read_int ?endl () =
    match endl with
    | None -> Scanf.scanf "%d " (fun x -> x)
    | Some () -> Scanf.scanf "%d\n" (fun x -> x)

  let read_array n =
    let a = Array.make n 0 in
    loop (n-1) (fun i -> a.(i) <- read_int ());
    a.(n-1) <- read_int ~endl:() ();
    a

end

module Ext = struct
  module List = struct
    let rec make n x =
      if (n <= 0) then []
      else x :: make (n-1) x

  end

end

module Alg = struct
  let rec gcd x y =
    if y <> 0 then (gcd y (x mod y))
    else (abs x)

  let lcm x y =
    if x = 0 || y = 0 then 0
    else abs (x * y) / (gcd x y)

end

let solve _ =
  let open Shortcuts in
  let open Helper in
  let open Printf in
  let open Ext in
  let open Alg in
  (* ***** Solution code here ***** *)
  let n = read_int () in
  let k = read_int ~endl:() () in
  loop (2*k - n-1) (fun i -> printf "%d " (i+1));
  loop (n - k+1) (fun i -> printf "%d " (k - i));
  printf "\n";
  (* ***** ******************* ***** *)
;;

let () =
  let open Helper in
  let open Shortcuts in
  let t = if multitest then read_int ~endl:() () else 1 in
  loop t solve;;


Dima, Inna and Seryozha have gathered in a room. That's right, someone's got to go. To cheer Seryozha up and inspire him to have a walk, Inna decided to cook something. Dima and Seryozha have n fruits in the fridge. Each fruit has two parameters: the taste and the number of calories. Inna decided to make a fruit salad, so she wants to take some fruits from the fridge for it. Inna follows a certain principle as she chooses the fruits: the total taste to the total calories ratio of the chosen fruits must equal k. In other words,  , where aj is the taste of the j-th chosen fruit and bj is its calories.Inna hasn't chosen the fruits yet, she is thinking: what is the maximum taste of the chosen fruits if she strictly follows her principle? Help Inna solve this culinary problem — now the happiness of a young couple is in your hands!Inna loves Dima very much so she wants to make the salad from at least one fruit.

The first line of the input contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10). The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100) — the fruits' tastes. The third line of the input contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 100) — the fruits' calories. Fruit number i has taste ai and calories bi.

If there is no way Inna can choose the fruits for the salad, print in the single line number -1. Otherwise, print a single integer — the maximum possible sum of the taste values of the chosen fruits.

NoteIn the first test sample we can get the total taste of the fruits equal to 18 if we choose fruit number 1 and fruit number 2, then the total calories will equal 9. The condition  fulfills, that's exactly what Inna wants.In the second test sample we cannot choose the fruits so as to follow Inna's principle.

let scan_int () = Scanf.scanf " %d" (fun x -> x);;
let scan_string () = Scanf.scanf " %s" (fun x -> x);;
let psp () = print_string " ";; let pnl () = print_newline ();;
let b2i x = if x == true then 1 else 0;;
let dbg x = print_int(x); pnl();;

let n = scan_int() and k = scan_int();;
let a = Array.init (n + 1) (fun i -> if i = 0 then 0 else scan_int());;
let b = Array.init (n + 1) (fun i -> if i = 0 then 0 else scan_int());;

let mx = 20007 and shift = 10003 and duzo = -1000000;;
let dp = Array.make_matrix (n + 1) mx duzo;;
dp.(0).(shift) <- 0;;

for i = 1 to n do
  let odejm = k * b.(i) in
  for j = 0 to mx - 1 do
    dp.(i).(j) <- (dp.(i - 1).(j));
    let wtedy = j - a.(i) + odejm in
    if wtedy >= 0 && wtedy < mx then dp.(i).(j) <- max dp.(i).(j) (dp.(i - 1).(wtedy) + b.(i));
  done;
done;;

if dp.(n).(shift) <= 0 then print_string("-1") else print_int(dp.(n).(shift) * k);;


In an English class Nick had nothing to do at all, and remembered about wonderful strings called palindromes. We should remind you that a string is called a palindrome if it can be read the same way both from left to right and from right to left. Here are examples of such strings: «eye», «pop», «level», «aba», «deed», «racecar», «rotor», «madam». Nick started to look carefully for all palindromes in the text that they were reading in the class. For each occurrence of each palindrome in the text he wrote a pair — the position of the beginning and the position of the ending of this occurrence in the text. Nick called each occurrence of each palindrome he found in the text subpalindrome. When he found all the subpalindromes, he decided to find out how many different pairs among these subpalindromes cross. Two subpalindromes cross if they cover common positions in the text. No palindrome can cross itself.Let's look at the actions, performed by Nick, by the example of text «babb». At first he wrote out all subpalindromes:• «b» — 1..1 • «bab» — 1..3 • «a» — 2..2 • «b» — 3..3 • «bb» — 3..4 • «b» — 4..4 Then Nick counted the amount of different pairs among these subpalindromes that cross. These pairs were six: 1. 1..1 cross with 1..3  2. 1..3 cross with 2..2  3. 1..3 cross with 3..3  4. 1..3 cross with 3..4  5. 3..3 cross with 3..4  6. 3..4 cross with 4..4 Since it's very exhausting to perform all the described actions manually, Nick asked you to help him and write a program that can find out the amount of different subpalindrome pairs that cross. Two subpalindrome pairs are regarded as different if one of the pairs contains a subpalindrome that the other does not.

The first input line contains integer n (1 ≤ n ≤ 2·106) — length of the text. The following line contains n lower-case Latin letters (from a to z).

In the only line output the amount of different pairs of two subpalindromes that cross each other. Output the answer modulo 51123987.

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

open Int64

let modulo = 51123987L
let ( ++ ) = add
let ( ** ) = mul
let ( -- ) = sub
let ( // ) = div
let ( %% ) = rem

let manacher a n =
  let z = Array.make n 0 in
  let rec go f g i =
    if i < n then
      if i < g && g-i <> z.(2*f-i) then (
        z.(i) <- min (g-i) z.(2*f-i);
        go f g (i+1)
      ) else (
        let rec go2 j =
          if j < n && 2*i-j >= 0 && a.[j] = a.[2*i-j] then
            go2 (j+1)
          else
            j
        in
        let g' = go2 (max g i) in
        z.(i) <- g'-i;
        go i g' (i+1)
      )
  in
  go 0 0 0;
  z

let () =
  let n = read_int () in
  let m = 2*n+1 in
  let a = read_str () in

  let b = String.make m '.' in
  for i = 0 to n-1 do
    b.[i*2+1] <- a.[i]
  done;
  let z = manacher b m in

  let l = Array.make (m+1) 0 in
  let r = Array.make (m+1) 0 in
  let ans = ref 0L in
  let rr = ref 0L in
  let add a x y = a.(x) <- a.(x) + y in
  for i = 0 to m-1 do
    add l (i-z.(i)+1) 1;
    add l (i+1) (-1);
    add r i 1;
    add r (i+z.(i)) (-1);
    ans := (!ans ++ of_int (z.(i)/2)) %% modulo
  done;
  ans := !ans ** (!ans -- 1L) // 2L %% modulo;
  for i = 0 to m-1 do
    if i > 0 then (
      add l i l.(i-1);
      add r i r.(i-1)
    );
    if i mod 2 = 1 then (
      ans := (!ans -- !rr ** of_int l.(i)) %% modulo;
      rr := !rr ++ of_int r.(i)
    )
  done;
  Printf.printf "%Ld\n" ((!ans ++ modulo) %% modulo)

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

open Int64

let modulo = 51123987L
let ( ++ ) = add
let ( ** ) = mul
let ( -- ) = sub
let ( // ) = div
let ( %% ) = rem

let manacher a n =
  let z = Array.make n 0 in
  let rec go f g i =
    if i < n then
      if i < g && g-i <> z.(2*f-i) then (
        z.(i) <- min (g-i) z.(2*f-i);
        go f g (i+1)
      ) else (
        let rec go2 j =
          if j < n && 2*i-j >= 0 && a.[j] = a.[2*i-j] then
            go2 (j+1)
          else
            j
        in
        let g' = go2 (max g i) in
        z.(i) <- g'-i;
        go i g' (i+1)
      )
  in
  go 0 0 0;
  z

let () =
  let n = read_int () in
  let m = 2*n+1 in
  let a = read_str () in

  let b = String.make m '.' in
  for i = 0 to n-1 do
    b.[i*2+1] <- a.[i]
  done;
  let z = manacher b m in

  let l = Array.make (m+1) 0 in
  let r = Array.make (m+1) 0 in
  let ans = ref 0L in
  let rr = ref 0L in
  let add a x y = a.(x) <- a.(x) + y in
  for i = 0 to m-1 do
    add l (i-z.(i)+1) 1;
    add l (i+1) (-1);
    add r i 1;
    add r (i+z.(i)) (-1);
    ans := !ans ++ of_int (z.(i)/2)
  done;
  ans := !ans ** (!ans -- 1L) // 2L %% modulo;
  for i = 0 to m-1 do
    if i > 0 then (
      add l i l.(i-1);
      add r i r.(i-1)
    );
    if i mod 2 = 1 then (
      ans := (!ans -- !rr ** of_int l.(i)) %% modulo;
      rr := !rr ++ of_int r.(i)
    )
  done;
  Printf.printf "%Ld\n" ((!ans ++ modulo) %% modulo)

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

open Int64

let modulo = 51123987L
let ( ++ ) = add
let ( ** ) = mul
let ( -- ) = sub
let ( // ) = div
let ( %% ) = rem

let manacher a n =
  let z = Array.make n 0 in
  let rec go f g i =
    if i < n then
      if i < g && g-i <> z.(2*f-i) then (
        z.(i) <- min (g-i) z.(2*f-i);
        go f g (i+1)
      ) else (
        let rec go2 j =
          if j < n && 2*i-j >= 0 && a.[j] = a.[2*i-j] then
            go2 (j+1)
          else
            j
        in
        let j = go2 i in
        z.(i) <- j-i;
        go i j (i+1)
      )
  in
  go 0 0 0;
  z

let () =
  let n = read_int () in
  let m = 2*n+1 in
  let a = read_str () in

  let b = String.make m '.' in
  for i = 0 to n-1 do
    b.[i*2+1] <- a.[i]
  done;
  let z = manacher b m in

  let l = Array.make (m+1) 0 in
  let r = Array.make (m+1) 0 in
  let ans = ref 0L in
  let rr = ref 0L in
  let add a x y = a.(x) <- a.(x) + y in
  for i = 0 to m-1 do
    add l (i-z.(i)+1) 1;
    add l (i+1) (-1);
    add r i 1;
    add r (i+z.(i)) (-1);
    ans := !ans ++ of_int (z.(i)/2)
  done;
  ans := !ans ** (!ans -- 1L) // 2L %% modulo;
  for i = 0 to m-1 do
    if i > 0 then (
      add l i l.(i-1);
      add r i r.(i-1)
    );
    if i mod 2 = 1 then (
      ans := (!ans -- !rr ** of_int l.(i)) %% modulo;
      rr := !rr ++ of_int r.(i)
    )
  done;
  Printf.printf "%Ld\n" !ans