A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k.You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-multiple free subset.

The first line of the input contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109). The next line contains a list of n distinct positive integers a1, a2, ..., an (1 ≤ ai ≤ 109). All the numbers in the lines are separated by single spaces.

On the only line of the output print the size of the largest k-multiple free subset of {a1, a2, ..., an}.

NoteIn the sample input one of the possible maximum 2-multiple free subsets is {4, 5, 6}.

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

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

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

  let () = Array.sort compare a in

  let h = Hashtbl.create 100 in

  let () =
    for i=0 to n-1 do
      Hashtbl.add h a.(i) false
    done in

  let rec mark_chain x i =
    if Hashtbl.mem h x then (
      if Hashtbl.find h x then 0 else (
	Hashtbl.replace h x true;
	mark_chain (x ** k) (i+1)
      )
    ) else i
  in

  let count = ref 0 in

    for i=0 to n-1 do
      let c = mark_chain a.(i) 0 in
	count := !count + ((c+1)/2)
    done;

    if k=1L then Printf.printf "%d\n" n
    else Printf.printf "%d\n" !count

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

let n = scan_int () and k = scan_int();;
let a = Array.make n 0;;

for i = 0 to n - 1 do a.(i) <- scan_int() done;
Array.sort compare a;

let cnt = ref 0 and q = Queue.create() in
for i = n - 1 downto 0 do
  while(not (Queue.is_empty q) && Queue.top q > a.(i)) do Queue.pop q; done;
  if(not (Queue.is_empty q) && Queue.top q = a.(i)) then incr cnt
  else if(a.(i) mod k = 0) then Queue.push (a.(i) / k) q;
done;

print_int(n - !cnt);

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

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

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

  let () = Array.sort compare a in

  let h = Hashtbl.create 100 in

  let () =
    for i=0 to n-1 do
      Hashtbl.add h a.(i) false
    done in

  let rec mark_chain x i =
    if Hashtbl.mem h x then (
      if Hashtbl.find h x then 0 else (
	Hashtbl.replace h x true;
	mark_chain (x ** k) (i+1)
      )
    ) else i
  in

  let count = ref 0 in

    for i=0 to n-1 do
      let c = mark_chain a.(i) 0 in
	count := !count + ((c+1)/2)
    done;

    Printf.printf "%d\n" !count

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

let n = scan_int () and k = scan_int();;
let a = Array.make n 0;;

for i = 0 to n - 1 do a.(i) <- scan_int() done;
Array.sort compare a;

let cnt = ref 0 and q = Queue.create() in
for i = n - 1 downto 0 do
  while(not (Queue.is_empty q) && Queue.top q > a.(i)) do Queue.pop q; done;
  if(not (Queue.is_empty q) && Queue.top q = a.(i)) then incr cnt;
  if(a.(i) mod k = 0) then Queue.push (a.(i) / k) q;
done;

print_int(n - !cnt);


You have a string $$$s$$$ consisting of digits from $$$0$$$ to $$$9$$$ inclusive. You can perform the following operation any (possibly zero) number of times:   You can choose a position $$$i$$$ and delete a digit $$$d$$$ on the $$$i$$$-th position. Then insert the digit $$$\min{(d + 1, 9)}$$$ on any position (at the beginning, at the end or in between any two adjacent digits). What is the lexicographically smallest string you can get by performing these operations?A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ of the same length if and only if the following holds:   in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a smaller digit than the corresponding digit in $$$b$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then the test cases follow. Each test case consists of a single line that contains one string $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$) — the string consisting of digits. Please note that $$$s$$$ is just a string consisting of digits, so leading zeros are allowed. It is guaranteed that the sum of lengths of $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

Print a single string — the minimum string that is possible to obtain.

NoteIn the first test case:   Delete $$$8$$$ and insert $$$9$$$ at the end of the notation. The resulting notation is $$$04299$$$.  Delete $$$4$$$ and insert $$$5$$$ in the $$$3$$$-rd position of the notation. The resulting notation is $$$02599$$$. Nothing needs to be done in the second and third test cases.

open Printf
open Scanf

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

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_string _ = bscanf Scanning.stdin " %s " (fun x -> x)
let l2d c = (int_of_char c) - (int_of_char '0')

let () =
  let cases = read_int() in
  for case = 1 to cases do
    let s = read_string () in
    let n = String.length s in
    let t = Array.init n (fun i -> l2d s.[i]) in
    let rightmost = Array.make 10 (-1) in

    for i=0 to n-1 do
      rightmost.(t.(i)) <- i
    done;

    let rec scan d st =
      (* count the number of d's at or after the point st *)
      if d = 10 || st >= n then ()
      else if rightmost.(d) < 0 then scan (d+1) st else (
	for i = st to rightmost.(d)-1 do
	  if t.(i) > d then t.(i) <- t.(i) + 1
	done;
	scan (d+1) (max st (rightmost.(d)+1))
      )
    in

    scan 0 0;

    Array.sort compare t;

    for i=0 to n-1 do
      printf "%d" (min t.(i) 9)
    done;
    print_newline()
  done

open Printf
open Scanf

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

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_string _ = bscanf Scanning.stdin " %s " (fun x -> x)
let l2d c = (int_of_char c) - (int_of_char '0')

let () =
  let cases = read_int() in
  for case = 1 to cases do
    let s = read_string () in
    let n = String.length s in
    let get i = l2d s.[i] in
    let t = Array.init n get in
(*
    let side = Array.make 10 0 in
*)
    let rightmost = Array.make 10 (-1) in

    for i=0 to n-1 do
      let d = get i in
      rightmost.(d) <- i
    done;

    let rec scan d st =
      (* count the number of d's at or after the point st *)
      if d = 10 || st >= n then ()
      else if rightmost.(d) < 0 then scan (d+1) st else (

	for i = st to rightmost.(d)-1 do
	  if t.(i) > d then t.(i) <- t.(i) + 1
	done;

	scan (d+1) (rightmost.(d)+1)

      )
    in

    scan 0 0;

    Array.sort compare t;

    for i=0 to n-1 do
      printf "%d" (min t.(i) 9)
    done;
    print_newline()
  done


Berland starts to seize the initiative on the war with Flatland. To drive the enemy from their native land, the berlanders need to know exactly how many more flatland soldiers are left in the enemy's reserve. Fortunately, the scouts captured an enemy in the morning, who had a secret encrypted message with the information the berlanders needed so much.The captured enemy had an array of positive integers. Berland intelligence have long been aware of the flatland code: to convey the message, which contained a number m, the enemies use an array of integers a. The number of its subarrays, in which there are at least k equal numbers, equals m. The number k has long been known in the Berland army so General Touristov has once again asked Corporal Vasya to perform a simple task: to decipher the flatlanders' message.Help Vasya, given an array of integers a and number k, find the number of subarrays of the array of numbers a, which has at least k equal numbers.Subarray a[i... j] (1 ≤ i ≤ j ≤ n) of array a = (a1, a2, ..., an) is an array, made from its consecutive elements, starting from the i-th one and ending with the j-th one: a[i... j] = (ai, ai + 1, ..., aj).

The first line contains two space-separated integers n, k (1 ≤ k ≤ n ≤ 4·105), showing how many numbers an array has and how many equal numbers the subarrays are required to have, correspondingly.  The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) — elements of the array.

Print the single number — the number of such subarrays of array a, that they have at least k equal integers. Please do not use the %lld specifier to read or write 64-bit integers in С++. In is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample are three subarrays, containing at least two equal numbers: (1,2,1), (2,1,2) and (1,2,1,2).In the second sample are two subarrays, containing three equal numbers: (1,2,1,1,3) and (1,2,1,1).In the third sample any subarray contains at least one 1 number. Overall they are 6: (1), (1), (1), (1,1), (1,1) and (1,1,1).

module M=Map.Make (struct type t = int let compare (a:int) b = compare a b end)

let _ =
    let id x = x in

    let get x map = try M.find x map with _ -> 0 in
    let inc x map = M.add x (1 + try M.find x map with _ -> 0) map in
    let del x map = M.add x (M.find x map - 1) map in

    let main () =
        let n, lim = Scanf.scanf "%d %d" (fun a b -> a, b) in
        let arr = Array.init n (fun _ -> Scanf.scanf " %d" id) in
        let rec initloop p map =
            if p >= n then 0. else
            let map = inc arr.(p) map in
            if get arr.(p) map >= lim then loop2 p 0 map 1 (float (n - p)) else
            initloop (p + 1) map
        and loop2 head tail map l acc =
            let x = arr.(tail) in
            if get x map = lim then (
                let l = l - 1 in
                if l > 0 then loop2 head (tail + 1) (del x map) l (acc +. float (n - head))
                         else loop3 (head + 1) (tail + 1) (del x map) acc
            ) else (
                loop2 head (tail + 1) (del x map) l (acc +. float (n - head))
            )
        and loop3 head tail map acc =
            if head >= n then acc else
            let map = inc arr.(head) map in
            if get arr.(head) map >= lim then loop2 head tail map 1 (acc +. float (n - head)) else
                loop3 (head + 1) tail map acc

        in

        let result = initloop 0 M.empty in
        Printf.printf "%.f\n%!" result
    in
    main ()


The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dn - 1 is the distance between the n - 1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t.

The first line contains integer n (3 ≤ n ≤ 100) — the number of stations on the circle line. The second line contains n integers d1, d2, ..., dn (1 ≤ di ≤ 100) — the distances between pairs of neighboring stations. The third line contains two integers s and t (1 ≤ s, t ≤ n) — the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces.

Print a single number — the length of the shortest path between stations number s and t.

NoteIn the first sample the length of path 1 → 2 → 3 equals 5, the length of path 1 → 4 → 3 equals 13.In the second sample the length of path 4 → 1 is 100, the length of path 4 → 3 → 2 → 1 is 15.In the third sample the length of path 3 → 1 is 1, the length of path 3 → 2 → 1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0.

let read_int () = Scanf.bscanf Scanf.Scanning.stdib " %d " (fun x -> x)
let read_pair () = let u = -1+read_int() in (u,-1+read_int())

let () =
  let n = read_int() in
  let d = Array.init n (fun i -> read_int()) in
  let (s,t) = read_pair() in

  let rec loop_up i ac = if i=t then ac else loop_up ((i+1) mod n) (ac + d.(i)) in

  let rec loop_down i ac = if i=t then ac else let ii = (i+n-1) mod n in loop_down ii (ac + d.(ii)) in

    Printf.printf "%d\n" (min (loop_up s 0) (loop_down s 0))


A TV show called "Guess a number!" is gathering popularity. The whole Berland, the old and the young, are watching the show.The rules are simple. The host thinks of an integer y and the participants guess it by asking questions to the host. There are four types of acceptable questions:  Is it true that y is strictly larger than number x?  Is it true that y is strictly smaller than number x?  Is it true that y is larger than or equal to number x?  Is it true that y is smaller than or equal to number x? On each question the host answers truthfully, "yes" or "no".Given the sequence of questions and answers, find any integer value of y that meets the criteria of all answers. If there isn't such value, print "Impossible".

The first line of the input contains a single integer n (1 ≤ n ≤ 10000) — the number of questions (and answers). Next n lines each contain one question and one answer to it. The format of each line is like that: "sign x answer", where the sign is:   ">" (for the first type queries),  "<" (for the second type queries),  ">=" (for the third type queries),  "<=" (for the fourth type queries).  All values of x are integer and meet the inequation  - 109 ≤ x ≤ 109. The answer is an English letter "Y" (for "yes") or "N" (for "no"). Consequtive elements in lines are separated by a single space.

Print any of such integers y, that the answers to all the queries are correct. The printed number y must meet the inequation  - 2·109 ≤ y ≤ 2·109. If there are many answers, print any of them. If such value doesn't exist, print word "Impossible" (without the quotes).

let n=read_int();;
let g=ref (Int64.of_string "-2000000000");;
let d=ref (Int64.of_string "2000000000");;
let l=ref (Int64.zero);;

for i=1 to n do
   let s=read_line() in
   begin
   if s.[1]='=' then l:=Int64.of_string(String.sub s 3 (String.length(s)-5))
                else l:=Int64.of_string(String.sub s 2 (String.length(s)-4));
   if ((s.[0]='<')&&(s.[1]='=')&&(s.[String.length(s)-1]='Y'))||((s.[0]='>')&&(s.[1]=' ')&&(s.[String.length(s)-1]='N')) then
      begin
      if !l< !d then d:= !l
      end
   else if ((s.[0]='>')&&(s.[1]='=')&&(s.[String.length(s)-1]='Y'))||((s.[0]='<')&&(s.[1]=' ')&&(s.[String.length(s)-1]='N')) then
      begin
      if !l > !g then g:= !l
      end
   else if ((s.[0]='>')&&(s.[1]=' ')&&(s.[String.length(s)-1]='Y'))||((s.[0]='<')&&(s.[1]='=')&&(s.[String.length(s)-1]='N')) then
      begin
      if (Int64.succ !l) > !g then g:= (Int64.succ !l)
      end
   else if ((s.[0]='<')&&(s.[1]=' ')&&(s.[String.length(s)-1]='Y'))||((s.[0]='>')&&(s.[1]='=')&&(s.[String.length(s)-1]='N')) then
      begin
      if (Int64.pred !l) < !d then d:= (Int64.pred !l)
      end
   end
done;;

if !g > !d then print_string "Impossible" else print_string(Int64.to_string !g);;

let n=read_int();;
let g=ref (Int64.of_string "-521");;
let d=ref (Int64.of_string "512");;
let l=ref (Int64.zero);;

for i=1 to n do
   let s=read_line() in
   begin
   if s.[1]='=' then l:=Int64.of_string(String.sub s 3 (String.length(s)-5))
                else l:=Int64.of_string(String.sub s 2 (String.length(s)-4));
   if ((s.[0]='<')&&(s.[1]='=')&&(s.[String.length(s)-1]='Y'))||((s.[0]='>')&&(s.[1]=' ')&&(s.[String.length(s)-1]='N')) then
      begin
      if !l< !d then d:= !l
      end
   else if ((s.[0]='>')&&(s.[1]='=')&&(s.[String.length(s)-1]='Y'))||((s.[0]='<')&&(s.[1]=' ')&&(s.[String.length(s)-1]='N')) then
      begin
      if !l > !g then g:= !l
      end
   else if ((s.[0]='>')&&(s.[1]=' ')&&(s.[String.length(s)-1]='Y'))||((s.[0]='<')&&(s.[1]='=')&&(s.[String.length(s)-1]='N')) then
      begin
      if (Int64.succ !l) > !g then g:= (Int64.succ !l)
      end
   else if ((s.[0]='<')&&(s.[1]=' ')&&(s.[String.length(s)-1]='Y'))||((s.[0]='>')&&(s.[1]='=')&&(s.[String.length(s)-1]='N')) then
      begin
      if (Int64.pred !l) < !d then d:= (Int64.pred !l)
      end
   end
done;;

if !g > !d then print_string "Impossible" else print_string(Int64.to_string !g);;

let n=read_int();;
let g=ref (Int64.of_string "-10000000000");;
let d=ref (Int64.of_string "10000000000");;
let l=ref (Int64.zero);;

for i=1 to n do
   let s=read_line() in
   begin
   if s.[1]='=' then l:=Int64.of_string(String.sub s 3 (String.length(s)-5))
                else l:=Int64.of_string(String.sub s 2 (String.length(s)-4));
   if ((s.[0]='<')&&(s.[1]='=')&&(s.[String.length(s)-1]='Y'))||((s.[0]='>')&&(s.[1]=' ')&&(s.[String.length(s)-1]='N')) then
      begin
      if !l< !d then d:= !l
      end
   else if ((s.[0]='>')&&(s.[1]='=')&&(s.[String.length(s)-1]='Y'))||((s.[0]='<')&&(s.[1]=' ')&&(s.[String.length(s)-1]='N')) then
      begin
      if !l > !g then g:= !l
      end
   else if ((s.[0]='>')&&(s.[1]=' ')&&(s.[String.length(s)-1]='Y'))||((s.[0]='<')&&(s.[1]='=')&&(s.[String.length(s)-1]='N')) then
      begin
      if (Int64.succ !l) > !g then g:= (Int64.succ !l)
      end
   else if ((s.[0]='<')&&(s.[1]=' ')&&(s.[String.length(s)-1]='Y'))||((s.[0]='>')&&(s.[1]='=')&&(s.[String.length(s)-1]='N')) then
      begin
      if (Int64.pred !l) < !d then d:= (Int64.pred !l)
      end
   end
done;;

if !g > !d then print_string "Impossible" else print_string(Int64.to_string !g);;


Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to time Anton would forget writing some letter and write it again. He asks you to count the total number of distinct letters in his set.

The first and the single line contains the set of letters. The length of the line doesn't exceed 1000. It is guaranteed that the line starts from an opening curved bracket and ends with a closing curved bracket. Between them, small English letters are listed, separated by a comma. Each comma is followed by a space.

Print a single number — the number of distinct letters in Anton's set.

(* module IntSet = Set.Make(
    struct
        let compare = Pervasives.compare
        type t = int
    end)  *)

module CharSet = Set.Make(Char)

let add s b =
    if String.length b == 0 then s
    else CharSet.add (String.get b 0) s

let x =
    let line = Str.split (Str.regexp "[{},] *") (read_line ()) in
    let s = List.fold_left add CharSet.empty line in
    print_int (CharSet.cardinal s);
    print_newline;

let get_list () =
    let letters = Pervasives.read_line () in
    let l = String.length letters in
    let rec loop i list =
        if i < 1
        then
            list
        else
            loop (i - 3) (letters.[i] :: list)
    in loop (l - 2) []

let rec get_uniques = function
    | head :: (middle :: _ as tail) ->
        if head = middle
        then
            get_uniques tail
        else
            (head :: get_uniques tail)
    | smaller -> smaller

let solve () = List.length (get_uniques (List.sort (Pervasives.compare) (get_list ())))

let print result = Printf.printf "%d\n" result
let () = print (solve ())

let get_list () =
    let letters = Pervasives.read_line () in
    let l = String.length letters in
    let rec loop i list =
        if i < 1
        then
            list
        else
            loop (i - 3) (letters.[i] :: list)
    in loop (l - 2) []

let rec get_uniques = function
    | head :: (middle :: _ as tail) ->
        if head = middle
        then
            get_uniques tail
        else
            (head :: get_uniques tail)
    | smaller -> smaller

let solve () = List.length (get_uniques (get_list ()))

let print result = Printf.printf "%d\n" result
let () = print (solve ())


Ivan is collecting coins. There are only $$$N$$$ different collectible coins, Ivan has $$$K$$$ of them. He will be celebrating his birthday soon, so all his $$$M$$$ freinds decided to gift him coins. They all agreed to three terms:  Everyone must gift as many coins as others. All coins given to Ivan must be different. Not less than $$$L$$$ coins from gifts altogether, must be new in Ivan's collection.But his friends don't know which coins have Ivan already got in his collection. They don't want to spend money so they want to buy minimum quantity of coins, that satisfy all terms, irrespective of the Ivan's collection. Help them to find this minimum number of coins or define it's not possible to meet all the terms.

The only line of input contains 4 integers $$$N$$$, $$$M$$$, $$$K$$$, $$$L$$$ ($$$1 \le K \le N \le 10^{18}$$$; $$$1 \le M, \,\, L \le 10^{18}$$$) — quantity of different coins, number of Ivan's friends, size of Ivan's collection and quantity of coins, that must be new in Ivan's collection.

Print one number — minimal number of coins one friend can gift to satisfy all the conditions. If it is impossible to satisfy all three conditions print "-1" (without quotes).

NoteIn the first test, one coin from each friend is enough, as he will be presented with 15 different coins and 13 of them will definitely be new.In the second test, Ivan has 11 friends, but there are only 10 different coins. So all friends can't present him different coins.

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
	(* math *)
	let ceildiv p q = (p+q-1L) / q
	let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
	let lcm m n = m / gcd m n * n
	module I64_infix = struct
		let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =
			let open Int64 in
			(logand),(logor),(logxor),lognot,
			(fun u v -> shift_left u (i32 v)),
			(fun u v -> shift_right u (i32 v)),
			(fun u v -> shift_right_logical u (i32 v))
	end
	(* input *)
	let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v))
	let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v)
	let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v)
	let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w)
	let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x)
	let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y)
	let i32_get_int _ = Scanf.scanf " %d" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf " %d %d" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y)
	(* utils *)
	external id : 'a -> 'a = "%identity"
	let 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)
	(* imperative *)
	let rep f t fbod =
		let rep0 f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i + 1L done
		in if f<=t then rep0 f t fbod else rep0 t f @@ fun v -> fbod @@ f + t - v
	let repb f t fbod =
		let rep0 f t fbod = let i,c = ref f,ref true in while !i <= t && !c do match fbod !i with | `Break -> c := false | `Ok -> i := !i + 1L done; !c
		in if f<=t then rep0 f t fbod
		else rep0 t f @@ fun v -> fbod @@ f + t - v
	let repm f t m0 fbod =
		let rep0 f t 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 + 1L done; !m
		in if f<=t then rep0 f t m0 fbod
		else rep0 t f m0 @@ fun u v -> fbod u @@ f + t - v
	let repi f t fbod =
		let rep0 f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ 1 done
		in if f<=t then rep0 f t fbod else rep0 t f @@ fun v -> fbod @@ f +$ t -$ v
	let repb f t fbod =
		let rep0 f t fbod = let i,c = ref f,ref true in while !i <= t && !c do
		match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ 1 done
		in if f<=t then rep0 f t fbod
		else rep0 t f @@ fun v -> fbod @@ f +$ t -$ v
	let repm f t m0 fbod =
		let rep0 f t 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 +$ 1 done; !m
		in if f<=t then rep0 f t m0 fbod
		else rep0 t f 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

let () =
	let n,m,k,l = get_4_i64 0 in
	let ans = ceildiv (l+k) m
	in (
		if
			ans < 1L || n < m || m*ans > n || n < l || k+l > n
		then -1L else ans
	)
	|> printf "%Ld\n"


Anatoly lives in the university dorm as many other students do. As you know, cockroaches are also living there together with students. Cockroaches might be of two colors: black and red. There are n cockroaches living in Anatoly's room.Anatoly just made all his cockroaches to form a single line. As he is a perfectionist, he would like the colors of cockroaches in the line to alternate. He has a can of black paint and a can of red paint. In one turn he can either swap any two cockroaches, or take any single cockroach and change it's color.Help Anatoly find out the minimum number of turns he needs to make the colors of cockroaches in the line alternate.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of cockroaches. The second line contains a string of length n, consisting of characters 'b' and 'r' that denote black cockroach and red cockroach respectively.

Print one integer — the minimum number of moves Anatoly has to perform in order to make the colors of cockroaches in the line to alternate.

NoteIn the first sample, Anatoly has to swap third and fourth cockroaches. He needs 1 turn to do this.In the second sample, the optimum answer is to paint the second and the fourth cockroaches red. This requires 2 turns.In the third sample, the colors of cockroaches in the line are alternating already, thus the answer is 0.

let kikou tab =
   let red_even = ref 0
   and blu_even = ref 0
   and red_odd = ref 0
   and blu_odd = ref 0
   in
      for i = 0 to String.length tab - 1 do
         incr @@ match tab.[i] , i mod 2 with
            | 'b', 0 -> blu_even
            | 'b', 1 -> blu_odd
            | 'r', 0 -> red_even
            | 'r', 1 -> red_odd
      done;
      !red_even, !blu_even, !red_odd, !blu_odd

let solve tab =
   let n = String.length tab in
   let (re,be,ro,bo) = kikou tab in
   let a = min re bo in
   let (re',be',ro',bo') = (re-a,be+a,ro+a,bo-a) in
      a + (((n+1)/2) - be') + ((n/2) - ro')

let olol =
   String.map (fun x -> if x = 'b' then 'r' else 'b')

let _ =
   let w = Scanf.scanf "%d %s" (fun _ w -> w) in
      Printf.printf "%d" (min (solve w) (solve (olol w)))

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 s = read_string () in

  let comp c = match c with 'r' -> 'b' | 'b' -> 'r' | _ -> failwith "bad input" in

  let solve c =
  (* c is the goal color of position 0 *)
    let rec loop i c rtob btor =
      if i=n then (rtob, btor) else
	let rtob = rtob + (if s.[i] = 'r' && c = 'b' then 1 else 0) in
	let btor = btor + (if s.[i] = 'b' && c = 'r' then 1 else 0) in
	loop (i+1) (comp c) rtob btor
    in
    let (rtob, btor) = loop 0 c 0 0 in
    let swaps = min rtob btor in
    (rtob + btor) - swaps
  in

  let answer = min (solve 'r') (solve 'b') in

  printf "%d\n" answer

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 s = read_string () in

  let comp c = match c with 'r' -> 'b' | 'b' -> 'r' | _ -> failwith "bad input" in

  let rec color i c ac =
    (* position i is already correctly colored c *)
    (* continue coloring from i+1 to the end *)
    if i = n-1 then ac else (
      if s.[i+1] = comp c then color (i+1) (comp c) ac
      else if i+2 < n && s.[i+2] <> s.[i+1] then color (i+2) c (ac+1)
      else color (i+1) (comp c) (ac+1)
    )
  in

  let answer = min (color (-1) 'r' 0) (color (-1) 'b' 0) in

  printf "%d\n" answer


Carol is currently curling.She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100.She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She will then push it so the disk’s y coordinate continuously decreases, and x coordinate stays constant. The disk stops once it touches the line y = 0 or it touches any previous disk. Note that once a disk stops moving, it will not move again, even if hit by another disk. Compute the y-coordinates of centers of all the disks after all disks have been pushed.

The first line will contain two integers n and r (1 ≤ n, r ≤ 1 000), the number of disks, and the radius of the disks, respectively. The next line will contain n integers x1, x2, ..., xn (1 ≤ xi ≤ 1 000) — the x-coordinates of the disks.

Print a single line with n numbers. The i-th number denotes the y-coordinate of the center of the i-th disk. The output will be accepted if it has absolute or relative error at most 10 - 6. Namely, let's assume that your answer for a particular value of a coordinate is a and the answer of the jury is b. The checker program will consider your answer correct if  for all coordinates.

NoteThe final positions of the disks will look as follows:  In particular, note the position of the last disk.

open Printf
open Scanf

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

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)

let () =
  let (n,r) = read_pair () in
  let x = Array.init n read_int in

  let height x0 x1 =
    let (x0,x1) = (min x0 x1, max x0 x1) in
    let d = x1 - x0 in
    if d > 2*r then -1.0
    else if d = 2*r then 0.0
    else
      let d = float d in
      let r = float r in
      sqrt ((sq (2.0 *. r)) -. (sq d))
  in

  let h = Array.make n 0.0 in

  h.(0) <- float r;
  printf "%.8f" h.(0);

  for i=1 to n-1 do
    h.(i) <- maxf 0 (i-1) (fun j ->
      let hh = height x.(i) x.(j) in
      if hh < 0.0 then float r else h.(j) +. hh
    );

    printf " %.8f" h.(i)
  done;

  print_newline()

open Printf
open Scanf

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

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)

let () =
  let (n,r) = read_pair () in
  let x = Array.init n read_int in

  let height x0 x1 =
    let (x0,x1) = (min x0 x1, max x0 x1) in
    let d = x1 - x0 in
    if d > 2*r then -1.0
    else if d = 2*r then 0.0
    else
      let d = float d in
      let r = float r in
      sqrt ((sq (2.0 *. r)) -. (sq d))
  in

  let h = Array.make n 0.0 in

  h.(0) <- float r;

  for i=1 to n-1 do
    h.(i) <- maxf 0 (i-1) (fun j ->
      let hh = height x.(i) x.(j) in
      if hh < 0.0 then float r else h.(j) +. hh
    );

    printf "%.8f " h.(i)
  done;

  print_newline()


This is yet another problem on regular bracket sequences.A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequence that consists of characters "(", ")" and "?". You have to replace each character "?" with a bracket so, that you get a regular bracket sequence.For each character "?" the cost of its replacement with "(" and ")" is given. Among all the possible variants your should choose the cheapest.

The first line contains a non-empty pattern of even length, consisting of characters "(", ")" and "?". Its length doesn't exceed 5·104. Then there follow m lines, where m is the number of characters "?" in the pattern. Each line contains two integer numbers ai and bi (1 ≤ ai,  bi ≤ 106), where ai is the cost of replacing the i-th character "?" with an opening bracket, and bi — with a closing one.

Print the cost of the optimal regular bracket sequence in the first line, and the required sequence in the second. Print -1, if there is no answer. If the answer is not unique, print any of them.

module type ZeroOrderedType = sig
  type t
  val compare: t -> t -> int
  val zero: t
end

exception No

module Heap(Ord: ZeroOrderedType) = struct
  type 'a t = { mutable size: int; data: 'a array }
  let create capacity = { size = 0; data = Array.make capacity Ord.zero }

  let up h pos key =
    let rec go pos =
      let pos2 = (pos-1)/2 in
      if pos > 0 && Ord.compare key h.data.(pos2) < 0 then (
        h.data.(pos) <- h.data.(pos2);
        go pos2
      ) else
        pos
    in
    h.data.(go pos) <- key

  let down h pos key =
    let rec go pos =
      let pos2 = ref (pos*2+1) in
      if !pos2 < h.size then (
        if !pos2+1 < h.size && Ord.compare h.data.(!pos2+1) h.data.(!pos2) < 0 then
          pos2 := !pos2+1;
        if Ord.compare h.data.(!pos2) key < 0 then (
          h.data.(pos) <- h.data.(!pos2);
          go !pos2
        ) else
          pos
      ) else
        pos
    in
    h.data.(go pos) <- key

  let push h key =
    up h h.size key;
    h.size <- h.size+1

  let pop h =
    let ret = h.data.(0) in
    h.size <- h.size-1;
    down h 0 h.data.(h.size);
    ret

  let empty h =
    h.size = 0
end

module IIHeap = Heap(struct type t = int*int let compare = compare let zero = 0,0 end)

let () =
  let c = ref 0
  and ans = ref 0L
  and a = read_line () in
  let h = IIHeap.create (String.length a) in
  try
    String.iteri (fun i ch ->
      (match ch with
      | '(' ->
        c := !c+1
      | ')' ->
        c := !c-1;
      | '?' ->
        let x,y = Scanf.sscanf (read_line ()) "%d %d" (fun x y -> x,y) in
        a.[i] <- ')';
        c := !c-1;
        ans := Int64.add !ans (Int64.of_int y);
        IIHeap.push h (x-y,i));
      if !c < 0 then (
        if IIHeap.empty h then (
          c := 1;
          raise No
        );
        let v,p = IIHeap.pop h in
        ans := Int64.add !ans (Int64.of_int v);
        a.[p] <- '(';
        c := !c+2;
      )
    ) a;
    if !c <> 0 then
      raise No;
    Printf.printf "%Ld\n%s\n" !ans a
  with _ ->
    print_endline "-1"

module type ZeroOrderedType = sig
  type t
  val compare: t -> t -> int
  val zero: t
end

exception No

module Heap(Ord: ZeroOrderedType) = struct
  type 'a t = { mutable size: int; data: 'a array }
  let create capacity = { size = 0; data = Array.make capacity Ord.zero }

  let up h pos key =
    let rec go pos =
      let pos2 = (pos-1)/2 in
      if pos > 0 && Ord.compare key h.data.(pos2) < 0 then (
        h.data.(pos) <- h.data.(pos2);
        go pos2
      ) else
        pos
    in
    h.data.(go pos) <- key

  let down h pos key =
    let rec go pos =
      let pos2 = ref (pos*2+1) in
      if !pos2 < h.size then (
        if !pos2+1 < h.size && Ord.compare h.data.(!pos2+1) h.data.(!pos2) < 0 then
          pos2 := !pos2+1;
        if Ord.compare h.data.(!pos2) key < 0 then (
          h.data.(pos) <- h.data.(!pos2);
          go !pos2
        ) else
          pos
      ) else
        pos
    in
    h.data.(go pos) <- key

  let push h key =
    up h h.size key;
    h.size <- h.size+1

  let pop h =
    let ret = h.data.(0) in
    h.size <- h.size-1;
    down h 0 h.data.(h.size);
    ret

  let empty h =
    h.size = 0
end

module IIHeap = Heap(struct type t = int*int let compare = compare let zero = 0,0 end)

let () =
  let c = ref 0
  and ans = ref 0
  and a = read_line () in
  let h = IIHeap.create (String.length a) in
  try
    String.iteri (fun i ch ->
      (match ch with
      | '(' ->
        c := !c+1
      | ')' ->
        c := !c-1;
      | '?' ->
        let x,y = Scanf.sscanf (read_line ()) "%d %d" (fun x y -> x,y) in
        a.[i] <- ')';
        c := !c-1;
        ans := !ans+y;
        IIHeap.push h (x-y,i));
      if !c < 0 then (
        if IIHeap.empty h then (
          c := 1;
          raise No
        );
        let v,p = IIHeap.pop h in
        ans := !ans+v;
        a.[p] <- '(';
        c := !c+2;
      )
    ) a;
    if !c <> 0 then
      raise No;
    Printf.printf "%d\n%s\n" !ans a
  with _ ->
    print_endline "-1"


Some number of people (this number is even) have stood in a circle. The people stand in the circle evenly. They are numbered clockwise starting from a person with the number $$$1$$$. Each person is looking through the circle's center at the opposite person.    A sample of a circle of $$$6$$$ persons. The orange arrows indicate who is looking at whom. You don't know the exact number of people standing in the circle (but this number is even, no doubt). It is known that the person with the number $$$a$$$ is looking at the person with the number $$$b$$$ (and vice versa, of course). What is the number associated with a person being looked at by the person with the number $$$c$$$? If, for the specified $$$a$$$, $$$b$$$, and $$$c$$$, no such circle exists, output -1.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing three distinct integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a,b,c \le 10^8$$$).

For each test case output in a separate line a single integer $$$d$$$ — the number of the person being looked at by the person with the number $$$c$$$ in a circle such that the person with the number $$$a$$$ is looking at the person with the number $$$b$$$. If there are multiple solutions, print any of them. Output $$$-1$$$ if there's no circle meeting the given conditions.

NoteIn the first test case, there's a desired circle of $$$8$$$ people. The person with the number $$$6$$$ will look at the person with the number $$$2$$$ and the person with the number $$$8$$$ will look at the person with the number $$$4$$$.In the second test case, there's no circle meeting the conditions. If the person with the number $$$2$$$ is looking at the person with the number $$$3$$$, the circle consists of $$$2$$$ people because these persons are neighbors. But, in this case, they must have the numbers $$$1$$$ and $$$2$$$, but it doesn't meet the problem's conditions.In the third test case, the only circle with the persons with the numbers $$$2$$$ and $$$4$$$ looking at each other consists of $$$4$$$ people. Therefore, the person with the number $$$10$$$ doesn't occur in the circle.

open Array;;
let readInt () = Scanf.scanf " %d" (fun i -> i)

let print_number x = print_string (string_of_int x); print_newline();;

let abs a =
  if a < 0 then a*(-1)
  else a;;

let check a b c n =
  if a > n then false
  else if b > n then false
  else if c > n then false
  else true;;

let t = readInt() in
let ans = ref 0 in
for i = 1 to t do
  let a = readInt() in
  let b = readInt() in
  let c = readInt() in
  let n = 2 * abs (a-b) in
  let () =
    if check a b c n then
      if c > (n/2) then
        ans := c - (n/2)
      else
        ans := c + (n/2)
    else
      ans := -1
  in
  print_number !ans;
done;;


Before the start of the football season in Berland a strange magic ritual is held. The most experienced magicians have to find a magic matrix of the size n × n (n is even number). Gods will never allow to start the championship without it. Matrix should contain integers from 0 to n - 1, main diagonal should contain only zeroes and matrix should be symmetric. Moreover, all numbers in each row should be different. Magicians are very tired of the thinking process, so they ask you to write a program to find such matrix.

The first line contains one integer n (2 ≤ n ≤ 1000), n is even.

Output n lines with n numbers each — the required matrix. Separate numbers with spaces. If there are several solutions, output any.

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

let () =
  let n = read_int 0 in
  for i = 0 to n-1 do
    for j = 0 to n-1 do
      Printf.printf "%d%c" (if i = j then 0
        else if i = n-1 || j = n-1 then
          min i j * 2 mod (n-1) + 1
        else
          (i+j) mod (n-1) + 1)
        (if j == n-1 then '\n' else ' ')
    done
  done


Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed x in the absolute value.Natasha doesn't like when Vanya spends a long time playing, so she hid all of his cards. Vanya became sad and started looking for the cards but he only found n of them. Vanya loves the balance, so he wants the sum of all numbers on found cards equal to zero. On the other hand, he got very tired of looking for cards. Help the boy and say what is the minimum number of cards does he need to find to make the sum equal to zero?You can assume that initially Vanya had infinitely many cards with each integer number from  - x to x.

The first line contains two integers: n (1 ≤ n ≤ 1000) — the number of found cards and x (1 ≤ x ≤ 1000) — the maximum absolute value of the number on a card. The second line contains n space-separated integers — the numbers on found cards. It is guaranteed that the numbers do not exceed x in their absolute value.

Print a single number — the answer to the problem.

NoteIn the first sample, Vanya needs to find a single card with number -2.In the second sample, Vanya needs to find two cards with number 2. He can't find a single card with the required number as the numbers on the lost cards do not exceed 3 in their absolute value.

open Printf
open Scanf

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

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

let () =
  let n = read_int() in
  let x = read_int() in
  let input = Array.init n (fun _ -> read_int()) in
  let s = sum 0 (n-1) (fun i -> input.(i)) in

  (* want the minimum number of cards such that their sum when
     combined with s is zero.  *)

  let s = abs s in
  let k = s/x in
  let k = if k*x = s then k else k+1 in
  printf "%d\n" k

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int() and x=read_int();;
let s=ref 0;;
for i=1 to n do
   s:= !s+read_int()
done;;
if !s<0 then s:= 0- !s;;
s:= !s+x-1;;
print_int ( !s/x);;

let k = int_of_string (List.nth (Str.split (Str.regexp_string " ") (read_line ())) 1);;
let s = List.map int_of_string (Str.split (Str.regexp_string " ") (read_line ()));;
let sum = abs (List.fold_left ( + ) 0 s);;
print_newline (print_int ((fun x -> if x * k < sum then (x + 1) else x) (sum / k)));;

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int() and x=read_int();;
let s=ref 0;;
for i=1 to n do
   s:= !s+read_int()
done;;
if !s<0 then s:= 0- !s;;
print_int ( !s/x);;

let k = int_of_string (List.nth (Str.split (Str.regexp_string " ") (read_line ())) 1);;
let s = List.map int_of_string (Str.split (Str.regexp_string " ") (read_line ()));;
let sum = abs (List.fold_left ( + ) 0 s);;
print_newline (print_int ((fun x -> if x * k < sum then x + 1 else x) (sum mod k)));;


Do you know a story about the three musketeers? Anyway, you will learn about its origins now.Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys.There are n warriors. Richelimakieu wants to choose three of them to become musketeers but it's not that easy. The most important condition is that musketeers must know each other to cooperate efficiently. And they shouldn't be too well known because they could be betrayed by old friends. For each musketeer his recognition is the number of warriors he knows, excluding other two musketeers.Help Richelimakieu! Find if it is possible to choose three musketeers knowing each other, and what is minimum possible sum of their recognitions.

The first line contains two space-separated integers, n and m (3 ≤ n ≤ 4000, 0 ≤ m ≤ 4000) — respectively number of warriors and number of pairs of warriors knowing each other. i-th of the following m lines contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Warriors ai and bi know each other. Each pair of warriors will be listed at most once.

If Richelimakieu can choose three musketeers, print the minimum possible sum of their recognitions. Otherwise, print "-1" (without the quotes).

NoteIn the first sample Richelimakieu should choose a triple 1, 2, 3. The first musketeer doesn't know anyone except other two musketeers so his recognition is 0. The second musketeer has recognition 1 because he knows warrior number 4. The third musketeer also has recognition 1 because he knows warrior 4. Sum of recognitions is 0 + 1 + 1 = 2.The other possible triple is 2, 3, 4 but it has greater sum of recognitions, equal to 1 + 1 + 1 = 3.In the second sample there is no triple of warriors knowing each other.

(* number of warriors n
 * number of pairs m *)
let () = Scanf.scanf "%d %d\n" (fun n m ->
				(* adjacency matrix *)
				let k = Array.make_matrix n n false
				(* recognition of each warrior *)
				and r = Array.make n 0
				(* adjacency list *)
				and d = Array.make n [] in

				(* populate adjacency and recognition *)
				for i = 1 to m do
				  Scanf.scanf "%d %d\n" (fun a b ->
							 k.(a - 1).(b - 1) <- true;
							 k.(b - 1).(a - 1) <- true;
							 r.(a - 1) <- r.(a - 1) + 1;
							 r.(b - 1) <- r.(b - 1) + 1;
							 d.(a - 1) <- (b - 1) :: d.(a - 1);
							 d.(b - 1) <- (a - 1) :: d.(b - 1))
				done;

				let m = ref 15000 in

				for i = 0 to (n - 2) do
				  for j = (i + 1) to (n - 1) do
				    if k.(i).(j) then
				    List.iter (fun l -> if k.(j).(l) then m := min !m (r.(i) + r.(j) + r.(l) - 6)) d.(i)
				  done
				done;

				Printf.printf "%d\n" (if !m = 15000 then (-1) else !m))


It is the easy version of the problem. The only difference is that in this version $$$a_i \le 200$$$.You are given an array of $$$n$$$ integers $$$a_0, a_1, a_2, \ldots a_{n - 1}$$$. Bryap wants to find the longest beautiful subsequence in the array.An array $$$b = [b_0, b_1, \ldots, b_{m-1}]$$$, where $$$0 \le b_0 < b_1 < \ldots < b_{m - 1} < n$$$, is a subsequence of length $$$m$$$ of the array $$$a$$$.Subsequence $$$b = [b_0, b_1, \ldots, b_{m-1}]$$$ of length $$$m$$$ is called beautiful, if the following condition holds:   For any $$$p$$$ ($$$0 \le p < m - 1$$$) holds: $$$a_{b_p} \oplus b_{p+1} < a_{b_{p+1}} \oplus b_p$$$. Here $$$a \oplus b$$$ denotes the bitwise XOR of $$$a$$$ and $$$b$$$. For example, $$$2 \oplus 4 = 6$$$ and $$$3 \oplus 1=2$$$.Bryap is a simple person so he only wants to know the length of the longest such subsequence. Help Bryap and find the answer to his question.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 3 \cdot 10^5$$$) — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_0,a_1,...,a_{n-1}$$$ ($$$0 \leq a_i \leq 200$$$) — the elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For each test case print a single integer — the length of the longest beautiful subsequence.

NoteIn the first test case, we can pick the whole array as a beautiful subsequence because $$$1 \oplus 1 < 2 \oplus 0$$$.In the second test case, we can pick elements with indexes $$$1$$$, $$$2$$$ and $$$4$$$ (in $$$0$$$-indexation). For this elements holds: $$$2 \oplus 2 < 4 \oplus 1$$$ and $$$4 \oplus 4 < 1 \oplus 2$$$.

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_array read n = A.init n (fun _ -> read ())

module BitTrie = struct
  let inf = 1000000000;

  type t = {
    bit_v: int;
    children: (t option) array;
    mx_ans: int array;
  }

  let init bit_size = {
    bit_v = bit_size - 1;
    children = [| None; None |];
    mx_ans = [| -inf; -inf; -inf; -inf |]
  }

  let insert i x (root:t): t * int =
    let xr = i lxor x in
    let go_to bit_v (bit: int)  (t:t) =
      let child = t.children.(bit) in
      if (child = None) then init bit_v
      else Opt.get child
    in
    let rec insert' (t:t): t * int =
      let bit = t.bit_v in
      let bit_x = (x lsr bit) land 1 lxor 1 in
      let bit_i = (i lsr bit) land 1 in
      let bit_xr = (xr lsr bit) land 1 in
      let cur_ans = t.mx_ans.(2 * bit_x + bit_i) in
      let child = go_to bit bit_xr t in
      let (new_child, child_ans) =
        if (bit = 0) then (child, -inf)
        else insert' child in
      let ret_ans = max cur_ans child_ans in
      t.children.(bit_xr) <- Some new_child;
      (t, ret_ans)
    in

    let (new_root, mx) = insert' root in
    let ans = max mx 0 + 1 in

    let rec relax (t:t) =
      let bit = t.bit_v in
      let bit_x = (x lsr bit) land 1 in
      let bit_i = (i lsr bit) land 1 in
      let coord = 2 * bit_i + bit_x in
      t.mx_ans.(coord) <- max t.mx_ans.(coord) ans;
      let bit_xr = (xr lsr bit) land 1 in
      if (bit = 0) then ()
      else relax (go_to bit bit_xr t)
    in
    relax new_root;
    (new_root, ans)

end

let () =
  let t = read_int () in
  for _ = 1 to t do
    let n = read_int () in
    let a = read_array read_int n in
    let t = BitTrie.init 20 in
    let (_, res) = A.fold_left (
      fun (t, mx) (i, v) ->
        let (new_root, ans) = BitTrie.insert i v t in
        (new_root, max ans mx)
      ) (t, 0) (A.mapi (fun i x -> (i, x)) a) in
    pf "%d\n" res;
  done;


You are given an integer $$$n$$$ and an array $$$a_1, a_2, \ldots, a_n$$$. You should reorder the elements of the array $$$a$$$ in such way that the sum of $$$\textbf{MEX}$$$ on prefixes ($$$i$$$-th prefix is $$$a_1, a_2, \ldots, a_i$$$) is maximized.Formally, you should find an array $$$b_1, b_2, \ldots, b_n$$$, such that the sets of elements of arrays $$$a$$$ and $$$b$$$ are equal (it is equivalent to array $$$b$$$ can be found as an array $$$a$$$ with some reordering of its elements) and $$$\sum\limits_{i=1}^{n} \textbf{MEX}(b_1, b_2, \ldots, b_i)$$$ is maximized.$$$\textbf{MEX}$$$ of a set of nonnegative integers is the minimal nonnegative integer such that it is not in the set.For example, $$$\textbf{MEX}(\{1, 2, 3\}) = 0$$$, $$$\textbf{MEX}(\{0, 1, 2, 4, 5\}) = 3$$$.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 100)$$$  — the number of test cases. The first line of each test case contains a single integer $$$n$$$ $$$(1 \le n \le 100)$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(0 \le a_i \le 100)$$$.

For each test case print an array $$$b_1, b_2, \ldots, b_n$$$  — the optimal reordering of $$$a_1, a_2, \ldots, a_n$$$, so the sum of $$$\textbf{MEX}$$$ on its prefixes is maximized. If there exist multiple optimal answers you can find any.

(* https://codeforces.com/contest/1497/problem/0 *)
let make_hist arr =
    let histo = Array.make 101 0 in
    Array.iter
        (fun e -> histo.(e) <- histo.(e) + 1)
        arr;
    histo

let rec add_ntimes i n el arr =
    if n > 0
    then
        let _ = arr.(i) <- el in
        add_ntimes (i+1) (n-1) el arr

let meximization arr =
    let len = Array.length arr in
    let meximized = Array.make len 0 and
    mex_i = ref 0 and
    histo = make_hist arr in
    Array.iteri
        (fun i e ->
            if e <> 0
            then begin
                meximized.(!mex_i) <- i;
                mex_i := !mex_i + 1;
                histo.(i) <- histo.(i) - 1
            end)
        histo;
    Array.iteri
        (fun i e ->
            if e <> 0
            then begin
                add_ntimes !mex_i e i meximized;
                mex_i := !mex_i + e
            end)
        histo;
    meximized

let read_case () =
    let _ = read_int () in
    let arr =
        read_line ()
        |> Str.split (Str.regexp " ")
        |> List.map int_of_string
        |> Array.of_list in
    arr

let solve_n n =
    let rec helper i =
        if i > 0
        then
            let arr = read_case () in
            let solution = meximization arr in
            let _ = Array.iter (Printf.printf "%d ") solution and
            _ = print_newline () in
            helper (i-1) in
    helper n

let () =
    let nb_cases = read_int () in
    solve_n nb_cases


Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set.

A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space.

On a single line print the answer to the problem. If such number does not exist, then you should print -1.

NoteIn the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number.

let gao a =
  let s = ref 0 in
  for i = 0 to Array.length a - 1 do
    s := !s + i * a.(i)
  done;
  if a.(0) > 0 && !s mod 3 = 0 then begin
    if !s = 0 then a.(0) <- 1;
    for i = Array.length a - 1 downto 0 do
      for j = 0 to a.(i) - 1 do
        print_int i
      done
    done;
    exit 0
  end
;;

let _ =
  let n = Scanf.scanf " %d" (fun x -> x) in
  let a = Array.create 10 0 in
  for i = 1 to n do
    let d = Scanf.scanf " %d" (fun x -> x) in
    a.(d) <- a.(d) + 1
  done;

  gao a;
  for i = 1 to 9 do
    if a.(i) > 0 then begin
      a.(i) <- a.(i) - 1;
      gao a;
      a.(i) <- a.(i) + 1
    end
  done;
  for i = 1 to 9 do
    if a.(i) > 0 then begin
      a.(i) <- a.(i) - 1;
      for j = 1 to i do
        if a.(j) > 0 then begin
          a.(j) <- a.(j) - 1;
          gao a;
          a.(j) <- a.(j) + 1
        end
      done;
      a.(i) <- a.(i) + 1
    end
  done;

  print_int (-1)
;;


Little Petya likes arrays of integers a lot. Recently his mother has presented him one such array consisting of n elements. Petya is now wondering whether he can swap any two distinct integers in the array so that the array got unsorted. Please note that Petya can not swap equal integers even if they are in distinct positions in the array. Also note that Petya must swap some two integers even if the original array meets all requirements.Array a (the array elements are indexed from 1) consisting of n elements is called sorted if it meets at least one of the following two conditions:  a1 ≤ a2 ≤ ... ≤ an;  a1 ≥ a2 ≥ ... ≥ an. Help Petya find the two required positions to swap or else say that they do not exist.

The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n non-negative space-separated integers a1, a2, ..., an — the elements of the array that Petya's mother presented him. All integers in the input do not exceed 109.

If there is a pair of positions that make the array unsorted if swapped, then print the numbers of these positions separated by a space. If there are several pairs of positions, print any of them. If such pair does not exist, print -1. The positions in the array are numbered with integers from 1 to n.

NoteIn the first two samples the required pairs obviously don't exist.In the third sample you can swap the first two elements. After that the array will look like this: 2 1 3 4. This array is unsorted.

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

let () =
  let n = read_int() in
  let a = Array.init n (fun i -> read_int()) in

  let rec findud i ac = if i=n-1 then List.rev ac else (
    if a.(i) < a.(i+1) then findud (i+1) ((1,i)::ac)
    else if a.(i) > a.(i+1) then findud (i+1) ((-1,i)::ac)
    else findud (i+1) ac
  )
  in
  let li = findud 0 [] in
  let m = List.length li in
  let (a,b) =
    if m=0 || n <= 2 then (-1,-1)
    else if m=1 then (
      let (_,i1) = List.nth li 0 in
	(i1, i1+1)
    ) else if m=2 then (
      let (d1,i1) = List.nth li 0 in
      let (d2,i2) = List.nth li 1 in
	if n=3 then (
	  if d1=d2 then (i1, i1+1)
	  else if a.(0) <> a.(n-1) then (0,n-1)
	  else (-1,-1)
	) else (
	  if d1=d2 then (i1, i1+1)
	  else if i1=0 then (i2, i2+1)
	  else (i1, i1+1)
	)
    ) else (
      (*  uuu -> duu   swap 1
          uud -> dud   swap 1
          udu -> d?u   swap 1 (or 3)
	  udd -> udu   swap 3
          duu -> dud   swap 3
          dud -> u?d   swap 1 (or 3)
	  ddu -> udu   swap 1
          ddd -> udd   swap 1
      *)
      let (d1,i1) = List.nth li 0 in
      let (d2,i2) = List.nth li 1 in
      let (d3,i3) = List.nth li 2 in
	if d1=d2 then (i1, i1+1)
	else (i3, i3+1)
    )
  in
    if (a,b) = (-1,-1) then Printf.printf "-1\n" else Printf.printf "%d %d\n" (a+1) (b+1)

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

let () =
  let n = read_int() in
  let a = Array.init n (fun i -> read_int()) in

  let rec findud i ac = if i=n-1 then List.rev ac else (
    if a.(i) < a.(i+1) then findud (i+1) ((1,i)::ac)
    else if a.(i) > a.(i+1) then findud (i+1) ((-1,i)::ac)
    else findud (i+1) ac
  )
  in
  let li = findud 0 [] in
  let m = List.length li in
    if m<=1 then Printf.printf "-1\n"
    else if m=2 then
      if a.(0) = a.(n-1) then Printf.printf "-1\n" else
	let (d1,i1) = List.nth li 0 in
	let (d2,i2) = List.nth li 1 in
	  if d1=d2 then Printf.printf "%d %d\n" (i1+1) (i1+2) else Printf.printf "%d %d\n" 1 n
    else (
      (*  uuu -> duu   swap 1
	  duu -> dud   swap 3
	  udu -> d?u   swap 1
	  ddu -> udu   swap 1
      *)
      let (d1,i1) = List.nth li 0 in
      let (d2,i2) = List.nth li 1 in
      let (d3,i3) = List.nth li 2 in
	if d1=d2 then Printf.printf "%d %d\n" (i1+1) (i1+2)
	else Printf.printf "%d %d\n" (i3+1) (i3+2)
    )

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

let () =
  let n = read_int() in
  let a = Array.init n (fun i -> read_int()) in

    if a.(0) = a.(n-1) || n=2 then Printf.printf "-1\n" else (
      if n>3 then Printf.printf "1 %d\n" n else (
	if a.(0) <> a.(1) then Printf.printf "1 2\n" else Printf.printf "2 3\n"
      )
    )

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

let () =
  let n = read_int() in
  let a = Array.init n (fun i -> read_int()) in

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

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

let () =
  let n = read_int() in
  let a = Array.init n (fun i -> read_int()) in

  let rec findud i ac = if i=n-1 then List.rev ac else (
    if a.(i) < a.(i+1) then findud (i+1) ((1,i)::ac)
    else if a.(i) > a.(i+1) then findud (i+1) ((-1,i)::ac)
    else findud (i+1) ac
  )
  in
  let li = findud 0 [] in
  let m = List.length li in
    if m<=1 then Printf.printf "-1\n"
    else if m=2 then
      if a.(0) = a.(n-1) then Printf.printf "-1\n" else Printf.printf "%d %d\n" 1 n
    else (
      (*  uuu -> duu   swap 1
	  duu -> dud   swap 3
	  udu -> d?u   swap 1
	  ddu -> udu   swap 1
      *)
      let (d1,i1) = List.nth li 0 in
      let (d2,i2) = List.nth li 1 in
      let (d3,i3) = List.nth li 2 in
	if d1=d2 then Printf.printf "%d %d\n" (i1+1) (i1+2)
	else Printf.printf "%d %d\n" (i3+1) (i3+2)
    )


Chubby Yang is studying linear equations right now. He came up with a nice problem. In the problem you are given an n × n matrix W, consisting of integers, and you should find two n × n matrices A and B, all the following conditions must hold:   Aij = Aji, for all i, j (1 ≤ i, j ≤ n);  Bij =  - Bji, for all i, j (1 ≤ i, j ≤ n);  Wij = Aij + Bij, for all i, j (1 ≤ i, j ≤ n). Can you solve the problem?

The first line contains an integer n (1 ≤ n ≤ 170). Each of the following n lines contains n integers. The j-th integer in the i-th line is Wij (0 ≤ |Wij| < 1717).

The first n lines must contain matrix A. The next n lines must contain matrix B. Print the matrices in the format equal to format of matrix W in input. It is guaranteed that the answer exists. If there are multiple answers, you are allowed to print any of them. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 4.

let _ =
  let n = Scanf.scanf "%d " (fun x -> x) in
  let w = Array.make_matrix n n 0. in
  for i = 0 to n - 1 do
    for j = 0 to n - 1 do
      w.(i).(j) <- Scanf.scanf "%f " (fun x -> x);
    done;
  done;
  for i = 0 to n - 1 do
    for j = 0 to n - 1 do
      Printf.printf "%.1f " ((w.(i).(j) +. w.(j).(i)) /. 2.)
    done;
    print_newline ();
  done;
  for i = 0 to n - 1 do
    for j = 0 to n - 1 do
      Printf.printf "%.1f " ((w.(i).(j) -. w.(j).(i)) /. 2.)
    done;
    print_newline ();
  done;


'Jeopardy!' is an intellectual game where players answer questions and earn points. Company Q conducts a simplified 'Jeopardy!' tournament among the best IT companies. By a lucky coincidence, the old rivals made it to the finals: company R1 and company R2. The finals will have n questions, m of them are auction questions and n - m of them are regular questions. Each question has a price. The price of the i-th question is ai points. During the game the players chose the questions. At that, if the question is an auction, then the player who chose it can change the price if the number of his current points is strictly larger than the price of the question. The new price of the question cannot be less than the original price and cannot be greater than the current number of points of the player who chose the question. The correct answer brings the player the points equal to the price of the question. The wrong answer to the question reduces the number of the player's points by the value of the question price.The game will go as follows. First, the R2 company selects a question, then the questions are chosen by the one who answered the previous question correctly. If no one answered the question, then the person who chose last chooses again.All R2 employees support their team. They want to calculate what maximum possible number of points the R2 team can get if luck is on their side during the whole game (they will always be the first to correctly answer questions). Perhaps you are not going to be surprised, but this problem was again entrusted for you to solve.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 100; m ≤ min(n, 30)) — the total number of questions and the number of auction questions, correspondingly. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 107) — the prices of the questions. The third line contains m distinct integers bi (1 ≤ bi ≤ n) — the numbers of auction questions. Assume that the questions are numbered from 1 to n.

In the single line, print the answer to the problem — the maximum points the R2 company can get if it plays optimally well. It is guaranteed that the answer fits into the integer 64-bit signed type.

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int() and m=read_int();;
let tab=Array.make (n+1) 0;;
for i=1 to n do
   tab.(i)<-read_int()
done;;
let boo=Array.make (n+1) 0;;
for i=1 to m do
   boo.(read_int())<-1
done;;
let auction=Array.make m 0;;
let non_auction=Array.make (n-m) 0;;
let j=ref 0;;
let k=ref 0;;
for i=1 to n do
   if boo.(i)=1 then (auction.(!j)<-tab.(i);incr j)
   else (non_auction.(!k)<-tab.(i);incr k)
done;;
Array.fast_sort (fun x y -> if x=y then 0 else if x>y then -1 else 1) auction;;
let sum=ref Int64.zero;;
for i=0 to n-m-1 do
   sum:=Int64.add (!sum) (Int64.of_int(non_auction.(i)))
done;;
let j=ref 0;;
for i=0 to m-1 do
   let x=Int64.of_int(auction.(i)) in
   begin
   if x> !sum then sum:=Int64.add (!sum) x
   else sum:=Int64.add (!sum) (!sum)
   end
done;;
print_string (Int64.to_string(!sum));;


The black king is standing on a chess field consisting of 109 rows and 109 columns. We will consider the rows of the field numbered with integers from 1 to 109 from top to bottom. The columns are similarly numbered with integers from 1 to 109 from left to right. We will denote a cell of the field that is located in the i-th row and j-th column as (i, j).You know that some squares of the given chess field are allowed. All allowed cells of the chess field are given as n segments. Each segment is described by three integers ri, ai, bi (ai ≤ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed.Your task is to find the minimum number of moves the king needs to get from square (x0, y0) to square (x1, y1), provided that he only moves along the allowed cells. In other words, the king can be located only on allowed cells on his way.Let us remind you that a chess king can move to any of the neighboring cells in one move. Two cells of a chess field are considered neighboring if they share at least one point.

The first line contains four space-separated integers x0, y0, x1, y1 (1 ≤ x0, y0, x1, y1 ≤ 109), denoting the initial and the final positions of the king. The second line contains a single integer n (1 ≤ n ≤ 105), denoting the number of segments of allowed cells. Next n lines contain the descriptions of these segments. The i-th line contains three space-separated integers ri, ai, bi (1 ≤ ri, ai, bi ≤ 109, ai ≤ bi), denoting that cells in columns from number ai to number bi inclusive in the ri-th row are allowed. Note that the segments of the allowed cells can intersect and embed arbitrarily. It is guaranteed that the king's initial and final position are allowed cells. It is guaranteed that the king's initial and the final positions do not coincide. It is guaranteed that the total length of all given segments doesn't exceed 105.

If there is no path between the initial and final position along allowed cells, print -1. Otherwise print a single integer — the minimum number of moves the king needs to get from the initial position to the final one.

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

module Pset = Set.Make (struct type t = int*int let compare = compare end)

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)
let minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)

let bound = 1_000_000_000

let () =
  let x0 = read_int() in
  let y0 = read_int() in
  let x1 = read_int() in
  let y1 = read_int() in
  let n = read_int() in
  let strip = Array.init n (
    fun _ ->
      let r = read_int() in
      let a = read_int() in
      let b = read_int() in
	(r,a,b)
  ) in

  let h = Hashtbl.create 1000 in
    for i=0 to n-1 do
      let (r,a,b) = strip.(i) in
	for c=a to b do
	  Hashtbl.add h (r,c) true
	done
    done;

    let neighbors (r,c) =
      let dl = List.map (fun (dr,dc) -> (r+dr, c+dc))
	[(1,1);(1,0);(1,-1);(0,1);(0,-1);(-1,1);(-1,0);(-1,-1)] in
	List.filter (
	  fun (r,c) ->
	    r >= 1 && c >= 1 && r <= bound && c<=bound &
	      Hashtbl.mem h (r,c)
	) dl
    in

    let rec pass prev current =
      Pset.fold (
	fun p s ->
	  let xnew = List.filter (
	    fun ne -> (not (Pset.mem ne current)) && (not (Pset.mem ne prev))
	  ) (neighbors p)
	  in
	    List.fold_left (fun s ne -> Pset.add ne s) s xnew
      ) current Pset.empty
    in

    let rec loop prev current d =
      if Pset.is_empty current then None
      else if Pset.mem (x1,y1) current then Some d
      else loop current (pass prev current) (d+1)
    in

    let ans =
      match loop Pset.empty (Pset.singleton (x0,y0)) 0 with
	| None -> -1
	| Some d -> d
    in

      Printf.printf "%d\n" ans


Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array $$$a$$$ with elements $$$a_1, a_2, \ldots, a_{2k-1}$$$, is the array $$$b$$$ with elements $$$b_1, b_2, \ldots, b_{k}$$$ such that $$$b_i$$$ is equal to the median of $$$a_1, a_2, \ldots, a_{2i-1}$$$ for all $$$i$$$. Omkar has found an array $$$b$$$ of size $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$, $$$-10^9 \leq b_i \leq 10^9$$$). Given this array $$$b$$$, Ray wants to test Omkar's claim and see if $$$b$$$ actually is an OmkArray of some array $$$a$$$. Can you help Ray?The median of a set of numbers $$$a_1, a_2, \ldots, a_{2i-1}$$$ is the number $$$c_{i}$$$ where $$$c_{1}, c_{2}, \ldots, c_{2i-1}$$$ represents $$$a_1, a_2, \ldots, a_{2i-1}$$$ sorted in nondecreasing order.

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. Description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 2 \cdot 10^5$$$) — the length of the array $$$b$$$. The second line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$-10^9 \leq b_i \leq 10^9$$$) — the elements of $$$b$$$. It is guaranteed the sum of $$$n$$$ across all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output one line containing YES if there exists an array $$$a$$$ such that $$$b_i$$$ is the median of $$$a_1, a_2, \dots, a_{2i-1}$$$ for all $$$i$$$, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted).

NoteIn the second case of the first sample, the array $$$[4]$$$ will generate an OmkArray of $$$[4]$$$, as the median of the first element is $$$4$$$.In the fourth case of the first sample, the array $$$[3, 2, 5]$$$ will generate an OmkArray of $$$[3, 3]$$$, as the median of $$$3$$$ is $$$3$$$ and the median of $$$2, 3, 5$$$ is $$$3$$$.In the fifth case of the first sample, the array $$$[2, 1, 0, 3, 4, 4, 3]$$$ will generate an OmkArray of $$$[2, 1, 2, 3]$$$ as   the median of $$$2$$$ is $$$2$$$  the median of $$$0, 1, 2$$$ is $$$1$$$  the median of $$$0, 1, 2, 3, 4$$$ is $$$2$$$  and the median of $$$0, 1, 2, 3, 3, 4, 4$$$ is $$$3$$$. In the second case of the second sample, the array $$$[1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5]$$$ will generate an OmkArray of $$$[1, 1, 3, 1, 0, -2, -1]$$$, as   the median of $$$1$$$ is $$$1$$$  the median of $$$0, 1, 4$$$ is $$$1$$$  the median of $$$0, 1, 3, 4, 5$$$ is $$$3$$$  the median of $$$-2, -2, 0, 1, 3, 4, 5$$$ is $$$1$$$  the median of $$$-4, -2, -2, -2, 0, 1, 3, 4, 5$$$ is $$$0$$$  the median of $$$-4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5$$$ is $$$-2$$$  and the median of $$$-4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5$$$ is $$$-1$$$ For all cases where the answer is NO, it can be proven that it is impossible to find an array $$$a$$$ such that $$$b$$$ is the OmkArray of $$$a$$$.

open Printf
open Scanf

(* set code from ~/Sync/contest-work/codeforces-709/d.ml *)

module Iset = Set.Make (struct type t = int let compare = compare end)
open Iset

let pred x s =
  let (l,_,_) = split x s in
  max_elt (if is_empty l then s else l)

let succ x s =
  let (_,_,r) = split x s in
  min_elt (if is_empty r then s else r)

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let () =
  let cases = read_int () in
  for case = 1 to cases do
    let n = read_int () in
    let b = Array.init n read_int in

    let rec loop s i = if i=n then true
    (* b.(i-1) is the last median before the current one *)
      else if b.(i) > b.(i-1) then (
	let z = succ b.(i-1) s in
	if z > b.(i-1) && b.(i) > z then false
	else loop (add b.(i) s) (i+1)
      ) else if b.(i) < b.(i-1) then (
	let z = pred b.(i-1) s in
	if z < b.(i-1) && b.(i) < z then false
	else loop (add b.(i) s) (i+1)
      ) else loop s (i+1)
    in
    if loop (singleton b.(0)) 1 then printf "YES\n" else printf "NO\n"
  done


Ayrat has number n, represented as it's prime factorization pi of size m, i.e. n = p1·p2·...·pm. Ayrat got secret information that that the product of all divisors of n taken modulo 109 + 7 is the password to the secret data base. Now he wants to calculate this value.

The first line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of primes in factorization of n.  The second line contains m primes numbers pi (2 ≤ pi ≤ 200 000).

Print one integer — the product of all divisors of n modulo 109 + 7.

NoteIn the first sample n = 2·3 = 6. The divisors of 6 are 1, 2, 3 and 6, their product is equal to 1·2·3·6 = 36.In the second sample 2·3·2 = 12. The divisors of 12 are 1, 2, 3, 4, 6 and 12. 1·2·3·4·6·12 = 1728.

open Printf
open Scanf

let p = 1_000_000_007L

let long x = Int64.of_int x
let short x = Int64.to_int x

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

let ( *** ) a b = (a**b) %% p
let ( +++ ) a b = let x = a++b in if x>=p then x--p else x
let ( --- ) a b = let x = a--b in if x<0L then x++p else x

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)

let rec ( ^ ) b e =
  if e=0L then 1L else
  let a = b ^ (e//2L) in
  if (Int64.logand e 1L)=0L then a***a else b***a***a

let long x = Int64.of_int x
let short x = Int64.to_int x

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

let () =
  let m = read_int () in

  let h = Hashtbl.create 10 in
  let increment t =
    let c = try Hashtbl.find h t with Not_found -> 0L in
    Hashtbl.replace h t (c++1L)
  in

  for i=0 to m-1 do
    increment (read_long ())
  done;

  let primefact = Array.of_list (
    Hashtbl.fold (fun pr pow ac -> (pr,pow)::ac) h []) in
  let np = Array.length primefact in

  let alphaprefix = Array.make (np+1) 1L in
  let alphasuffix = Array.make (np+1) 1L in

  for i=1 to np do
    let (_,pow) = primefact.(i-1) in
    alphaprefix.(i) <- (alphaprefix.(i-1) ** (pow++1L)) %% (p--1L)
  done;

  for i=np-1 downto 0 do
    let (_,pow) = primefact.(i) in
    alphasuffix.(i) <- (alphasuffix.(i+1) ** (pow++1L)) %% (p--1L)
  done;

  (* alphaprefix.(i) = pow0 * pow1 * ... * pow(i-1) *)
  (* alphasuffix.(i) = pow(np-1) * pow(np-2) * ... * pow(i) *)

  (* the product of the powers (mod p-1) without pow(i) is
     alphaprefix.(i) * alphasuffix.(i+1)
  *)

  let answer = fold 0 (np-1) (fun i ac ->
    let (pr,pow) = primefact.(i) in
    let alphaprod =  (alphaprefix.(i) ** alphasuffix.(i+1)) %% (p--1L) in
    let x = ((pow ** (pow ++ 1L)) // 2L) %% (p--1L) in
    let y = (x ** alphaprod) %% (p--1L) in
    let z = pr ^ y in
    ac *** z
  ) 1L in

  printf "%Ld\n" answer


President of Berland has a very vast office-room, where, apart from him, work his subordinates. Each subordinate, as well as President himself, has his own desk of a unique colour. Each desk is rectangular, and its sides are parallel to the office walls. One day President decided to establish an assembly, of which all his deputies will be members. Unfortunately, he does not remember the exact amount of his deputies, but he remembers that the desk of each his deputy is adjacent to his own desk, that is to say, the two desks (President's and each deputy's) have a common side of a positive length.The office-room plan can be viewed as a matrix with n rows and m columns. Each cell of this matrix is either empty, or contains a part of a desk. An uppercase Latin letter stands for each desk colour. The «period» character («.») stands for an empty cell.

The first line contains two separated by a space integer numbers n, m (1 ≤ n, m ≤ 100) — the length and the width of the office-room, and c character — the President's desk colour. The following n lines contain m characters each — the office-room description. It is guaranteed that the colour of each desk is unique, and each desk represents a continuous subrectangle of the given matrix. All colours are marked by uppercase Latin letters.

Print the only number — the amount of President's deputies.

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 () =
  let n = read_int 0 in
  let m = read_int 0 in
  let r = (read_str 0).[0] in
  let a = Array.init n read_str in
  let h = Hashtbl.create n in
  for i = 0 to n-1 do
    for j = 0 to m-1 do
      if a.(i).[j] = r then
        List.iter2 (fun di dj ->
          let ii = i+di in
          let jj = j+dj in
          if 0 <= ii && ii < n && 0 <= jj && jj < m && a.(ii).[jj] <> '.' &&
          a.(ii).[jj] <> r then
            Hashtbl.replace h a.(ii).[jj] ()
        ) [-1;0;1;0] [0;1;0;-1]
    done
  done;
  Printf.printf "%d\n" (Hashtbl.length h)


One of the most important products of the R1 company is a popular @r1.com mail service. The R1 mailboxes receive and send millions of emails every day.Today, the online news thundered with terrible information. The R1 database crashed and almost no data could be saved except for one big string. The developers assume that the string contains the letters of some users of the R1 mail. Recovering letters is a tedious mostly manual work. So before you start this process, it was decided to estimate the difficulty of recovering. Namely, we need to calculate the number of different substrings of the saved string that form correct e-mail addresses.We assume that valid addresses are only the e-mail addresses which meet the following criteria:  the address should begin with a non-empty sequence of letters, numbers, characters '_', starting with a letter;  then must go character '@';  then must go a non-empty sequence of letters or numbers;  then must go character '.';  the address must end with a non-empty sequence of letters. You got lucky again and the job was entrusted to you! Please note that the substring is several consecutive characters in a string. Two substrings, one consisting of the characters of the string with numbers l1, l1 + 1, l1 + 2, ..., r1 and the other one consisting of the characters of the string with numbers l2, l2 + 1, l2 + 2, ..., r2, are considered distinct if l1 ≠ l2 or r1 ≠ r2.

The first and the only line contains the sequence of characters s1s2... sn (1 ≤ n ≤ 106) — the saved string. It is guaranteed that the given string contains only small English letters, digits and characters '.', '_', '@'.

Print in a single line the number of substrings that are valid e-mail addresses.

NoteIn the first test case all the substrings that are correct e-mail addresses begin from one of the letters of the word agapov and end in one of the letters of the word com.In the second test case note that the e-mail x@x.x is considered twice in the answer. Note that in this example the e-mail entries overlap inside the string.

let s=read_line();;
let n=String.length(s)-1;;

let isvalid c=
if (c<>'.')&&(c<>'@')&&(c<>'_') then true else false;;

let isletter c=
if (c>='a')&&(c<='z') then true else false;;

let sol=ref Int64.zero;;

let rec faire i deb etape=
if i>n then ()
else if etape="debut" then
   begin
   if s.[i]='@' then
      begin
      if deb<>0 then faire (i+1) deb "arobase1"
      else faire (i+1) 0 "debut"
      end
   else if s.[i]='.' then faire (i+1) 0 "debut"
   else if (isletter s.[i]) then faire (i+1) (deb+1) "debut"
   else faire (i+1) deb "debut"
   end
else if etape="arobase1" then
   begin
   if (isvalid s.[i]) then faire (i+1) deb "arobase2" else faire (i+1) 0 "debut"
   end
else if etape="arobase2" then
   begin
   if (isvalid s.[i]) then faire (i+1) deb "arobase2"
   else if s.[i]='.' then faire (i+1) deb "point"
   else faire (i-1) 0 "retour_arobase"
   end
else if etape="point" then
   begin
   if (isletter s.[i]) then (sol:= Int64.add (!sol) (Int64.of_int deb);faire (i+1) deb "point")
   else faire (i-1) 0 "retour_point"
   end
else if etape="retour_point" then
   begin
   if s.[i]='.' then faire (i+1) 0 "debut"
   else faire (i-1) 0 "retour_point"
   end
else if s.[i]='@' then faire (i+1) 0 "debut"
else faire (i-1) 0 "retour_arobase";;

faire 0 0 "debut";;

print_string( Int64.to_string(!sol));;

let _ =
  let sb = Scanf.Scanning.stdib in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  (*let s = "gerald.agapov1991@gmail.com" in
  let s = "x@x.x@x.x_e_@r1.com" in*)
  let n = String.length s in
  let c = ref 0 in
  let c2 = ref 0 in
  let a = Array.make n 0 in
  let b = Array.make n 0 in
  let res = ref 0L in
    for i = 0 to n - 1 do
      match s.[i] with
	| '@' ->
	    a.(i) <- !c;
	    c := 0;
	| '.' -> c := 0;
	| 'a'..'z' -> incr c;
	| '0'..'9' -> ()
	| '_' -> ()
	| _ -> assert false
    done;
    c := 0;
    for i = n - 1 downto 0 do
      match s.[i] with
	| '@' ->
	    if !c2 <> 0 && s.[i + 1] <> '.'
	    then b.(i) <- !c2;
	    c2 := 0;
	    c := 0;
	| '.' ->
	    c2 := !c;
	    c := 0;
	| 'a'..'z' ->
	    incr c;
	| '0'..'9' ->
	    c := 0;
	| '_' ->
	    c := 0;
	    c2 := 0;
	| _ -> assert false
    done;
    for i = 0 to n - 1 do
      if s.[i] = '@'
      then res := Int64.add !res (Int64.mul (Int64.of_int a.(i))
				    (Int64.of_int b.(i)))
    done;
    Printf.printf "%Ld\n" !res;
    a, b

let s=read_line();;
let n=String.length(s)-1;;

let isvalid c=
if (c<>'.')&&(c<>'@')&&(c<>'_') then true else false;;

let isletter c=
if (c>='a')&&(c<='z') then true else false;;

let sol=ref 0;;

let rec faire i deb etape=
if i>n then ()
else if etape="debut" then
   begin
   if s.[i]='@' then
      begin
      if deb<>0 then faire (i+1) deb "arobase1"
      else faire (i+1) 0 "debut"
      end
   else if s.[i]='.' then faire (i+1) 0 "debut"
   else if (isletter s.[i]) then faire (i+1) (deb+1) "debut"
   else faire (i+1) deb "debut"
   end
else if etape="arobase1" then
   begin
   if (isvalid s.[i]) then faire (i+1) deb "arobase2" else faire (i+1) 0 "debut"
   end
else if etape="arobase2" then
   begin
   if (isvalid s.[i]) then faire (i+1) deb "arobase2"
   else if s.[i]='.' then faire (i+1) deb "point"
   else faire (i-1) 0 "retour_arobase"
   end
else if etape="point" then
   begin
   if (isletter s.[i]) then (sol:= !sol+deb;faire (i+1) deb "point")
   else faire (i-1) 0 "retour_point"
   end
else if etape="retour_point" then
   begin
   if s.[i]='.' then faire (i+1) 0 "debut"
   else faire (i-1) 0 "retour_point"
   end
else if s.[i]='@' then faire (i+1) 0 "debut"
else faire (i-1) 0 "retour_arobase";;

faire 0 0 "debut";;

print_int( !sol);;

let s=read_line();;
let n=String.length(s)-1;;

let isvalid c=
if (c<>'.')&&(c<>'@')&&(c<>'_') then true else false;;

let isletter c=
if (c>='a')&&(c<='z') then true else false;;

let sol=ref 0;;

let rec faire i deb etape=
if i>n then ()
else if etape="debut" then
   begin
   if s.[i]='@' then
      begin
      if deb<>0 then faire (i+2) deb "arobase1"
      else faire (i+1) 0 "debut"
      end
   else if s.[i]='.' then faire (i+1) 0 "debut"
   else if (isletter s.[i]) then faire (i+1) (deb+1) "debut"
   else faire (i+1) deb "debut"
   end
else if etape="arobase1" then
   begin
   if (isvalid s.[i]) then faire (i+1) deb "arobase2" else faire (i+1) 0 "debut"
   end
else if etape="arobase2" then
   begin
   if (isvalid s.[i]) then faire (i+1) deb "arobase2"
   else if s.[i]='.' then faire (i+2) deb "point"
   else faire (i-1) 0 "retour_arobase"
   end
else if etape="point" then
   begin
   if (isletter s.[i]) then (sol:= !sol+deb;faire (i+1) deb "point")
   else faire (i-1) 0 "retour_point"
   end
else if etape="retour_point" then
   begin
   if s.[i]='.' then faire (i+1) 0 "debut"
   else faire (i-1) 0 "retour_point"
   end
else if s.[i]='@' then faire (i+1) 0 "debut"
else faire (i-1) 0 "retour_arobase";;

faire 0 0 "debut";;

print_int( !sol);;

let _ =
  let sb = Scanf.Scanning.stdib in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  (*let s = "gerald.agapov1991@gmail.com" in
  let s = "x@x.x@x.x_e_@r1.com" in*)
  let n = String.length s in
  let c = ref 0 in
  let c2 = ref 0 in
  let st = ref 0 in
  let a = Array.make n 0 in
  let b = Array.make n 0 in
  let res = ref 0L in
    for i = 0 to n - 1 do
      match s.[i] with
	| '@' ->
	    a.(i) <- !c;
	    c := 0;
	| '.' -> c := 0;
	| 'a'..'z' -> incr c;
	| '0'..'9' -> ()
	| '_' -> ()
	| _ -> assert false
    done;
    c := 0;
    for i = n - 1 downto 0 do
      match s.[i] with
	| '@' ->
	    b.(i) <- !c2;
	    c2 := 0;
	    c := 0;
	| '.' ->
	    c2 := !c;
	    c := 0;
	| 'a'..'z' ->
	    incr c;
	| '0'..'9' ->
	    c := 0;
	| '_' ->
	    c := 0;
	    c2 := 0;
	| _ -> assert false
    done;
    for i = 0 to n - 1 do
      if s.[i] = '@'
      then res := Int64.add !res (Int64.mul (Int64.of_int a.(i))
				    (Int64.of_int b.(i)))
    done;
    Printf.printf "%Ld\n" !res;
    a, b


You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.

The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly. The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space. The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A. The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.

Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).

NoteIn the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3).In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .

let () = Scanf.scanf "%d %d\n%d %d\n" (fun na nb k m ->
    let a = Array.init na (fun _ -> Scanf.scanf "%d%_c" (fun x -> x))
    and b = Array.init nb (fun _ -> Scanf.scanf "%d%_c" (fun x -> x))
    in

    print_endline (if a.(k - 1) < b.(nb - m) then "YES" else "NO"))


Michael is accused of violating the social distancing rules and creating a risk of spreading coronavirus. He is now sent to prison. Luckily, Michael knows exactly what the prison looks like from the inside, especially since it's very simple.The prison can be represented as a rectangle $$$a\times b$$$ which is divided into $$$ab$$$ cells, each representing a prison cell, common sides being the walls between cells, and sides on the perimeter being the walls leading to freedom. Before sentencing, Michael can ask his friends among the prison employees to make (very well hidden) holes in some of the walls (including walls between cells and the outermost walls). Michael wants to be able to get out of the prison after this, no matter which cell he is placed in. However, he also wants to break as few walls as possible.Your task is to find out the smallest number of walls to be broken so that there is a path to the outside from every cell after this.

The first line contains a single integer $$$t$$$ ($$$1\leq t\leq 100$$$) — the number of test cases. Each of the following $$$t$$$ lines contains two integers $$$a$$$ and $$$b$$$ ($$$1\leq a, b\leq 100$$$), representing a corresponding test case.

For each test case print the single integer on a separate line — the answer to the problem.

NoteSome possible escape plans for the example test cases are shown below. Broken walls are shown in gray, not broken walls are shown in black.

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

for i = 1 to n do
  let (a,b) = read_pair () in
  Printf.printf "%d\n" (a*b)
done

open Printf
open Scanf

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 cases = read_int () in
  for case = 1 to cases do
    let (a,b) = read_pair () in
    printf "%d\n" (a*b)
  done


You have an array $$$a$$$ of length $$$n$$$. For every positive integer $$$x$$$ you are going to perform the following operation during the $$$x$$$-th second:  Select some distinct indices $$$i_{1}, i_{2}, \ldots, i_{k}$$$ which are between $$$1$$$ and $$$n$$$ inclusive, and add $$$2^{x-1}$$$ to each corresponding position of $$$a$$$. Formally, $$$a_{i_{j}} := a_{i_{j}} + 2^{x-1}$$$ for $$$j = 1, 2, \ldots, k$$$. Note that you are allowed to not select any indices at all. You have to make $$$a$$$ nondecreasing as fast as possible. Find the smallest number $$$T$$$ such that you can make the array nondecreasing after at most $$$T$$$ seconds.Array $$$a$$$ is nondecreasing if and only if $$$a_{1} \le a_{2} \le \ldots \le a_{n}$$$.You have to answer $$$t$$$ independent test cases.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^{4}$$$) — the number of test cases. The first line of each test case contains single integer $$$n$$$ ($$$1 \le n \le 10^{5}$$$) — the length of array $$$a$$$. It is guaranteed that the sum of values of $$$n$$$ over all test cases in the input does not exceed $$$10^{5}$$$. The second line of each test case contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$-10^{9} \le a_{i} \le 10^{9}$$$).

For each test case, print the minimum number of seconds in which you can make $$$a$$$ nondecreasing.

NoteIn the first test case, if you select indices $$$3, 4$$$ at the $$$1$$$-st second and $$$4$$$ at the $$$2$$$-nd second, then $$$a$$$ will become $$$[1, 7, 7, 8]$$$. There are some other possible ways to make $$$a$$$ nondecreasing in $$$2$$$ seconds, but you can't do it faster.In the second test case, $$$a$$$ is already nondecreasing, so answer is $$$0$$$.In the third test case, if you do nothing at first $$$2$$$ seconds and select index $$$2$$$ at the $$$3$$$-rd second, $$$a$$$ will become $$$[0, 0]$$$.

let r_long () = Int64.of_int (Scanf.scanf " %d" (fun x -> x)) in
let r_int () = Scanf.scanf " %d" (fun x -> x) in

let rec max_diff maxi = function
| 0 -> 0L
| nbNombres ->
   let nombre = r_long () in
   let nouvMax = max nombre maxi in
   max (Int64.sub maxi nombre) (max_diff nouvMax (nbNombres - 1))
in

let rec log = function
| 0L -> 0
| n -> 1 + log (Int64.div n 2L)
in

let nbTests = r_int () in
for iTest = 1 to nbTests do
   let nbNombres = r_int () in
   let diff = max_diff (r_long ()) (nbNombres - 1) in
   print_int (log diff);
   print_newline ()
done;

open Printf
open Scanf

let rec topbit d = if d lsr 1 = 0 then 0 else 1 + topbit (d lsr 1)

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

let () =
  let cases = read_int() in
  for case = 1 to cases do
    let n = read_int() in
    let a = Array.init n read_int in
    let rec loop i mb = if i=n-1 then mb else (
      if a.(i) <= a.(i+1) then loop (i+1) mb
      else (
	let d = a.(i) - a.(i+1) in
	a.(i+1) <- a.(i);
	let mb = max mb (1 + topbit d) in
	loop (i+1) mb
      )
    )
    in
    printf "%d\n" (if n = 1 then 0 else loop 0 0)
  done

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

let rec max_diff maxi = function
| 0 -> 0
| nbNombres ->
   let nombre = r_int () in
   let nouvMax = max nombre maxi in
   max (maxi - nombre) (max_diff nouvMax (nbNombres - 1))
in

let rec log = function
| 0 -> 0
| n -> 1 + log (n / 2)
in

let nbTests = r_int () in
for iTest = 1 to nbTests do
   let nbNombres = r_int () in
   let diff = max_diff (r_int ()) (nbNombres - 1) in
   print_int (log diff);
   print_newline ()
done;


Consider a tunnel on a one-way road. During a particular day, $$$n$$$ cars numbered from $$$1$$$ to $$$n$$$ entered and exited the tunnel exactly once. All the cars passed through the tunnel at constant speeds.A traffic enforcement camera is mounted at the tunnel entrance. Another traffic enforcement camera is mounted at the tunnel exit. Perfectly balanced.Thanks to the cameras, the order in which the cars entered and exited the tunnel is known. No two cars entered or exited at the same time.Traffic regulations prohibit overtaking inside the tunnel. If car $$$i$$$ overtakes any other car $$$j$$$ inside the tunnel, car $$$i$$$ must be fined. However, each car can be fined at most once.Formally, let's say that car $$$i$$$ definitely overtook car $$$j$$$ if car $$$i$$$ entered the tunnel later than car $$$j$$$ and exited the tunnel earlier than car $$$j$$$. Then, car $$$i$$$ must be fined if and only if it definitely overtook at least one other car.Find the number of cars that must be fined.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 10^5$$$), denoting the number of cars. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le n$$$), denoting the ids of cars in order of entering the tunnel. All $$$a_i$$$ are pairwise distinct. The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le n$$$), denoting the ids of cars in order of exiting the tunnel. All $$$b_i$$$ are pairwise distinct.

NoteThe first example is depicted below:Car $$$2$$$ definitely overtook car $$$5$$$, while car $$$4$$$ definitely overtook cars $$$1$$$, $$$2$$$, $$$3$$$ and $$$5$$$. Cars $$$2$$$ and $$$4$$$ must be fined.In the second example car $$$5$$$ was definitely overtaken by all other cars.In the third example no car must be fined.

let n = read_int() in
let mp = Array.make (n+1) 0 in
let scan_int() = Scanf.scanf " %d" (fun x -> x) in
let rec read_mp i =
    if (i > n) then () else
    begin
        mp.(scan_int()) <- i;
        read_mp (i+1)
    end
in
let () = read_mp 1 in
let rec read_int_list n cur = match n with
    | 0 -> cur
    | n -> let x = scan_int() in read_int_list (n-1) (x::cur)
in
let a = read_int_list n [] in
let rec count_bad b mn total = match b with
    | [] -> total
    | x::xs -> begin
        let x = mp.(x) in
        count_bad xs (if x < mn then x else mn) (if x > mn then (total+1) else total)
    end
in Printf.printf "%d\n" (count_bad a (n+1) 0)

let n = read_int() in
let mp = Array.make (n+1) 0 in
let scan_int() = Scanf.scanf " %d" (fun x -> x) in
let rec read_mp i =
    if (i > n) then () else
    begin
        (mp.(i) <- scan_int());
        read_mp (i+1)
    end
in
let () = read_mp 1 in
let rec read_int_list n cur = match n with
    | 0 -> cur
    | n -> let x = scan_int() in read_int_list (n-1) (x::cur)
in
let a = read_int_list n [] in
let rec count_bad b mn total = match b with
    | [] -> total
    | x::xs ->
        let x = mp.(x) in
        count_bad xs (if x < mn then x else mn) (if x > mn then (total+1) else total)
in Printf.printf "%d\n" (count_bad a (n+1) 0)


You are given an array a with n elements. Each element of a is either 0 or 1.Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).

The first line contains two integers n and k (1 ≤ n ≤ 3·105, 0 ≤ k ≤ n) — the number of elements in a and the parameter k. The second line contains n integers ai (0 ≤ ai ≤ 1) — the elements of a.

On the first line print a non-negative integer z — the maximal value of f(a) after no more than k changes of zeroes to ones. On the second line print n integers aj — the elements of the array a after the changes. If there are multiple answers, you can print any one of them.

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
  in
  let l = ref 0 in
  let z = ref 0 in
  let b = ref 0 in
  let bl = ref 0 in
  let br = ref 0 in
    for r = 0 to n - 1 do
      if a.(r) = 0 then (
	incr z;
      );
      while !l <= r && !z > k do
	if a.(!l) = 0
	then decr z;
	incr l;
      done;
      if r - !l + 1 >= !b then (
	b := r - !l + 1;
	bl := !l;
	br := r;
      );
    done;
    Printf.printf "%d\n" !b;
    for i = 0 to n - 1 do
      let x =
	if !bl <= i && i <= !br
	then 1
	else a.(i)
      in
	Printf.printf "%d " x
    done;
    Printf.printf "\n"