A boy named Ayrat lives on planet AMI-1511. Each inhabitant of this planet has a talent. Specifically, Ayrat loves running, moreover, just running is not enough for him. He is dreaming of making running a real art.First, he wants to construct the running track with coating t. On planet AMI-1511 the coating of the track is the sequence of colored blocks, where each block is denoted as the small English letter. Therefore, every coating can be treated as a string.Unfortunately, blocks aren't freely sold to non-business customers, but Ayrat found an infinite number of coatings s. Also, he has scissors and glue. Ayrat is going to buy some coatings s, then cut out from each of them exactly one continuous piece (substring) and glue it to the end of his track coating. Moreover, he may choose to flip this block before glueing it. Ayrat want's to know the minimum number of coating s he needs to buy in order to get the coating t for his running track. Of course, he also want's to know some way to achieve the answer.

First line of the input contains the string s — the coating that is present in the shop. Second line contains the string t — the coating Ayrat wants to obtain. Both strings are non-empty, consist of only small English letters and their length doesn't exceed 2100.

The first line should contain the minimum needed number of coatings n or -1 if it's impossible to create the desired coating. If the answer is not -1, then the following n lines should contain two integers xi and yi — numbers of ending blocks in the corresponding piece. If xi ≤ yi then this piece is used in the regular order, and if xi > yi piece is used in the reversed order. Print the pieces in the order they should be glued to get the string t.

NoteIn the first sample string "cbaabc" = "cba" + "abc".In the second sample: "ayrat" = "a" + "yr" + "at".

let read1 () = Scanf.scanf "%d\n" ( fun x -> x );;
let read2 () = Scanf.scanf "%d %d\n" ( fun x y -> x, y );;
let read3 () = Scanf.scanf "%d %d %d\n" ( fun x y z -> x, y, z);;
let read x = (if x = 0 then Scanf.scanf "%d\n" else Scanf.scanf "%d ") ( fun x -> x );;

let (+$) x y =
  if x > max_int - y then max_int
  else x + y;;

let rec ( *$ ) x y =
  if y = 0 then 0 else
  if y mod 2 = 1 then x *$ (y-1) +$ x
  else let a = x *$ (y/2) in a +$ a;;

let (+|) = Int64.add;;
let (-|) = Int64.sub;;
let ( *| ) = Int64.mul;;
let ( /| ) = Int64.div;;
let two_64 = Int64.one +| Int64.one;;

let licz x = (x-|Int64.one)/|two_64;;

let init n g =
  let q = String.make n 'a' in
  for i=0 to (n-1) do
    q.[i] <- g i
  done; q;;

let szukaj w t wynik =
  let nt = String.length t in
  let rt = init nt (fun x -> t.[nt-x-1]) in
  let s = "!"^w^"#"^t^"$"^rt in
  let n = String.length s in
  let pre = Array.make n 0
  and d = ref (-1)
  and maxi = ref 0
  and juz = ref false in
  pre.(0) <- -1;
  for i=1 to (n-1) do
    while !d >= 0 && s.[!d+1] <> s.[i] do
      d := pre.( !d )
    done;
    incr d;
    pre.(i) <- !d;
    if !juz then maxi := max !maxi !d;
    if s.[i] = '#' then juz := true
  done;
  if !maxi = 0 then 0
  else begin
    let id = ref 0
    and wyn = ref (0,0)
    and wzrost = ref 0 in
    for i=0 to n-1 do
      id := !id + !wzrost;
      if s.[i] = '#' then wzrost := 1;
      if s.[i] = '$' then begin wzrost := -1; id := nt+1 end;
      if pre.(i) = !maxi then wyn := (!id - ( (!maxi-1) * !wzrost), !id )
    done;
    wynik := !wyn :: !wynik;
    !maxi
  end;;

let rec wypisz lista =
  match lista with
  | [] -> ()
  | (a,b)::t -> wypisz t;Printf.printf "%d %d\n" a b;;

let _ =
  let (t,ww) = Scanf.scanf "%s\n%s\n" ( fun x y -> x,y ) in
  let w = ref ww
  and wynik = ref []
  and dalej = ref true
  in
  while String.length !w <> 0 && !dalej do
    let k =  szukaj !w t wynik in
    if k = 0 then dalej := false
    else
      let q = init (String.length !w - k) (fun x -> !w.[x+k])
      in w := q
  done;
  if String.length !w <> 0 then Printf.printf "-1\n"
  else begin Printf.printf "%d\n" (List.length !wynik); wypisz !wynik end;;

let read1 () = Scanf.scanf "%d\n" ( fun x -> x );;
let read2 () = Scanf.scanf "%d %d\n" ( fun x y -> x, y );;
let read3 () = Scanf.scanf "%d %d %d\n" ( fun x y z -> x, y, z);;
let read x = (if x = 0 then Scanf.scanf "%d\n" else Scanf.scanf "%d ") ( fun x -> x );;

let (+$) x y =
  if x > max_int - y then max_int
  else x + y;;

let rec ( *$ ) x y =
  if y = 0 then 0 else
  if y mod 2 = 1 then x *$ (y-1) +$ x
  else let a = x *$ (y/2) in a +$ a;;

let (+|) = Int64.add;;
let (-|) = Int64.sub;;
let ( *| ) = Int64.mul;;
let ( /| ) = Int64.div;;
let two_64 = Int64.one +| Int64.one;;

let licz x = (x-|Int64.one)/|two_64;;

let init n g =
  let q = String.make n 'a' in
  for i=0 to (n-1) do
    q.[i] <- g i
  done; q;;

let szukaj w t wynik =
  let nt = String.length t in
  let rt = init nt (fun x -> t.[nt-x-1]) in
  let s = w^"#"^t^"$"^rt in
  let n = String.length s in
  let pre = Array.make n 0
  and d = ref (-1)
  and maxi = ref 0
  and juz = ref false in
  pre.(0) <- -1;
  for i=1 to (n-1) do
    while !d >= 0 && s.[!d] <> s.[i] do
      d := pre.(!d)
    done;
    incr d;
    pre.(i) <- !d;
    if !juz then maxi := max !maxi !d;
    if s.[i] = '#' then juz := true
  done;
  if !maxi = 0 then 0
  else begin
    let id = ref 0
    and wyn = ref (0,0)
    and wzrost = ref 0 in
    for i=0 to n-1 do
      id := !id + !wzrost;
      if s.[i] = '#' then wzrost := 1;
      if s.[i] = '$' then begin wzrost := -1; id := nt+1 end;
      if pre.(i) = !maxi then wyn := (!id - ( (!maxi-1) * !wzrost), !id )
    done;
    wynik := !wyn :: !wynik;
    !maxi
  end;;

let rec wypisz lista =
  match lista with
  | [] -> ()
  | (a,b)::t -> wypisz t;Printf.printf "%d %d\n" a b;;

let _ =
  let (t,ww) = Scanf.scanf "%s\n%s\n" ( fun x y -> x,y ) in
  let w = ref ww
  and wynik = ref []
  and dalej = ref true
  in
  while String.length !w <> 0 && !dalej do
    let k =  szukaj !w t wynik in
    if k = 0 then dalej := false
    else
      let q = init (String.length !w - k) (fun x -> !w.[x+k])
      in w := q
  done;
  if String.length !w <> 0 then Printf.printf "-1\n"
  else begin Printf.printf "%d\n" (List.length !wynik); wypisz !wynik end;;

let read1 () = Scanf.scanf "%d\n" ( fun x -> x );;
let read2 () = Scanf.scanf "%d %d\n" ( fun x y -> x, y );;
let read3 () = Scanf.scanf "%d %d %d\n" ( fun x y z -> x, y, z);;
let read x = (if x = 0 then Scanf.scanf "%d\n" else Scanf.scanf "%d ") ( fun x -> x );;

let (+$) x y =
  if x > max_int - y then max_int
  else x + y;;

let rec ( *$ ) x y =
  if y = 0 then 0 else
  if y mod 2 = 1 then x *$ (y-1) +$ x
  else let a = x *$ (y/2) in a +$ a;;

let (+|) = Int64.add;;
let (-|) = Int64.sub;;
let ( *| ) = Int64.mul;;
let ( /| ) = Int64.div;;
let two_64 = Int64.one +| Int64.one;;

let licz x = (x-|Int64.one)/|two_64;;

let init n g =
  let q = String.make n 'a' in
  for i=0 to (n-1) do
    q.[i] <- g i
  done; q;;

let szukaj w t wynik =
  let nt = String.length t in
  let rt = init nt (fun x -> t.[nt-x-1]) in
  let s = w^"#"^t^"$"^rt in
  let n = String.length s in
  let pre = Array.make n 0
  and d = ref (-1)
  and maxi = ref 0
  and juz = ref false in
  pre.(0) <- 0;
  for i=1 to (n-1) do
    while !d >= 0 && s.[!d] <> s.[i] do
      if !d = 0 then d := -1
      else d := pre.( !d - 1 )
    done;
    incr d;
    pre.(i) <- !d;
    if !juz then maxi := max !maxi !d;
    if s.[i] = '#' then juz := true
  done;
  if !maxi = 0 then 0
  else begin
    let id = ref 0
    and wyn = ref (0,0)
    and wzrost = ref 0 in
    for i=0 to n-1 do
      id := !id + !wzrost;
      if s.[i] = '#' then wzrost := 1;
      if s.[i] = '$' then begin wzrost := -1; id := nt+1 end;
      if pre.(i) = !maxi then wyn := (!id - ( (!maxi-1) * !wzrost), !id )
    done;
    wynik := !wyn :: !wynik;
    !maxi
  end;;

let rec wypisz lista =
  match lista with
  | [] -> ()
  | (a,b)::t -> wypisz t;Printf.printf "%d %d\n" a b;;

let _ =
  let (t,ww) = Scanf.scanf "%s\n%s\n" ( fun x y -> x,y ) in
  let w = ref ww
  and wynik = ref []
  and dalej = ref true
  in
  while String.length !w <> 0 && !dalej do
    let k =  szukaj !w t wynik in
    if k = 0 then dalej := false
    else
      let q = init (String.length !w - k) (fun x -> !w.[x+k])
      in w := q
  done;
  if String.length !w <> 0 then Printf.printf "-1\n"
  else begin Printf.printf "%d\n" (List.length !wynik); wypisz !wynik end;;

let read1 () = Scanf.scanf "%d\n" ( fun x -> x );;
let read2 () = Scanf.scanf "%d %d\n" ( fun x y -> x, y );;
let read3 () = Scanf.scanf "%d %d %d\n" ( fun x y z -> x, y, z);;
let read x = (if x = 0 then Scanf.scanf "%d\n" else Scanf.scanf "%d ") ( fun x -> x );;

let (+$) x y =
  if x > max_int - y then max_int
  else x + y;;

let rec ( *$ ) x y =
  if y = 0 then 0 else
  if y mod 2 = 1 then x *$ (y-1) +$ x
  else let a = x *$ (y/2) in a +$ a;;

let (+|) = Int64.add;;
let (-|) = Int64.sub;;
let ( *| ) = Int64.mul;;
let ( /| ) = Int64.div;;
let two_64 = Int64.one +| Int64.one;;

let licz x = (x-|Int64.one)/|two_64;;

let init n g =
  let q = String.make n 'a' in
  for i=0 to (n-1) do
    q.[i] <- g i
  done; q;;

let szukaj w t wynik =
  let nt = String.length t in
  let rt = init nt (fun x -> t.[nt-x-1]) in
  let s = w^"#"^t^"$"^rt in
  let n = String.length s in
  let pre = Array.make n 0
  and d = ref (-1)
  and maxi = ref 0
  and juz = ref false in
  pre.(0) <- -1;
  for i=1 to (n-1) do
    while !d >= 0 && s.[!d] <> s.[i] do
      d := pre.(!d)
    done;
    incr d;
    pre.(i) <- !d;
    if !juz then maxi := max !maxi !d;
    if s.[i] = '#' then juz := true
  done;
  if !maxi = 0 then 0
  else begin
    let id = ref 0
    and wyn = ref (0,0)
    and wzrost = ref 0 in
    for i=0 to n-1 do
      id := !id + !wzrost;
      if s.[i] = '#' then wzrost := 1;
      if s.[i] = '$' then begin wzrost := -1; id := nt+1 end;
      if pre.(i) = !maxi then wyn := (!id - ( (!maxi-1) * !wzrost), !id )
    done;
    wynik := !wyn :: !wynik;
    !maxi
  end;;

let rec wypisz lista =
  match lista with
  | [] -> ()
  | (a,b)::t -> wypisz t;Printf.printf "%d %d\n" a b;;

let _ =
  let (t,ww) = Scanf.scanf "%s\n%s\n" ( fun x y -> x,y ) in
  let w = ref ww
  and wynik = ref []
  and dalej = ref true
  in
  while String.length !w <> 0 && !dalej do
    let k =  szukaj !w t wynik in
    if k = 0 then dalej := false
    else
      let q = init (String.length !w - k) (fun x -> !w.[x+k])
      in w := q
  done;
  if String.length !w <> 0 then Printf.printf "-1\n"
  else Printf.printf "%d\n" (List.length !wynik); wypisz !wynik;


Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1, a2, ..., an are good.Now she is interested in good sequences. A sequence x1, x2, ..., xk is called good if it satisfies the following three conditions:  The sequence is strictly increasing, i.e. xi < xi + 1 for each i (1 ≤ i ≤ k - 1).  No two adjacent elements are coprime, i.e. gcd(xi, xi + 1) > 1 for each i (1 ≤ i ≤ k - 1) (where gcd(p, q) denotes the greatest common divisor of the integers p and q).  All elements of the sequence are good integers. Find the length of the longest good sequence.

The input consists of two lines. The first line contains a single integer n (1 ≤ n ≤ 105) — the number of good integers. The second line contains a single-space separated list of good integers a1, a2, ..., an in strictly increasing order (1 ≤ ai ≤ 105; ai < ai + 1).

Print a single integer — the length of the longest good sequence.

NoteIn the first example, the following sequences are examples of good sequences: [2; 4; 6; 9], [2; 4; 6], [3; 9], [6]. The length of the longest good sequence is 4.

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

let factor n =
  let rec loop n p ac =
    if n=1 then ac
    else if p*p > n then (n::ac)
    else if n mod p = 0 then loop (n/p) p (p::ac)
    else loop n (p+1) ac
  in
    List.rev (loop n 2 [])

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

  let h = Hashtbl.create 10 in

  let getp p = try Hashtbl.find h p with Not_found -> 0 in

  let rec loop i ac = if i=n then ac else (
    let fl = factor a.(i) in
    let m = 1 + List.fold_left (fun ac p -> max ac (getp p)) 0 fl in
      List.iter (fun p -> Hashtbl.replace h p m) fl;
      loop (i+1) (max ac m)

  ) in

  let ans = loop 0 0 in
    Printf.printf "%d\n" ans


Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.She has $$$n$$$ friends who are also grannies (Maria is not included in this number). The $$$i$$$-th granny is ready to attend the ceremony, provided that at the time of her appearance in the courtyard there will be at least $$$a_i$$$ other grannies there. Note that grannies can come into the courtyard at the same time. Formally, the granny $$$i$$$ agrees to come if the number of other grannies who came earlier or at the same time with her is greater than or equal to $$$a_i$$$.Grannies gather in the courtyard like that.  Initially, only Maria is in the courtyard (that is, the initial number of grannies in the courtyard is $$$1$$$). All the remaining $$$n$$$ grannies are still sitting at home. On each step Maria selects a subset of grannies, none of whom have yet to enter the courtyard. She promises each of them that at the time of her appearance there will be at least $$$a_i$$$ other grannies (including Maria) in the courtyard. Maria can call several grannies at once. In this case, the selected grannies will go out into the courtyard at the same moment of time. She cannot deceive grannies, that is, the situation when the $$$i$$$-th granny in the moment of appearing in the courtyard, finds that now there are strictly less than $$$a_i$$$ other grannies (except herself, but including Maria), is prohibited. Please note that if several grannies appeared in the yard at the same time, then each of them sees others at the time of appearance. Your task is to find what maximum number of grannies (including herself) Maria can collect in the courtyard for the ceremony. After all, the more people in one place during quarantine, the more effective the ceremony!Consider an example: if $$$n=6$$$ and $$$a=[1,5,4,5,1,9]$$$, then:  at the first step Maria can call grannies with numbers $$$1$$$ and $$$5$$$, each of them will see two grannies at the moment of going out into the yard (note that $$$a_1=1 \le 2$$$ and $$$a_5=1 \le 2$$$);  at the second step, Maria can call grannies with numbers $$$2$$$, $$$3$$$ and $$$4$$$, each of them will see five grannies at the moment of going out into the yard (note that $$$a_2=5 \le 5$$$, $$$a_3=4 \le 5$$$ and $$$a_4=5 \le 5$$$);  the $$$6$$$-th granny cannot be called into the yard  — therefore, the answer is $$$6$$$ (Maria herself and another $$$5$$$ grannies).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then test cases follow. The first line of a test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of grannies (Maria is not included in this number). The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$). It is guaranteed that the sum of the values $$$n$$$ over all test cases of the input does not exceed $$$10^5$$$.

For each test case, print a single integer $$$k$$$ ($$$1 \le k \le n + 1$$$) — the maximum possible number of grannies in the courtyard.

NoteIn the first test case in the example, on the first step Maria can call all the grannies. Then each of them will see five grannies when they come out. Therefore, Maria and five other grannies will be in the yard.In the second test case in the example, no one can be in the yard, so Maria will remain there alone.The third test case in the example is described in the details above.In the fourth test case in the example, on the first step Maria can call grannies with numbers $$$1$$$, $$$2$$$ and $$$3$$$. If on the second step Maria calls $$$4$$$ or $$$5$$$ (one of them), then when a granny appears in the yard, she will see only four grannies (but it is forbidden). It means that Maria can't call the $$$4$$$-th granny or the $$$5$$$-th granny separately (one of them). If she calls both: $$$4$$$ and $$$5$$$, then when they appear, they will see $$$4+1=5$$$ grannies. Despite the fact that it is enough for the $$$4$$$-th granny, the $$$5$$$-th granny is not satisfied. So, Maria cannot call both the $$$4$$$-th granny and the $$$5$$$-th granny at the same time. That is, Maria and three grannies from the first step will be in the yard in total.

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 n = read_int() in
    let a = Array.init n read_int in
    Array.sort compare a;
    let rec loop i j current =
      (* grannies 0...i-1 are already there.
	 current = #there counting maria.
	 Try to put all grannies from i to j there all
	 at once.  If possible do it. Otherwise move
	 onto i (j+1).
      *)
      if current + (j-i) >= a.(j) then (
	let current = current + (j-i+1) in
	if j+1 = n then current else loop (j+1) (j+1) current
      ) else (
	if j+1 = n then current else loop i (j+1) current
      )
    in
    printf "%d\n" (loop 0 0 1)
  done


Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company. Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!

The first line of the input contains two space-separated integers, n and d (1 ≤ n ≤ 105, ) — the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively. Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type mi, si (0 ≤ mi, si ≤ 109) — the amount of money and the friendship factor, respectively.

Print the maximum total friendship factir that can be reached.

NoteIn the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.In the second sample test we can take all the friends.

open Big_int;;

let main () =
	let (n,d) = Scanf.scanf "%d %d" (fun i j -> (i,j)) and l = ref []
	in
		for i=1 to n do
			Scanf.scanf " %d %s" (fun i j -> l := (i,big_int_of_string j)::!l);
		done;
	let tab = Array.of_list (List.sort (fun (i,_) (j,_) -> compare i j) !l) and i = ref 0
	and j = ref 0 in
	let act = ref (snd (tab.(0))) and maxi= ref (big_int_of_int 0) in
		while !j < n do
			if fst (tab.(!j)) - fst (tab.(!i)) < d
				then (
			maxi := max_big_int !maxi !act;incr j;if !j < n then act := add_big_int !act (snd (tab.(!j))))
				else (act := sub_big_int !act (snd (tab.(!i))); incr i);
		done;
	Printf.printf "%s" (string_of_big_int !maxi);;

main ();;

let read_int64 () = Scanf.bscanf Scanf.Scanning.stdin " %s " (fun x -> Big_int.big_int_of_string x);;
let read_int () = Scanf.bscanf Scanf.Scanning.stdin " %d " (fun x -> x);;
let read_pair _ = let x = read_int64 () in let y = read_int64 () in (x, y);;
let comp (a, b) (c, d) = if (Big_int.compare_big_int a c) = 0 then Big_int.compare_big_int b d else Big_int.compare_big_int a c;;
let main () =
    let n = read_int () in
    let d = read_int64 () in
    let a = Array.init n read_pair in
    let _ = Array.sort comp a in
    let (i, j, k, c) = (ref 0, ref 0, ref (Big_int.big_int_of_int 0), ref (Big_int.big_int_of_int 0)) in (
        while !i < n do (
            match (a.(!i), a.(!j)) with
            | ((x, y), (z, w)) -> (
                if Big_int.compare_big_int (Big_int.sub_big_int x z) d < 0 then
                    (k := (Big_int.add_big_int !k y); c := (Big_int.max_big_int (!c) (!k)); incr i)
                else
                    (k := (Big_int.sub_big_int !k w); incr j)
            )
        )
        done;
        Printf.printf "%s\n" (Big_int.string_of_big_int !c)
    )
;;

main ();;

let read_int64 () = Scanf.bscanf Scanf.Scanning.stdin " %d " (fun x -> Int64.of_int x);;
let read_int () = Scanf.bscanf Scanf.Scanning.stdin " %d " (fun x -> x);;
let read_pair _ = let x = read_int64 () in let y = read_int64 () in (x, y);;
let comp (a, b) (c, d) = if (Int64.compare a c) = 0 then Int64.compare b d else Int64.compare a c;;
let main () =
    let n = read_int () in
    let d = read_int64 () in
    let a = Array.init n read_pair in
    let _ = Array.sort comp a in
    let (i, j, k, c) = (ref 0, ref 0, ref 0L, ref 0L) in (
        while !i < n do (
            match (a.(!i), a.(!j)) with
            | ((x, y), (z, w)) -> (
                if Int64.compare (Int64.sub x z) d < 0 then
                    (k := (Int64.add !k y); c := (max (!c) (!k)); incr i)
                else
                    (k := (Int64.sub !k w); incr j)
            )
        )
        done;
        Printf.printf "%s\n" (Int64.to_string !c)
    )
;;
main ();;

let main () =
	let (n,d) = Scanf.scanf "%d %d" (fun i j -> (i,j)) and l = ref []
	in
		for i=1 to n do
			Scanf.scanf " %d %d" (fun i j -> l := (i,j)::!l);
		done;
	let tab = Array.of_list (List.sort compare !l) and i = ref 0
	and j = ref 0 in
	let act = ref (snd (tab.(0))) and maxi= ref 0 in
		while !j < n do
			if fst (tab.(!j)) - fst (tab.(!i)) < d
				then (
			maxi := max !maxi !act;incr j;if !j < n then act := !act + snd (tab.(!j)))
				else (act := !act - snd (tab.(!i)); incr i);
		done;
	Printf.printf "%d" !maxi;;

main ();;

let read_int () = Scanf.bscanf Scanf.Scanning.stdin " %d " (fun x -> x);;
let read_pair _ = let x = read_int () in let y = read_int () in (x, y);;
let comp a b = if a < b then -1 else if a = b then 0 else 1;;
let main () =
    let n = read_int () in
    let d = read_int () in
    let a = Array.init n read_pair in
    let _ = Array.sort comp a in
    let (i, j, k, c) = (ref 0, ref 0, ref 0, ref 0) in (
        while !i < n do (
            match (a.(!i), a.(!j)) with
            | ((x, y), (z, w)) -> (
                if x - z < d then
                    (k := !k + y; c := max (!c) (!k); incr i)
                else
                    (k := !k - w; incr j)
            )
        )
        done;
        Printf.printf "%d\n" (!c)
    )
;;

main ();;


Vanya is managed to enter his favourite site Codehorses. Vanya uses n distinct passwords for sites at all, however he can't remember which one exactly he specified during Codehorses registration.Vanya will enter passwords in order of non-decreasing their lengths, and he will enter passwords of same length in arbitrary order. Just when Vanya will have entered the correct password, he is immediately authorized on the site. Vanya will not enter any password twice.Entering any passwords takes one second for Vanya. But if Vanya will enter wrong password k times, then he is able to make the next try only 5 seconds after that. Vanya makes each try immediately, that is, at each moment when Vanya is able to enter password, he is doing that.Determine how many seconds will Vanya need to enter Codehorses in the best case for him (if he spends minimum possible number of second) and in the worst case (if he spends maximum possible amount of seconds).

The first line of the input contains two integers n and k (1 ≤ n, k ≤ 100) — the number of Vanya's passwords and the number of failed tries, after which the access to the site is blocked for 5 seconds. The next n lines contains passwords, one per line — pairwise distinct non-empty strings consisting of latin letters and digits. Each password length does not exceed 100 characters. The last line of the input contains the Vanya's Codehorses password. It is guaranteed that the Vanya's Codehorses password is equal to some of his n passwords.

Print two integers — time (in seconds), Vanya needs to be authorized to Codehorses in the best case for him and in the worst case respectively.

NoteConsider the first sample case. As soon as all passwords have the same length, Vanya can enter the right password at the first try as well as at the last try. If he enters it at the first try, he spends exactly 1 second. Thus in the best case the answer is 1. If, at the other hand, he enters it at the last try, he enters another 4 passwords before. He spends 2 seconds to enter first 2 passwords, then he waits 5 seconds as soon as he made 2 wrong tries. Then he spends 2 more seconds to enter 2 wrong passwords, again waits 5 seconds and, finally, enters the correct password spending 1 more second. In summary in the worst case he is able to be authorized in 15 seconds.Consider the second sample case. There is no way of entering passwords and get the access to the site blocked. As soon as the required password has length of 2, Vanya enters all passwords of length 1 anyway, spending 2 seconds for that. Then, in the best case, he immediately enters the correct password and the answer for the best case is 3, but in the worst case he enters wrong password of length 2 and only then the right one, spending 4 seconds at all.

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

let find array n =
  let rec loop low high i =
    if i = Array.length array then low, high
    else begin
      let sl = String.length array.(i) in
      if sl < n then loop (low + 1) high (i + 1)
      else if sl = n then loop low (high + 1) (i + 1)
      else loop low high (i + 1)
    end
  in
  let low, high = loop 0 0 0 in
  low, low + high

let () =
  let n = read_int () in
  let k = read_int () in
  let array = Array.init n (fun _ ->
      read_string ()
    )
  in
  let ra = read_string () in
  let (low, high) = find array (String.length ra) in
  let a, b =
    let c = if k = 0 then 0 else (high -1) / k in
    let d = if k = 0 then 0 else low / k in
    if low = 0 then 1, (5 * c + high)
    else (5 * d + low + 1), (5 * c + high)
  in
  Printf.printf "%d %d" a b

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

let find array n =
  let rec loop low high i =
    if i = Array.length array then low, high
    else begin
      let sl = String.length array.(i) in
      if sl < n then loop (low + 1) high (i + 1)
      else if sl = n then loop low (high + 1) (i + 1)
      else loop low high (i + 1)
    end
  in
  let low, high = loop 0 0 0 in
  low, low + high

let () =
  let n = read_int () in
  let k = read_int () in
  let array = Array.init n (fun _ ->
      read_string ()
    )
  in
  let ra = read_string () in
  let (low, high) = find array (String.length ra) in
  let a, b =
    let c = if k = 0 then 0 else high / k in
    let d = if k = 0 then 0 else low / k in
    if low = 0 then 1, (5 * c + high)
    else (5 * d + low + 1), (5 * c + high)
  in
  Printf.printf "%d %d" a b

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

let find array n =
  let rec loop low high i =
    if i = Array.length array then low, high
    else begin
      let sl = String.length array.(i) in
      if sl < n then loop (low + 1) high (i + 1)
      else if sl = n then loop low (high + 1) (i + 1)
      else loop low high (i + 1)
    end
  in
  let low, high = loop 0 0 0 in
  low, low + high

let () =
  let n = read_int () in
  let k = read_int () in
  let array = Array.init n (fun _ ->
      read_string ()
    )
  in
  let ra = read_string () in
  let (low, high) = find array (String.length ra) in
  let a, b =
    if low = 0 then 1, (5 * (high / k) + high)
    else (5 * (low / k) + low + 1), (5 * (high / k) + high)
  in
  Printf.printf "%d %d" a b


One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop.Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist.

The first line contains an integer n (1 ≤ n ≤ 105) — the number of laptops. Next n lines contain two integers each, ai and bi (1 ≤ ai, bi ≤ n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality). All ai are distinct. All bi are distinct.

If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes).

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

let make_sorted_list () =
    let n = read () in
    let rec loop i list =
        if i < n
        then
            let price = read () in
            let quality = read () in
            loop (i + 1) ((price, quality) :: list)
        else
            List.sort (Pervasives.compare) list
    in loop 0 []

let solve () =
    let notebooks = make_sorted_list () in
    let rec loop list prev_price prev_quality =
        match list with
        | ((price, quality) :: tail) ->
            if prev_quality > quality
            then
                "Happy Alex"
            else
                loop tail price quality
        | [] -> "Poor Alex"
    in loop notebooks 0 (-1)

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

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

let make_sorted_list () =
    let n = read () in
    let rec loop i list =
        if i < n
        then
            let price = read () in
            let quality = read () in
            loop (i + 1) ((price, quality) :: list)
        else
            List.sort (Pervasives.compare) list
    in loop 0 []

let solve () =
    let notebooks = make_sorted_list () in
    let rec loop list prev_price prev_quality =
        match list with
        | ((price, quality) :: tail) ->
            if prev_quality > quality
            then
                "Happy Alex"
            else
                loop tail price quality
        | [] -> "Poor Alex"
    in loop notebooks 0 1000001

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


A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.

The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.

Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.

let _ =
  let sb = Scanf.Scanning.stdib in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let n = String.length s in
  let a = Array.make 26 0 in
    for i = 0 to n - 1 do
      let c = Char.code s.[i] - Char.code 'a' in
	a.(c) <- a.(c) + 1
    done;
    let res = ref [] in
    let res2 = ref [] in
    let l = ref 0 in
    let r = ref 25 in
    let odd = ref (-1) in
      (*if n mod 2 <> 0 then (
	while a.(!r) mod 2 = 0 do
	  decr r
	done;
	odd := !r;
	a.(!r) <- a.(!r) - 1;
	r := 25;
      );*)
      for i = 1 to n / 2 do
	while a.(!l) = 0 do
	  incr l
	done;
	while a.(!r) = 0 do
	  decr r
	done;
(*Printf.printf "asd %d %d %d %d\n" !l !r a.(!l) a.(!r);*)
	if a.(!l) mod 2 = 0 then (
	  res := !l :: !res;
	  a.(!l) <- a.(!l) - 2;
	) else if a.(!r) mod 2 = 0 then (
	  res2 := !r :: !res2;
	  a.(!r) <- a.(!r) - 2;
	) else (
	  res := !l :: !res;
	  a.(!l) <- a.(!l) - 1;
	  a.(!r) <- a.(!r) - 1;
	)
      done;
      if n mod 2 <> 0 then (
	while a.(!l) = 0 do
	  incr l
	done;
	while a.(!r) = 0 do
	  decr r
	done;
	assert (!l = !r && a.(!l) = 1);
	odd := !l;
	a.(!l) <- a.(!l) - 1;
      );
      let res =
	if n mod 2 = 0
	then List.rev !res @ !res2 @ List.rev !res2 @ !res
	else List.rev !res @ !res2 @ [!odd] @ List.rev !res2 @ !res
      in
	List.iter
	  (fun c ->
	     Printf.printf "%c" (Char.chr (c + Char.code 'a'))
	  ) res;
	Printf.printf "\n"

let _ =
  let sb = Scanf.Scanning.stdib in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let n = String.length s in
  let a = Array.make 26 0 in
    for i = 0 to n - 1 do
      let c = Char.code s.[i] - Char.code 'a' in
	a.(c) <- a.(c) + 1
    done;
    let res = ref [] in
    let res2 = ref [] in
    let l = ref 0 in
    let r = ref 25 in
    let odd = ref (-1) in
      (*if n mod 2 <> 0 then (
	while a.(!r) mod 2 = 0 do
	  decr r
	done;
	odd := !r;
	a.(!r) <- a.(!r) - 1;
	r := 25;
      );*)
      for i = 1 to n / 2 do
	while a.(!l) = 0 do
	  incr l
	done;
	while a.(!r) = 0 do
	  decr r
	done;
(*Printf.printf "asd %d %d %d %d\n" !l !r a.(!l) a.(!r);*)
	if a.(!l) mod 2 = 0 then (
	  res := !l :: !res;
	  a.(!l) <- a.(!l) - 2;
	) else if a.(!r) mod 2 = 0 then (
	  res2 := !r :: !res2;
	  a.(!r) <- a.(!r) - 2;
	) else (
	  res := !l :: !res;
	  a.(!l) <- a.(!l) - 1;
	  a.(!r) <- a.(!r) - 1;
	)
      done;
      if n mod 2 <> 0 then (
	while a.(!l) = 0 do
	  incr l
	done;
	while a.(!r) = 0 do
	  decr r
	done;
	assert (!l = !r && a.(!l) = 1);
	odd := !l;
	a.(!l) <- a.(!l) - 1;
      );
      let res =
	if n mod 2 = 0
	then List.rev !res @ List.rev !res2 @ !res2 @ !res
	else List.rev !res @ List.rev !res2 @ [!odd] @ !res2 @ !res
      in
	List.iter
	  (fun c ->
	     Printf.printf "%c" (Char.chr (c + Char.code 'a'))
	  ) res;
	Printf.printf "\n"


A Martian boy is named s — he has got this name quite recently from his parents for his coming of age birthday. Now he enjoys looking for his name everywhere. If he sees that he can obtain his name from some string by removing zero or more letters (at that, the remaining letters remain in the same order), he gets happy. For example, if s=«aba», then strings «baobab», «aabbaa», «helloabahello» make him very happy and strings «aab», «baaa» and «helloabhello» do not.However rather than being happy once, he loves twice as much being happy twice! So, when he got string t as a present, he wanted to cut it in two parts (the left part and the right part) so that each part made him happy.Help s determine the number of distinct ways to cut the given string t into two parts in the required manner.

The first line contains string s, consisting of lowercase English letters. The length of string s is from 1 to 1000 letters. The second line contains string t, that also consists of lowercase English letters. The length of string t is from 1 to 106 letters.

Print the sought number of ways to cut string t in two so that each part made s happy.

let explode s =
      let rec exp i l =
              if i < 0 then l else exp (i - 1) (s.[i] :: l) in
        exp (String.length s - 1) []

let _ =
    let a = explode (read_line ()) in
    let b = explode (read_line ()) in
    let rec least a b i =
        match (a, b) with
        | (x, []) -> -1
        | ([], y) -> i
        | (x :: xs, y :: ys) when x = y
            -> least xs ys (i + 1)
        | (x, y :: ys)
           -> least x ys (i + 1)
    in
    let start = least a b 0 in
    let finish = 1 + (List.length b) - least (List.rev a) (List.rev b) 0 in
    if start > finish || start = -1 || finish = -1 then
        print_endline "0"
    else
        print_endline (string_of_int (finish - start))


You are given an undirected weighted connected graph with $$$n$$$ vertices and $$$m$$$ edges without loops and multiple edges.The $$$i$$$-th edge is $$$e_i = (u_i, v_i, w_i)$$$; the distance between vertices $$$u_i$$$ and $$$v_i$$$ along the edge $$$e_i$$$ is $$$w_i$$$ ($$$1 \le w_i$$$). The graph is connected, i. e. for any pair of vertices, there is at least one path between them consisting only of edges of the given graph.A minimum spanning tree (MST) in case of positive weights is a subset of the edges of a connected weighted undirected graph that connects all the vertices together and has minimum total cost among all such subsets (total cost is the sum of costs of chosen edges).You can modify the given graph. The only operation you can perform is the following: increase the weight of some edge by $$$1$$$. You can increase the weight of each edge multiple (possibly, zero) times.Suppose that the initial MST cost is $$$k$$$. Your problem is to increase weights of some edges with minimum possible number of operations in such a way that the cost of MST in the obtained graph remains $$$k$$$, but MST is unique (it means that there is only one way to choose MST in the obtained graph).Your problem is to calculate the minimum number of operations required to do it.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5, n - 1 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges in the initial graph. The next $$$m$$$ lines contain three integers each. The $$$i$$$-th line contains the description of the $$$i$$$-th edge $$$e_i$$$. It is denoted by three integers $$$u_i, v_i$$$ and $$$w_i$$$ ($$$1 \le u_i, v_i \le n, u_i \ne v_i, 1 \le w \le 10^9$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices connected by the $$$i$$$-th edge and $$$w_i$$$ is the weight of this edge. It is guaranteed that the given graph doesn't contain loops and multiple edges (i.e. for each $$$i$$$ from $$$1$$$ to $$$m$$$ $$$u_i \ne v_i$$$ and for each unordered pair of vertices $$$(u, v)$$$ there is at most one edge connecting this pair of vertices). It is also guaranteed that the given graph is connected.

Print one integer — the minimum number of operations to unify MST of the initial graph without changing the cost of MST.

NoteThe picture corresponding to the first example: You can, for example, increase weight of the edge $$$(1, 6)$$$ or $$$(6, 3)$$$ by $$$1$$$ to unify MST.The picture corresponding to the last example: You can, for example, increase weights of edges $$$(1, 5)$$$ and $$$(2, 4)$$$ by $$$1$$$ to unify MST.

let jajka n k =
	let rzm = min (k + 1) 31 in
	let a = Array.make_matrix (n + 1) rzm 0 in
	let wynik = ref 0 in
	for i = 1 to n do
		for j = 1 to rzm - 1 do
			a.(i).(j) <- a.(i - 1).(j - 1) + a.(i - 1).(j) + 1;
			print_int a.(i).(j);
			print_string " ";
			if a.(i).(j) >= n && !wynik = 0 then wynik := i
		done;
		print_endline ""
	done;
	!wynik;;

let liczba () =
	Scanf.bscanf Scanf.Scanning.stdin " %d " (fun x -> x);;

let plecak l p =
	let a = Array.make (p + 1) 0 in
	let dodaj (poj, k) =
		for i = p downto poj do
			a.(i) <- max a.(i) (a.(i - poj) + k)
		done in
	List.iter dodaj l;
	Array.fold_left max 0 a;;

let repair_road t x =
	let p = ref 0 in
	let dl = (Array.length t) in
	let wynik = ref 0 in
	let odp = ref 0 in
	for i = 0 to dl - 1 do
		while !wynik <= x && !p < dl do
			wynik := !wynik + 1 - t.(!p);
			incr p
		done;
		if !wynik > x then begin
			decr p;
			wynik := !wynik - 1 + t.(!p)
		end;
		odp := max (!odp) (!p - i);
		wynik := !wynik - 1 + t.(i);(*
		print_int i;
		print_string " ";
		print_int !p;
		print_endline ""; *)
	done;
	!odp

let wczytaj () =
	let n = liczba () in
	let s = liczba () in
	let t = Array.make n 0 in
	for i = 0 to n - 1 do
		let pole = liczba () in(*
		print_int pole;
		print_endline ""; *)
		t.(i) <- pole
	done;
	print_int (repair_road t s);
	print_endline "";;

let main () =
	let n = liczba () in
	for i = 1 to n do
		wczytaj ()
	done;;

let examin x =
	let sito = Array.make (x + 1) 0 in
	let kolejka = Queue.create () in
	let mapa = Hashtbl.create 1000000 in
	let skad = Hashtbl.create 1000000 in
	let prims = ref [] in
	for i = 2 to x do
		prims := i :: !prims
	done;
	let primes = !prims in
	let dodaj a =
		if sito.(a) = 0 then
		let it = ref (a * a) in
		while !it <= x do
			sito.(!it) <- a;
			it := !it + a
		done in
	let rec dzielniki a =
		let akt_dziel = sito.(a) in
		if akt_dziel = 0 then [a] else
		let aktliczba = ref a in
		while !aktliczba mod akt_dziel = 0 do
			aktliczba := !aktliczba / akt_dziel
		done;
		(akt_dziel :: dzielniki !aktliczba) in
	List.iter dodaj primes;
	Hashtbl.add mapa x 0;
	Queue.add x kolejka;
	while not (Hashtbl.mem mapa 1) do
		let gora = Queue.take kolejka in
		let przejscia = dzielniki gora in
		let dodaj liczba wynik =
			Hashtbl.add mapa liczba wynik;
			Hashtbl.add skad liczba gora;
			Queue.add liczba kolejka in
		let przejdz dzielnik =
			if not (Hashtbl.mem mapa (gora / dzielnik)) then
				dodaj (gora / dzielnik) (Hashtbl.find mapa gora + 1) in
		List.iter przejdz przejscia;
		if not (Hashtbl.mem mapa (gora - 1)) then
			dodaj (gora - 1) (Hashtbl.find mapa gora + 1)
	done;
	let wynik = ref [] in
	let akt = ref 1 in
	while !akt <> x do
		wynik := (!akt :: !wynik);
		akt := Hashtbl.find skad !akt
	done;
	wynik := (x :: !wynik);
	List.rev !wynik

let to_array l =
	let n = List.length l in
	let tbl = Array.make n (List.hd l) in
	let lista = ref l in
	for i = 0 to n - 1 do
		tbl.(i) <- List.hd !lista;
		lista := List.tl !lista
	done;
	tbl

let dbg t =
	Array.iter (fun x -> print_int x) t;
	print_endline ""

let palindromy l =
	let n = List.length l in
	let l2 = l @ (List.rev l) in
	let tbl = to_array l2 in
	let knp = Array.make (List.length l2) 0 in
	for j = 0 to 1 do
		for i = 1 + n * j to n * (j + 1) - 1 do
			let odp = ref knp.(i - 1) in
			while tbl.(!odp) <> tbl.(i) && !odp <> 0 do
				odp := knp.(!odp - 1)
			done;
			if tbl.(!odp) = tbl.(i) then
				incr odp;
			knp.(i) <- !odp
		done;
		if tbl.(n) = tbl.(0) then
			knp.(n) <- 1
	done;
	knp.(2 * n - 1);;

let main () =
	let n = liczba () in
	let m = liczba () in
	let kraw = Array.make (m + 1) (0, 0, 0) in
	for i = 1 to m do
		let u = liczba () in
		let v = liczba () in
		let w = liczba () in
		kraw.(i) <- (u, v, w)
	done;
	let fu = Array.make (n + 1) 0 in
	let rozm = Array.make (n + 1) 0 in
	for i = 1 to n do
		fu.(i) <- i;
		rozm.(i) <- 1
	done;
	let rec znajdz x =
		if fu.(x) = x then x else
			let wynik = znajdz (fu.(x)) in
			fu.(x) <- wynik;
			wynik in
	let rec znajdz_rozm x =
		if fu.(x) = x then rozm.(x) else znajdz_rozm (fu.(x)) in
	let merge (x, y, _) =
		let v1 = znajdz x in
		let v2 = znajdz y in
		if znajdz_rozm v1 < znajdz_rozm v2 then begin
			fu.(v1) <- v2;
			rozm.(v2) <- rozm.(v2) + rozm.(v1)
		end else begin
			fu.(v2) <- v1;
			rozm.(v1) <- rozm.(v1) + rozm.(v2);
		end in
	let waga_kraw (_, _, w) = w in
	let pierw_kraw (w, _, _) = w in
	let drug_kraw (_, w, _) = w in
	Array.sort (fun (u1, v2, w1) (u2, v2, w2) -> w1 - w2) kraw;
	let poprz_waga = ref 0 in
	let lista = ref [] in
	let wynik = ref (m - n + 1) in
	for i = 1 to m do
		if waga_kraw kraw.(i) > !poprz_waga then begin
			List.iter (fun x -> merge kraw.(x)) !lista;
			lista := [];
			poprz_waga := waga_kraw kraw.(i)
		end;
		if znajdz (pierw_kraw kraw.(i)) = znajdz (drug_kraw kraw.(i)) then
			decr wynik
		else
			lista := (i :: !lista)
	done;
	print_int !wynik;;

main() ;;

let segment t =
	let n = Array.length t in
	let p = ref 0 in
	let lista = Array.make n 0 in
	let pocz = ref 0 in
	let kon = ref (-1) in
	let wynik = ref 0 in
	for i = 0 to n - 1 do
		print_int i;
		print_string " ";
		let mini () =
			if !pocz > !kon then t.(!p) else
			min t.(lista.(!pocz)) t.(!p) in
		while !p < n && mini () >= !p - i + 1 do
			while pocz <= kon && t.(lista.(!kon)) > t.(i) do
				decr kon
			done;
			incr kon;
			lista.(!kon) <- !p;
			incr p
		done;
		wynik := max !wynik (!p - i);
		if lista.(!pocz) = i && !pocz <= !kon then
			incr pocz;
		print_int !p;
		if !p = i then
			incr p;
		print_int !p;
		print_endline ""
	done;
	!wynik


Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.Note that the order of the points inside the group of three chosen points doesn't matter.

The first line contains two integers: n and d (1 ≤ n ≤ 105; 1 ≤ d ≤ 109). The next line contains n integers x1, x2, ..., xn, their absolute value doesn't exceed 109 — the x-coordinates of the points that Petya has got. It is guaranteed that the coordinates of the points in the input strictly increase.

Print a single integer — the number of groups of three points, where the distance between two farthest points doesn't exceed d. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample any group of three points meets our conditions.In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.In the third sample only one group does: {1, 10, 20}.

let read_int () = Scanf.bscanf Scanf.Scanning.stdib " %d " (fun x -> x)
(* it fails because they were using a 32 bit installation instead of 64 bit *)

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 d = read_int() in
  let x = Array.init n (fun i -> read_int()) in

  let rec loop l r ac =
    let r = max r (l+1) in
      if r=n then ac else (
	if x.(r) - x.(l) > d then loop (l+1) r ac else (
	  if r=n-1 || x.(r+1) > x.(l) + d  then (
	    let ll = Int64.of_int l in
	    let rr = Int64.of_int r in
	      let ac = ac ++ ((rr--ll) ** (rr--ll--1L)) // 2L in
		loop (l+1) r ac
	  ) else (
	    loop l (r+1) ac
	  )
	)
      )
  in

    Printf.printf "%s\n" (Int64.to_string (loop 0 0 0L))

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

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

  let rec loop l r ac =
    let r = max r (l+1) in
      if r=n then ac else (
	if x.(r) - x.(l) > d then loop (l+1) r ac else (
	  if r=n-1 || x.(r+1) > x.(l) + d  then (
	      let ac = ac + ((r-l) * (r-l-1)) / 2 in
		loop (l+1) r ac
	  ) else (
	    loop l (r+1) ac
	  )
	)
      )
  in

    Printf.printf "%d\n" (loop 0 0 0)


Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length.

The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white.

Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1.

NoteIn the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black.

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 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 rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)
let sum i j f = fold i j (fun i a -> (f i) + a) 0

let read_pair _ = bscanf Scanning.stdib " %d %d " (fun x y -> (x,y))
let read_string _ = bscanf Scanning.stdib " %s " (fun x -> x)

let () =
  let (n,m) = read_pair () in
  let board = Array.init n read_string in

  if forall 0 (n-1) (fun r -> forall 0 (m-1) (fun c -> board.(r).[c] = 'W')) then (
    printf "1\n"
  ) else (
    let r1 = ref (n-1) in
    let r2 = ref 0 in
    let c1 = ref (m-1) in
    let c2 = ref 0 in
    for r=0 to n-1 do
      for c=0 to m-1 do
	if board.(r).[c] = 'B' then (
	  r1 := min !r1 r;
	  r2 := max !r1 r;
	  c1 := min !c1 c;
	  c2 := max !c2 c
	)
      done
    done;

    let dx = !c2 - !c1 + 1 in
    let dy = !r2 - !r1 + 1 in

    let side = max dx dy in

    if side > (min n m) then printf "-1\n" else (
      let nblacks = sum !r1 !r2 (fun r -> sum !c1 !c2 (fun c ->
	if board.(r).[c] = 'B' then 1 else 0
      )) in
      printf "%d\n" (side * side - nblacks)
    )
  )


You are given an integer $$$n$$$. In one move, you can either multiply $$$n$$$ by two or divide $$$n$$$ by $$$6$$$ (if it is divisible by $$$6$$$ without the remainder).Your task is to find the minimum number of moves needed to obtain $$$1$$$ from $$$n$$$ or determine if it's impossible to do that.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow.  The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

For each test case, print the answer — the minimum number of moves needed to obtain $$$1$$$ from $$$n$$$ if it's possible to do that or -1 if it's impossible to obtain $$$1$$$ from $$$n$$$.

NoteConsider the sixth test case of the example. The answer can be obtained by the following sequence of moves from the given integer $$$15116544$$$:  Divide by $$$6$$$ and get $$$2519424$$$;  divide by $$$6$$$ and get $$$419904$$$;  divide by $$$6$$$ and get $$$69984$$$;  divide by $$$6$$$ and get $$$11664$$$;  multiply by $$$2$$$ and get $$$23328$$$;  divide by $$$6$$$ and get $$$3888$$$;  divide by $$$6$$$ and get $$$648$$$;  divide by $$$6$$$ and get $$$108$$$;  multiply by $$$2$$$ and get $$$216$$$;  divide by $$$6$$$ and get $$$36$$$;  divide by $$$6$$$ and get $$$6$$$;  divide by $$$6$$$ and get $$$1$$$.

let divBy3 x =
  let rec loop acc x' =
    if x' <= 1 then Some acc
    else if (x' mod 3) = 0 then loop (acc + 1) (x' / 3)
    else None
  in loop 0 x

let divBy6 x =
  let rec loop acc x' =
    if (x' mod 6) = 0 then loop (acc + 1) (x' / 6) else acc
  in loop 0 x

let rec without6 x =
  if (x mod 6) = 0 then without6 (x / 6) else x

let solveFor x =
  match divBy3 (without6 x) with
  | None -> -1
  | Some x' -> (divBy6 x) + (x' * 2)

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

let () =
  for i = 1 to (read_int ()) do
    read_int ()
    |> solveFor
    |> Printf.printf "%d\n"
  done

open Printf

let rec divide a b c = if a mod b = 0 then divide (a / b) b (c + 1) else (a,c)

let main =
    let n = read_int() in
    for i = 1 to n do
        let x = read_int() in
        let (y,n2) = divide x 2 0 in
        let (z,n3) = divide y 3 0 in
        if z <> 1 || n2 > n3 then
            printf "-1\n"
        else
            printf "%d\n" (2 * n3 - n2)
    done


The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).

The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.

Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).

NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.

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

let () =
  let n = read_int() in
  let m = read_int() in

  let s = Array.make n (-1) in  (* the sets *)
  let rec find i = if s.(i) < 0 then i else
    let r = find s.(i) in
      s.(i) <- r;
      r
  in

  let union i j = (* union the two sets together, and return 1 if something happened 0 otherwise *)
    let (i,j) = ((find i), (find j)) in
      if i <> j then (
	s.(i) <- j;
	1
      ) else 0
  in

  let lange = Array.make m [] in

  let all_zero = ref true in

    for i=0 to n-1 do
      let numlang = read_int() in
	all_zero := (numlang = 0) && !all_zero;
	for j=0 to numlang-1 do
	  let lang = (read_int()) -1 in
	    lange.(lang) <- i::(lange.(lang))
	done
    done;

    let unioncount = ref 0 in

      for l=0 to m-1 do
	let rec loop e llist ucount = match llist with [] -> ucount
	  | f::llist -> loop e llist (ucount + (union e f))
	in
	  if lange.(l) <> [] then
	    let e = List.hd lange.(l) in
	    let rest = List.tl lange.(l) in
	      unioncount := !unioncount + (loop e rest 0)
      done;

      let components = n - !unioncount in

       (* take care of the special case when all employees no zero languages *)

      let answer = components -1 + (if !all_zero then 1 else 0) in

	Printf.printf "%d\n" answer


Polycarp has $$$x$$$ of red and $$$y$$$ of blue candies. Using them, he wants to make gift sets. Each gift set contains either $$$a$$$ red candies and $$$b$$$ blue candies, or $$$a$$$ blue candies and $$$b$$$ red candies. Any candy can belong to at most one gift set.Help Polycarp to find the largest number of gift sets he can create.For example, if $$$x = 10$$$, $$$y = 12$$$, $$$a = 5$$$, and $$$b = 2$$$, then Polycarp can make three gift sets:   In the first set there will be $$$5$$$ red candies and $$$2$$$ blue candies;  In the second set there will be $$$5$$$ blue candies and $$$2$$$ red candies;  In the third set will be $$$5$$$ blue candies and $$$2$$$ red candies. Note that in this example there is one red candy that Polycarp does not use in any gift set.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case consists of a single string containing four integers $$$x$$$, $$$y$$$, $$$a$$$, and $$$b$$$ ($$$1 \le x, y, a, b \le 10^9$$$).

For each test case, output one number — the maximum number of gift sets that Polycarp can make.

(* 7:31 *)

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 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 read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))

let sort (a,b) = if a < b then (a,b) else (b,a)

let () =
  let cases = read_int() in
  for case = 1 to cases do
    let (x,y) = sort (read_pair ()) in
    let (a,b) = sort (read_pair ()) in
    if a = b then (
      let m = min (x/a) (y/b) in
      printf "%d\n" m
    ) else (
      let delxy = y-x in
      let delab = b-a in
      let z = delxy/delab in
    (* if we go beyond this many moves x becomes less than y *)
      let m = min (x/a) (y/b) in
    (* maximum number where we remove (a,b) from (x,y) *)
      let m = min m z in
      let (x,y) = sort (x - m*a, y-m*b) in
      let w = if a+b < 0 then 0 else x/(a+b) in (* overflow fix *)
      let (x,y) = sort (x-w*(a+b), y-w*(a+b)) in
      let v = if x >= a && y >= b then 1 else 0 in
      printf "%d\n" (m + 2*w + v)
    )
  done

(* 7:31 *)

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 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 read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))

let sort (a,b) = if a < b then (a,b) else (b,a)

let () =
  let cases = read_int() in
  for case = 1 to cases do
    let (x,y) = sort (read_pair ()) in
    let (a,b) = sort (read_pair ()) in
    if a = b then (
      let m = min (x/a) (y/b) in
      printf "%d\n" m
    ) else (
      let delxy = y-x in
      let delab = b-a in
      let z = delxy/delab in
    (* if we go beyond this many moves x becomes less than y *)
      let m = min (x/a) (y/b) in
    (* maximum number where we remove (a,b) from (x,y) *)
      let m = min m z in
      let (x,y) = sort (x - m*a, y-m*b) in
      let w = x/(a+b) in
      let (x,y) = sort (x-w*(a+b), y-w*(a+b)) in
      let v = if x >= a && y >= b then 1 else 0 in
      printf "%d\n" (m + 2*w + v)
    )
  done


Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from ai to bi. Of course, Famil Door wants to have as many friends celebrating together with him as possible.Far cars are as weird as Far Far Away citizens, so they can only carry two people of opposite gender, that is exactly one male and one female. However, Far is so far from here that no other transportation may be used to get to the party.Famil Door should select some day of the year and invite some of his friends, such that they all are available at this moment and the number of male friends invited is equal to the number of female friends invited. Find the maximum number of friends that may present at the party.

The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — then number of Famil Door's friends. Then follow n lines, that describe the friends. Each line starts with a capital letter 'F' for female friends and with a capital letter 'M' for male friends. Then follow two integers ai and bi (1 ≤ ai ≤ bi ≤ 366), providing that the i-th friend can come to the party from day ai to day bi inclusive.

Print the maximum number of people that may come to Famil Door's party.

NoteIn the first sample, friends 3 and 4 can come on any day in range [117, 128].In the second sample, friends with indices 3, 4, 5 and 6 can come on day 140.

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 d = 366 in
  let deltaf = Array.make (d+1) 0 in
  let deltam = Array.make (d+1) 0 in

  for i=0 to n-1 do
    let darray = if read_string () = "M" then deltam else deltaf in
    let st = -1 + read_int() in
    let ed = -1 + read_int() in
    darray.(st) <- darray.(st) + 1;
    darray.(ed+1) <- darray.(ed+1) - 1;
  done;

  let rec loop i nmale nfemale best =
    let nmale = deltam.(i) + nmale in
    let nfemale = deltaf.(i) + nfemale in
    let best = max best (2 * (min nmale nfemale)) in
    if i = d then best else loop (i+1) nmale nfemale best
  in

  printf "%d\n" (loop 0 0 0 0)


There is little time left before the release of the first national operating system BerlOS. Some of its components are not finished yet — the memory manager is among them. According to the developers' plan, in the first release the memory manager will be very simple and rectilinear. It will support three operations:   alloc n — to allocate n bytes of the memory and return the allocated block's identifier x;  erase x — to erase the block with the identifier x;  defragment — to defragment the free memory, bringing all the blocks as close to the beginning of the memory as possible and preserving their respective order; The memory model in this case is very simple. It is a sequence of m bytes, numbered for convenience from the first to the m-th.The first operation alloc n takes as the only parameter the size of the memory block that is to be allocated. While processing this operation, a free block of n successive bytes is being allocated in the memory. If the amount of such blocks is more than one, the block closest to the beginning of the memory (i.e. to the first byte) is prefered. All these bytes are marked as not free, and the memory manager returns a 32-bit integer numerical token that is the identifier of this block. If it is impossible to allocate a free block of this size, the function returns NULL.The second operation erase x takes as its parameter the identifier of some block. This operation frees the system memory, marking the bytes of this block as free for further use. In the case when this identifier does not point to the previously allocated block, which has not been erased yet, the function returns ILLEGAL_ERASE_ARGUMENT.The last operation defragment does not have any arguments and simply brings the occupied memory sections closer to the beginning of the memory without changing their respective order.In the current implementation you are to use successive integers, starting with 1, as identifiers. Each successful alloc operation procession should return following number. Unsuccessful alloc operations do not affect numeration.You are to write the implementation of the memory manager. You should output the returned value for each alloc command. You should also output ILLEGAL_ERASE_ARGUMENT for all the failed erase commands.

The first line of the input data contains two positive integers t and m (1 ≤ t ≤ 100;1 ≤ m ≤ 100), where t — the amount of operations given to the memory manager for processing, and m — the available memory size in bytes. Then there follow t lines where the operations themselves are given. The first operation is alloc n (1 ≤ n ≤ 100), where n is an integer. The second one is erase x, where x is an arbitrary 32-bit integer numerical token. The third operation is defragment.

Output the sequence of lines. Each line should contain either the result of alloc operation procession , or ILLEGAL_ERASE_ARGUMENT as a result of failed erase operation procession. Output lines should go in the same order in which the operations are processed. Successful procession of alloc operation should return integers, starting with 1, as the identifiers of the allocated blocks.

6 10
alloc 5
alloc 3
erase 1
alloc 6
defragment
alloc 6

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

open Int32

let () =
  let m = read_int 0 in
  let n = read_int 0 in
  let allo = ref 0l
  and a = Array.make n (0l,0) in
  for cc = 1 to m do
    let op = read_str 0 in
    match op.[0] with
    | 'a' ->
      let v = read_int 0 in
      let rec go i c =
        if c >= v then
          i-v
        else if i >= n then
          -1
        else
          go (i+1) (if fst a.(i) = 0l then c+1 else 1-snd a.(i))
      in
      let r = go 0 0 in
      if r < 0 then
        print_endline "NULL"
      else (
        allo := add !allo 1l;
        a.(r) <- !allo, v;
        Printf.printf "%ld\n" !allo;
      )
    | 'e' ->
      let v = read_int32 0 in
      let rec go i =
        if i >= n then
          -1
        else if fst a.(i) = v then
          i
        else
          go (i+1)
      in
      let r = go 0 in
      if v <= 0l || r < 0 then
        print_endline "ILLEGAL_ERASE_ARGUMENT"
      else
        a.(r) <- 0l, 0
    | 'd' ->
      let rec go i j =
        if i < n then
          if fst a.(i) = 0l then
            go (i+1) j
          else (
            a.(j) <- a.(i);
            for jj = j+1 to j+snd a.(j)-1 do
              a.(jj) <- 0l, 0
            done;
            go (i+1) (j+snd a.(j))
          )
        else if j < n then (
          a.(j) <- 0l, 0;
          go n (j+1)
        )
      in
      go 0 0
  done

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

open Int32

let () =
  let m = read_int 0 in
  let n = read_int 0 in
  let allo = ref 0l
  and a = Array.make n (0l,0) in
  for cc = 1 to m do
    let op = read_str 0 in
    match op.[0] with
    | 'a' ->
      let v = read_int 0 in
      let rec go i c =
        if c >= v then
          i-v
        else if i >= n then
          -1
        else
          go (i+1) (if fst a.(i) = 0l then c+1 else 1-snd a.(i))
      in
      let r = go 0 0 in
      if r < 0 then
        print_endline "NULL"
      else (
        allo := add !allo 1l;
        a.(r) <- !allo, v;
        Printf.printf "%ld\n" !allo;
      )
    | 'e' ->
      let v = read_int32 0 in
      let rec go i =
        if i >= n then
          -1
        else if fst a.(i) = v then
          i
        else
          go (i+1)
      in
      let r = go 0 in
      if r < 0 then
        print_endline "ILLEGAL_ERASE_ARGUMENT"
      else
        a.(r) <- 0l, 0
    | 'd' ->
      let rec go i j =
        if i < n then
          if fst a.(i) = 0l then
            go (i+1) j
          else (
            a.(j) <- a.(i);
            for jj = j+1 to j+snd a.(i)-1 do
              a.(jj) <- 0l, 0
            done;
            go (i+1) (j+snd a.(i))
          )
        else if j < n then (
          a.(j) <- 0l, 0;
          go n (j+1)
        )
      in
      go 0 0
  done

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

open Int32

let () =
  let m = read_int 0 in
  let n = read_int 0 in
  let allo = ref 0l
  and a = Array.make n (0l,0) in
  for cc = 1 to m do
    let op = read_str 0 in
    match op.[0] with
    | 'a' ->
      let v = read_int 0 in
      let rec go i c =
        if c >= v then
          i-v
        else if i >= n then
          -1
        else
          go (i+1) (if fst a.(i) = 0l then c+1 else 1-snd a.(i))
      in
      let r = go 0 0 in
      if r < 0 then
        print_endline "NULL"
      else (
        allo := add !allo 1l;
        a.(r) <- !allo, v;
        Printf.printf "%ld\n" !allo;
      )
    | 'e' ->
      let v = read_int32 0 in
      let rec go i =
        if i >= n then
          -1
        else if fst a.(i) = v then
          i
        else
          go (i+1)
      in
      let r = go 0 in
      if r < 0 then
        print_endline "ILLEGAL_ERASE_ARGUMENT"
      else
        a.(r) <- 0l, 0
    | 'd' ->
      let rec go i j =
        if i < n then
          if fst a.(i) = 0l then
            go (i+1) j
          else (
            a.(j) <- a.(i);
            for jj = j+1 to j+snd a.(i)-1 do
              a.(j) <- 0l, 0
            done;
            go (i+1) (j+snd a.(i))
          )
        else if j < n then (
          a.(j) <- 0l, 0;
          go n (j+1)
        )
      in
      go 0 0
  done

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

open Int32

let () =
  let m = read_int 0 in
  let n = read_int 0 in
  let allo = ref 0l
  and a = Array.make n (0l,0) in
  for cc = 1 to m do
    let op = read_str 0 in
    match op.[0] with
    | 'a' ->
      let v = read_int 0 in
      let rec go i c =
        if c >= v then
          i-v
        else if i >= n then
          -1
        else
          go (i+1) (if fst a.(i) = 0l then c+1 else 1-snd a.(i))
      in
      let r = go 0 0 in
      if r < 0 then
        print_endline "NULL"
      else (
        allo := add !allo 1l;
        a.(r) <- !allo, v;
        Printf.printf "%ld\n" !allo;
      )
    | 'e' ->
      let v = read_int32 0 in
      let rec go i =
        if i >= n then
          -1
        else if fst a.(i) = v then
          i
        else
          go (i+1)
      in
      let r = go 0 in
      if r < 0 then
        print_endline "ILLEGAL_ERASE_ARGUMENT"
      else
        a.(r) <- 0l, 0
    | 'd' ->
      let rec go i j =
        if i < n then
          if fst a.(i) = 0l then
            go (i+1) j
          else (
            a.(j) <- a.(i);
            for jj = j+1 to j+snd a.(j)-1 do
              a.(jj) <- 0l, 0
            done;
            go (i+1) (j+snd a.(j))
          )
        else if j < n then (
          a.(j) <- 0l, 0;
          go n (j+1)
        )
      in
      go 0 0
  done


Genos needs your help. He was asked to solve the following programming problem by Saitama:The length of some string s is denoted |s|. The Hamming distance between two strings s and t of equal length is defined as , where si is the i-th character of s and ti is the i-th character of t. For example, the Hamming distance between string "0011" and string "0110" is |0 - 0| + |0 - 1| + |1 - 1| + |1 - 0| = 0 + 1 + 0 + 1 = 2.Given two binary strings a and b, find the sum of the Hamming distances between a and all contiguous substrings of b of length |a|.

The first line of the input contains binary string a (1 ≤ |a| ≤ 200 000). The second line of the input contains binary string b (|a| ≤ |b| ≤ 200 000). Both strings are guaranteed to consist of characters '0' and '1' only.

Print a single integer — the sum of Hamming distances between a and all contiguous substrings of b of length |a|.

NoteFor the first sample case, there are four contiguous substrings of b of length |a|: "00", "01", "11", and "11". The distance between "01" and "00" is |0 - 0| + |1 - 0| = 1. The distance between "01" and "01" is |0 - 0| + |1 - 1| = 0. The distance between "01" and "11" is |0 - 1| + |1 - 1| = 1. Last distance counts twice, as there are two occurrences of string "11". The sum of these edit distances is 1 + 0 + 1 + 1 = 3.The second sample case is described in the statement.

let v s i = int_of_char( s.[i] ) - 48 ;;
let a, b = Scanf.scanf "%s %s" (fun a b -> (a,b)) ;;

let rec bsum = function
    | 0 -> 0
    | i -> (v b (i-1) ) + bsum (i-1)
;;
let cmplen = String.length b - String.length a ;;
let (+^), to64 = Int64.(add, of_int) ;;
let rec f i cs =
    if i = String.length a
    then 0L
    else let cs2 = cs + v b (cmplen+i) in
        to64 (if v a i = 0 then cs2 else cmplen+1-cs2)
      +^ f (i+1) (cs2 - v b i)
;;
Printf.printf "%Ld" (f 0 (bsum cmplen))

open Printf
open Scanf

let ( ++ ) a b = Int64.add a b
let long x = Int64.of_int x
let rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i))

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

let () =
  let a = read_string () in
  let b = read_string () in

  let n = String.length a in
  let m = String.length b in

  let a = Array.init n (fun i -> if a.[i] = '1' then 1 else 0) in
  let b = Array.init m (fun i -> if b.[i] = '1' then 1 else 0) in

  let sigma = Array.make (m+1) 0 in

  for i=1 to m do
    sigma.(i) <- sigma.(i-1) + b.(i-1)
  done;

  (* sigma.(x) = sum of b's from b.(0) to b.(x-1) *)

  let sum_range i j = sigma.(j+1) - sigma.(i) in

  let answer = sum 0 (n-1) (fun i ->
    let first = i in
    let last = m-n+i in
    let nones = sum_range first last in
    long (if a.(i) = 1 then (last-first+1) - nones else nones)
  ) 0L in

  printf "%Ld\n" answer

let v s i = int_of_char( s.[i] ) - 48 ;;
let a, b = Scanf.scanf "%s %s" (fun a b -> (a,b)) ;;

let rec bsum = function
    | 0 -> 0
    | i -> (v b (i-1) ) + bsum (i-1)
;;
let cmplen = String.length b - String.length a ;;

let rec f i cs =
    if i = String.length a
    then 0
    else let cs2 = cs + v b (cmplen+i) in
        (if v a i = 0 then cs2 else cmplen+1-cs2)
      + f (i+1) (cs2 - v b i)
;;
print_int @@ f 0 (bsum cmplen)


Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same.Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible.

The first line contains an integer N (1 ≤ N ≤ 1000) — the number of bars at Vasya’s disposal. The second line contains N space-separated integers li — the lengths of the bars. All the lengths are natural numbers not exceeding 1000.

In one line output two numbers — the height of the largest tower and their total number. Remember that Vasya should use all the bars.

module Int = struct
	let compare = compare
	type t = int
end;;

module IntMap = Map.Make(Int);;

let rec solve i bruski =
	if i = 0 then (
		let l = IntMap.fold (fun _ _ l -> l + 1) bruski 0 in
		let max = IntMap.fold (fun _ h m -> max h m) bruski 0 in
		Printf.printf "%d %d" max l
	) else (
		let w = Scanf.scanf " %d" (fun i->i) in
		let nbruski = IntMap.add w ((if IntMap.mem w bruski
			then IntMap.find w bruski else 0) + 1) bruski in
		solve (i-1) nbruski
	)
;;

let () =
	solve (read_int()) IntMap.empty
;;

open Scanf;;
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 maxN = 1007;;
let tab = Array.make maxN 0;;

for i = 1 to n do
  let x = scan_int() in
  tab.(x) <- (tab.(x) + 1);
done;;

let cnt = ref 0 and maxik = ref 0;;
for i = 1 to (maxN - 1) do
  cnt := (!cnt + b2i(tab.(i) > 0));
  maxik := max (!maxik) tab.(i);
done;;

print_int !maxik; psp(); print_int !cnt;


There are n stone quarries in Petrograd.Each quarry owns mi dumpers (1 ≤ i ≤ n). It is known that the first dumper of the i-th quarry has xi stones in it, the second dumper has xi + 1 stones in it, the third has xi + 2, and the mi-th dumper (the last for the i-th quarry) has xi + mi - 1 stones in it.Two oligarchs play a well-known game Nim. Players take turns removing stones from dumpers. On each turn, a player can select any dumper and remove any non-zero amount of stones from it. The player who cannot take a stone loses.Your task is to find out which oligarch will win, provided that both of them play optimally. The oligarchs asked you not to reveal their names. So, let's call the one who takes the first stone «tolik» and the other one «bolik».

The first line of the input contains one integer number n (1 ≤ n ≤ 105) — the amount of quarries. Then there follow n lines, each of them contains two space-separated integers xi and mi (1 ≤ xi, mi ≤ 1016) — the amount of stones in the first dumper of the i-th quarry and the number of dumpers at the i-th quarry.

Output «tolik» if the oligarch who takes a stone first wins, and «bolik» otherwise.

let [zer;on;two;fou] = List.map Big_int.big_int_of_int [0;1;2;4]

let (+) = Big_int.add_big_int
let (-) = Big_int.sub_big_int
let ( * ) = Big_int.mult_big_int
let (mod) = Big_int.mod_big_int
let (=) = Big_int.eq_big_int
let (<=) a b = Big_int.compare_big_int a b <= 0

let xor_betw a b =
    let x = ref (a * (a mod two)) in
    let beg = ref (b + (a mod two) - ((b-a) mod fou)) in
        while !beg <= b do
            x := Big_int.xor_big_int !beg !x;
            beg := !beg + on;
        done;
        !x

let main () =
    let n = Scanf.scanf "%d" (fun i -> i) and a = ref zer in
    for i = 1 to n do
        Scanf.scanf " %s %s" (fun x' m' ->
            let [x;m] = List.map Big_int.big_int_of_string [x';m'] in
                a := Big_int.xor_big_int !a (xor_betw x (x+m-on)));
    done;
    print_endline (if !a = zer then "bolik" else "tolik");;

main ();;

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

open Int64

let () =
  let z = ref 0L in
  for i = 1 to read_int 0 do
    let x = read_int64 0 |> ref in
    let y = read_int64 0 |> ref in
    y := add !y !x;
    while !x < !y && rem !x 4L <> 0L do
      z := logxor !z !x;
      x := add !x 1L
    done;
    while !x < !y && rem !y 4L <> 0L do
      y := sub !y 1L;
      z := logxor !z !y
    done
  done;
  print_endline (if !z <> 0L then "tolik" else "bolik")

let xor_betw a b =
    let x = ref 0 in
        if a mod 2 = 1 then x := a;
        for i = b + 1 - ((b-a) mod 4) to b do
            x := i lxor !x;
        done;
        !x

let main () =
    let n = Scanf.scanf "%d" (fun i -> i) and a = ref 0 in
    for i = 1 to n do
        Scanf.scanf " %d %d" (fun x m->a := !a lxor (xor_betw x (x+m-1)));
    done;
    print_endline (if !a = 0 then "bolik" else "tolik");;

main ();;

let n = Scanf.scanf "%d" (fun i -> i) and res = ref 0 in
    for i=1 to n-1 do
        Scanf.scanf " %s"
        (fun w -> res := !res + int_of_char (w.[String.length w - 1]));
    done;
Printf.printf (if !res mod 2 = 0 then "bolik" else "tolik");;

let n = Scanf.scanf "%d" (fun i -> i) and res = ref 0 in
    for i=1 to n do
        Scanf.scanf " %s %s"
        (fun _ w -> res := !res + int_of_char (w.[String.length w - 1]));
    done;
Printf.printf (if !res mod 2 = 0 then "bolik" else "tolik");;

let n = Scanf.scanf "%d" (fun i -> i) and res = ref 0 in
    for i=1 to n do
        Scanf.scanf " %s"
        (fun w -> res := !res + int_of_char (w.[String.length w - 1]));
    done;
Printf.printf (if !res mod 2 = 0 then "bolik" else "tolik");;

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

let () =
  let z = ref 0 in
  for i = 1 to read_int 0 do
    let x = read_int 0 |> ref in
    let y = read_int 0 |> ref in
    y := !y + !x;
    while !x < !y && !x mod 4 <> 0 do
      z := !z + !x;
      incr x
    done;
    while !x < !y && !y mod 4 <> 0 do
      decr y;
      z := !z + !y
    done
  done;
  print_endline (if !z <> 0 then "tolik" else "bolik")


While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly $$$H$$$ centimeters above the water surface. Inessa grabbed the flower and sailed the distance of $$$L$$$ centimeters. Exactly at this point the flower touched the water surface.  Suppose that the lily grows at some point $$$A$$$ on the lake bottom, and its stem is always a straight segment with one endpoint at point $$$A$$$. Also suppose that initially the flower was exactly above the point $$$A$$$, i.e. its stem was vertical. Can you determine the depth of the lake at point $$$A$$$?

The only line contains two integers $$$H$$$ and $$$L$$$ ($$$1 \le H < L \le 10^{6}$$$).

Print a single number — the depth of the lake at point $$$A$$$. The absolute or relative error should not exceed $$$10^{-6}$$$. Formally, let your answer be $$$A$$$, and the jury's answer be $$$B$$$. Your answer is accepted if and only if $$$\frac{|A - B|}{\max{(1, |B|)}} \le 10^{-6}$$$.

open Scanf
open Printf

let solve h l =
  (l ** 2. -. h ** 2.) /. (2. *. h)

let main () =
  let (h, l) = scanf " %f %f" (fun h l -> (h, l)) in
  printf "%f\n" (solve h l)

let () = main ()


Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 109, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.

The first line contains a single integer n (1 ≤ n ≤ 105), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 109, inclusive.

Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.

(*************** Ocaml stdio functions **********************)
let stdin_stream = Stream.of_channel stdin;;
let stdout_buffer = Buffer.create 65536;;
let rec gi() =
  match Stream.next stdin_stream with
    '-' ->  - (ri 0)
  | '+' ->  ri 0
  | '0'..'9' as c -> ri ((int_of_char c) - 48)
  | _ -> gi ()
and ri x =
  match Stream.next stdin_stream with
    '0'..'9' as c -> ri (((int_of_char c) - 48) + (x * 10))
  | _ -> x
;;
let flushout () = Buffer.output_buffer stdout stdout_buffer; Buffer.reset stdout_buffer;;
let putchar c =
  if (Buffer.length stdout_buffer) >= 65536 then flushout() else ();
  Buffer.add_char stdout_buffer c;;
let rec ppi i = if i < 10 then putchar (char_of_int (48 + i)) else (ppi (i / 10); putchar (char_of_int (48 + (i mod 10)))) ;;
let pi i = if i >= 0 then ppi i else (putchar ('-'); ppi (-i));;
let pa a = let n = Array.length a in Array.iteri (fun i j -> pi j; putchar (if i == (n-1) then '\n' else ' ')) a;;
(*************** Ocaml solution ******************************)
open Array
let main() =
  let n = gi() in
  let a = init (n+1) (fun i -> if i > 0 then gi() else 1) in
  stable_sort compare a;
  if a.(n) == 1 then a.(n-1) <- 2 else ();
  pa (sub a 0 n)
  ;;
main();;
flushout ()

open Array
open Scanf
let main() =
  let s = stable_sort (-) in
  let gi() = bscanf Scanning.stdib " %d" (fun x -> x) in
  let n = gi () in
  let a = init n (fun i -> gi ()) in
  s a;
  a.(n-1) <- if fold_left (&&) true (map ((==) 1) a) then 2 else 1;
  s a;
  iter (Printf.printf "%d ") a
  ;;
main()

(*************** Ocaml stdio functions **********************)
let stdin_stream = Stream.of_channel stdin;;
let stdout_buffer = Buffer.create 65536;;
let rec gi() =
  match Stream.next stdin_stream with
    '-' ->  - (ri 0)
  | '+' ->  ri 0
  | '0'..'9' as c -> ri ((int_of_char c) - 48)
  | _ -> gi ()
and ri x =
  match Stream.next stdin_stream with
    '0'..'9' as c -> ri (((int_of_char c) - 48) + (x * 10))
  | _ -> x
;;
let flushout () = Buffer.output_buffer stdout stdout_buffer; Buffer.reset stdout_buffer;;
let putchar c =
  if (Buffer.length stdout_buffer) >= 65536 then flushout() else ();
  Buffer.add_char stdout_buffer c;;
let rec ppi i = if i < 10 then putchar (char_of_int (48 + i)) else (ppi (i / 10); putchar (char_of_int (48 + (i mod 10)))) ;;
let pi i = if i >= 0 then ppi i else (putchar ('-'); ppi (-i));;
(*************** Ocaml solution ******************************)
open Array
let main() =
  let n = gi() in
  let a = init (n+1) (fun i -> if i > 0 then gi() else 1) in
  stable_sort compare a;
  if a.(n) == 1 then a.(n-1) <- 2 else ();
  iteri (fun i j -> pi j; putchar (if i == (n-1) then '\n' else ' ')) (sub a 0 n)
  ;;
main();;
flushout ()

open Array
let main() =
  let s = stable_sort (-) in
  let gi() = Scanf.scanf " %d" (fun i -> i) in
  let n = gi () in
  let a = init n (fun i -> gi ()) in
  s a;
  a.(n-1) <- if fold_left (&&) true (map ((==) 1) a) then 2 else 1;
  s a;
  iter (Printf.printf "%d ") a
  ;;
main()

    let _ =
      let sb = Scanf.Scanning.stdib in
      let n = Scanf.bscanf sb "%d " (fun s -> s) in
      let a = Array.make n 0 in
        for i = 0 to n - 1 do
          let k = Scanf.bscanf sb "%d " (fun s -> s) in
            a.(i) <- k
        done;
        Array.sort compare a;
        a.(n - 1) <-
          if a.(n - 1) > 1
          then 1
          else 2;
        Array.sort compare a;
        for i = 0 to n - 1 do
          Printf.printf "%d " a.(i);
        done;
        Printf.printf "\n"

let getnum =
  let l = 512000 in
  let buf = String.make l ' ' in
  let s = ref 0 in
  let pos = ref 0 in
  let getc () =
    if !pos >= !s then (
      let new_s = input stdin buf 0 l in
	(*if new_s = 0 then raise End_of_file;*)
	s := new_s;
	if new_s = 0 then (
	  buf.[0] <- '\000';
	  s := 1;
	);
	pos := 0;
    );
    let c = buf.[!pos] in
      incr pos;
      c
  in
  let aux () =
    let n = ref 0 in
    let k = ref 1 in
      if !s - !pos < 50 then (
	let c = ref (getc ()) in
	  while !c <= ' ' do
	    c := getc ()
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := getc ();
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := getc ()
	  done;
	  !n * !k
      ) else (
	let c = ref (buf.[!pos]) in
	  incr pos;
	  while !c <= ' ' do
	    c := buf.[!pos];
	    incr pos;
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := buf.[!pos];
	    incr pos;
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := buf.[!pos];
	    incr pos;
	  done;
	  !n * !k
      )
  in
    aux

let _ =
  let n = getnum () in
  let a = Array.make n 0 in
    for i = 0 to n - 1 do
      let k = getnum () in
	a.(i) <- k
    done;
    Array.sort compare a;
    a.(n - 1) <-
      if a.(n - 1) > 1
      then 1
      else 2;
    Array.sort compare a;
    for i = 0 to n - 1 do
      Printf.printf "%d " a.(i);
    done;
    Printf.printf "\n"

try (
  let a = Array.make 1 1 in
  Printf.printf "1 1 2 3 ";
  a.(10) <- 4;
  Printf.printf "%d\n" (a.(10))
  )
with
_ -> exit 1

open Sys
let rec pa = function
    [] -> ()
  | (x::xs) -> (Printf.printf "%s\n" x; pa xs)
  ;;
Printf.printf "word_size = %d\n" word_size;;
Printf.printf "max_string_length = %d\n" max_string_length;;
Printf.printf "max_array_length = %d\n" max_array_length;;
Printf.printf "os_type = %s\n" os_type;;
Printf.printf "ocaml_version = %s\n" ocaml_version

Printf.printf "%s\n" (Str.quote "abacaba")

let a = Array.make 1 1;;
Printf.printf "1 1 2 3 ";;
a.(10) <- 4;;
Printf.printf "%d\n" (a.(10))


One day Natalia was walking in the woods when she met a little mushroom gnome. The gnome told her the following story:Everybody knows that the mushroom gnomes' power lies in the magic mushrooms that grow in the native woods of the gnomes. There are n trees and m magic mushrooms in the woods: the i-th tree grows at a point on a straight line with coordinates ai and has the height of hi, the j-th mushroom grows at the point with coordinates bj and has magical powers zj.But one day wild mushroommunchers, the sworn enemies of mushroom gnomes unleashed a terrible storm on their home forest. As a result, some of the trees began to fall and crush the magic mushrooms. The supreme oracle of mushroom gnomes calculated in advance the probability for each tree that it will fall to the left, to the right or will stand on. If the tree with the coordinate x and height h falls to the left, then all the mushrooms that belong to the right-open interval [x - h, x), are destroyed. If a tree falls to the right, then the mushrooms that belong to the left-open interval (x, x + h] are destroyed. Only those mushrooms that are not hit by a single tree survive.Knowing that all the trees fall independently of each other (i.e., all the events are mutually independent, and besides, the trees do not interfere with other trees falling in an arbitrary direction), the supreme oracle was also able to quickly calculate what would be the expectation of the total power of the mushrooms which survived after the storm. His calculations ultimately saved the mushroom gnomes from imminent death.Natalia, as a good Olympiad programmer, got interested in this story, and she decided to come up with a way to quickly calculate the expectation of the sum of the surviving mushrooms' power.

The first line contains two integers n and m (1 ≤ n ≤ 105, 1 ≤ m ≤ 104) — the number of trees and mushrooms, respectively. Each of the next n lines contain four integers — ai, hi, li, ri (|ai| ≤ 109, 1 ≤ hi ≤ 109, 0 ≤ li, ri, li + ri ≤ 100) which represent the coordinate of the i-th tree, its height, the percentage of the probabilities that the tree falls to the left and to the right, respectively (the remaining percentage is the probability that the tree will stand on). Each of next m lines contain two integers bj, zj (|bj| ≤ 109, 1 ≤ zj ≤ 103) which represent the coordinate and the magical power of the j-th mushroom, respectively. An arbitrary number of trees and mushrooms can grow in one point.

Print a real number — the expectation of the total magical power of the surviving mushrooms. The result is accepted with relative or absolute accuracy 10 - 4.

NoteIt is believed that the mushroom with the coordinate x belongs to the right-open interval [l, r) if and only if l ≤ x < r. Similarly, the mushroom with the coordinate x belongs to the left-open interval (l, r] if and only if l < x ≤ r.In the first test the mushroom survives with the probability of 50%, depending on where the single tree falls.In the second test the mushroom survives only if neither of the two trees falls on it. It occurs with the probability of 50%  ×  50% = 25%.Pretest №12 is the large test with 105 trees and one mushroom.

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

type event = Mu of int | TS of int | TE of int

let n = read_int()
let m = read_int()

let trees = Array.make n (0,0,0,0)
let mushs = Array.make m (0,0.0)

let events = ref []

let () =
  for i=0 to n-1 do
    let a = read_int() in
    let h = read_int() in
    let left = read_int() in
    let right = read_int() in
      trees.(i) <- (a, h, 100-right, 100-left);
      events := (TS(i))::!events;
      events := (TE(i))::!events;
  done

let () =
  for j=0 to m-1 do
    let b = read_int() in
    let z = read_int() in
      mushs.(j) <- (b,float z);
      events := (Mu(j))::!events
  done

let comp dir e1 e2 =
  let place = function
    | Mu(i) -> fst mushs.(i)
    | TE(i) -> let (a,h,_,_) = trees.(i) in a + dir*h
    | TS(i) -> let (a,_,_,_) = trees.(i) in a
  in
  let (p1, p2) = (place e1, place e2) in
  let c = compare p1 p2 in
    if c<>0 then dir*c else
      match e1 with Mu(_) -> -1 | _ -> (match e2 with Mu(_) -> 1 | _ -> 0)

let rec power a i =
  if i=0 then 1.0
  else let p = power a (i/2) in
    p *. p *. (if i land 1 = 0 then 1.0 else a)

let scan dir pa li =
  let hist = Array.make 101 0 in
  let rec eval i ac =
    if i=101 then ac else eval (i+1) (ac *. (power ((float i) /. 100.0) hist.(i)))
  in
  let percent i = let (_,_,p,q) = trees.(i) in if dir=1 then p else q in
  let update i d = let j = percent i in hist.(j) <- hist.(j) + d in
    List.iter (
      function
	| Mu(j) -> pa.(j) <- eval 0 1.0
	| TS(i) -> update i 1
	| TE(i) -> update i (-1)
    ) li

let plr = Array.make m 0.0
let prl = Array.make m 0.0

let () = scan 1    plr (List.sort (comp    1) !events)
let () = scan (-1) prl (List.sort (comp (-1)) !events)

let rec sum j ac =
  if j=m then ac
  else sum (j+1) (ac +. plr.(j) *. prl.(j) *. (snd mushs.(j)))

let () = Printf.printf "%f" (sum 0 0.0)

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

type event = Mu of int | TS of int | TE of int

let n = read_int()
let m = read_int()

let trees = Array.make n (0,0,0.0,0.0)
let mushs = Array.make m (0,0.0)

let events = ref []

let toprob i = (float i) /. 100.0

let () =
  for i=0 to n-1 do
    let a = read_int() in
    let h = read_int() in
    let left = read_int() in
    let right = read_int() in
      trees.(i) <- (a, h, toprob (100-right), toprob (100-left));
      events := (TS(i))::!events;
      events := (TE(i))::!events;
  done

let () =
  for j=0 to m-1 do
    let b = read_int() in
    let z = read_int() in
      mushs.(j) <- (b,float z);
      events := (Mu(j))::!events
  done

let comp dir e1 e2 =
  let place = function
    | Mu(i) -> fst mushs.(i)
    | TE(i) -> let (a,h,_,_) = trees.(i) in a + dir*h
    | TS(i) -> let (a,_,_,_) = trees.(i) in a
  in
  let (p1, p2) = (place e1, place e2) in
  let c = compare p1 p2 in
    if c<>0 then dir*c else
      match e1 with Mu(_) -> -1 | _ -> (match e2 with Mu(_) -> 1 | _ -> 0)

let rec scan dir pa li openp =
  let prob i = let (_,_,p,q) = trees.(i) in if dir=1 then p else q in
    match li with
      | [] -> ()
      | (Mu(j))::tail -> pa.(j) <- openp; scan dir pa tail openp
      | (TS(i))::tail ->                  scan dir pa tail (openp *. (prob i))
      | (TE(i))::tail ->                  scan dir pa tail (openp /. (prob i))

let plr = Array.make m 0.0
let prl = Array.make m 0.0

let () = scan 1    plr (List.sort (comp    1) !events) 1.0
let () = scan (-1) prl (List.sort (comp (-1)) !events) 1.0

let rec sum j ac =
  if j=m then ac
  else sum (j+1) (ac +. plr.(j) *. prl.(j) *. (snd mushs.(j)))

let () = Printf.printf "%f" (sum 0 0.0)

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

type event = Mu of int | TS of int | TE of int

let n = read_int()
let m = read_int()

let trees = Array.make n (0,0,0.0,0.0)
let mushs = Array.make m (0,0)

let events = ref []

let toprob i = (float i) /. 100.0

let () =
  for i=0 to n-1 do
    let a = read_int() in
    let h = read_int() in
    let left = read_int() in
    let right = read_int() in
      trees.(i) <- (a, h, toprob (100-right), toprob (100-left));
      events := (TS(i))::!events;
      events := (TE(i))::!events;
  done

let () =
  for j=0 to m-1 do
    let b = read_int() in
    let z = read_int() in
      mushs.(j) <- (b,z);
      events := (Mu(j))::!events
  done

let place dir e = match e with
  | Mu(i) -> fst mushs.(i)
  | TE(i) -> let (a,h,_,_) = trees.(i) in a + dir*h
  | TS(i) -> let (a,h,_,_) = trees.(i) in a

let comp dir e1 e2 =
  let (p1, p2) = (place dir e1, place dir e2) in
  let c = compare p1 p2 in
    dir * (if c<>0 then c else
	     match e1 with Mu(_) -> -1 | _ -> (match e2 with Mu(_) -> 1 | _ -> 0))

let lprob i = let (_,_,p,_) = trees.(i) in p

let rec scan pa li openp =  match li with
  | [] -> ()
  | (Mu(j))::tail -> pa.(j) <- openp; scan pa tail openp
  | (TS(i))::tail ->                  scan pa tail (openp *. (lprob i))
  | (TE(i))::tail ->                  scan pa tail (openp /. (lprob i))

let plr = Array.make m 0.0
let prl = Array.make m 0.0

let () = scan plr (List.sort (comp 1) !events) 1.0
let () = scan prl (List.sort (comp (-1)) !events) 1.0

let rec sum j ac = if j=m then ac else sum (j+1) (ac +. plr.(j) *. prl.(j))

let () = Printf.printf "%f" (sum 0 0.0)