The main server of Gomble company received a log of one top-secret process, the name of which can't be revealed. The log was written in the following format: «[date:time]: message», where for each «[date:time]» value existed not more than 10 lines. All the files were encoded in a very complicated manner, and only one programmer — Alex — managed to decode them. The code was so complicated that Alex needed four weeks to decode it. Right after the decoding process was finished, all the files were deleted. But after the files deletion, Alex noticed that he saved the recordings in format «[time]: message». So, information about the dates was lost. However, as the lines were added into the log in chronological order, it's not difficult to say if the recordings could appear during one day or not. It is possible also to find the minimum amount of days during which the log was written.So, to make up for his mistake Alex has to find the minimum amount of days covered by the log. Note that Alex doesn't have to find the minimum amount of days between the beginning and the end of the logging, he has to find the minimum amount of dates in which records could be done. (See Sample test 2 for further clarifications).We should remind you that the process made not more than 10 recordings in a minute. Consider that a midnight belongs to coming day.

The first input line contains number n (1 ≤ n ≤ 100). The following n lines contain recordings in format «[time]: message», where time is given in format «hh:mm x.m.». For hh two-digit numbers from 01 to 12 are used, for mm two-digit numbers from 00 to 59 are used, and x is either character «a» or character «p». A message is a non-empty sequence of Latin letters and/or spaces, it doesn't start or end with a space. The length of each message doesn't exceed 20.

Output one number — the minimum amount of days covered by the log.

5
[05:00 a.m.]: Server is started
[05:00 a.m.]: Rescan initialized
[01:13 p.m.]: Request processed
[01:10 p.m.]: Request processed
[11:40 p.m.]: Rescan completed

3
[09:00 a.m.]: User logged in
[08:00 a.m.]: User logged in
[07:00 a.m.]: User logged in

NoteFormally the 12-hour time format is described at:   http://en.wikipedia.org/wiki/12-hour_clock.  The problem authors recommend you to look through these descriptions before you start with the problem.

let (|>) x f = f x
let flip f x y = f y x

let () =
  let re = Str.regexp "^\\[\\([0-9][0-9]\\):\\([0-9][0-9]\\) \\([ap]\\)" in
  let last = ref max_int in
  let cnt = ref 0 in
  let ans = ref 0 in
  for i = 1 to read_int () do
    let s = read_line () in
    Str.string_match re s 0 |> ignore;
    let hh = Str.matched_group 1 s |> int_of_string |> flip (mod) 12 in
    let mm = Str.matched_group 2 s |> int_of_string in
    let pm = if Str.matched_group 3 s = "p" then 12*3600 else 0 in
    let time = hh*60+mm+pm in
    if time = !last then
      incr cnt
    else
      cnt := 1;
    if time < !last || !cnt > 10 then (
      incr ans;
      cnt := 1
    );
    last := time
  done;
  Printf.printf "%d\n" !ans


The evil Bumbershoot corporation produces clones for gruesome experiments in a vast underground lab. On one occasion, the corp cloned a boy Andryusha who was smarter than his comrades. Immediately Andryusha understood that something fishy was going on there. He rallied fellow clones to go on a feud against the evil corp, and they set out to find an exit from the lab. The corp had to reduce to destroy the lab complex.The lab can be pictured as a connected graph with n vertices and m edges. k clones of Andryusha start looking for an exit in some of the vertices. Each clone can traverse any edge once per second. Any number of clones are allowed to be at any vertex simultaneously. Each clone is allowed to stop looking at any time moment, but he must look at his starting vertex at least. The exit can be located at any vertex of the lab, hence each vertex must be visited by at least one clone.Each clone can visit at most  vertices before the lab explodes.Your task is to choose starting vertices and searching routes for the clones. Each route can have at most  vertices.

The first line contains three integers n, m, and k (1 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105, 1 ≤ k ≤ n) — the number of vertices and edges in the lab, and the number of clones. Each of the next m lines contains two integers xi and yi (1 ≤ xi, yi ≤ n) — indices of vertices connected by the respective edge. The graph is allowed to have self-loops and multiple edges. The graph is guaranteed to be connected.

You should print k lines. i-th of these lines must start with an integer ci () — the number of vertices visited by i-th clone, followed by ci integers — indices of vertices visited by this clone in the order of visiting. You have to print each vertex every time it is visited, regardless if it was visited earlier or not. It is guaranteed that a valid answer exists.

NoteIn the first sample case there is only one clone who may visit vertices in order (2, 1, 3), which fits the constraint of 6 vertices per clone.In the second sample case the two clones can visited vertices in order (2, 1, 3) and (4, 1, 5), which fits the constraint of 5 vertices per clone.

open Printf
open Scanf

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

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

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

  let graph = Array.make n [] in

  let add_edge (i,j) =
    graph.(i) <- j::graph.(i);
    graph.(j) <- i::graph.(j)
  in

  for i=1 to m do add_edge (read_pair ()) done;

  let visited = Array.make n false in

  let rec dfs v ac =
    (* only get here if v not yet visited *)
    visited.(v) <- true;
    let ac = v::ac in
    List.fold_left (fun ac w ->
      if visited.(w) then ac else v::(dfs w ac)
    ) ac graph.(v)
  in

  let path = dfs 0 [] in

  (*  List.iter (fun v -> printf "%d " (v+1)) path; *)

  let len = List.length path in

  let path = Array.of_list path in

  let remain = ref len in
  let nblocks = ref 0 in

  let block = (len+k-1) / k in

  for i=0 to len-1 do
    if i mod block = 0 then (
      nblocks := !nblocks +1;
      if i<>0 then print_newline();
      printf "%d " (min block !remain);
      remain := !remain - block
    );
    printf "%d " (path.(i) + 1)
  done;
  print_newline();
  for i=1 to k - !nblocks do  printf "1 1\n" done

open Printf
open Scanf

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

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

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

  let graph = Array.make n [] in

  let add_edge (i,j) =
    graph.(i) <- j::graph.(i);
    graph.(j) <- i::graph.(j)
  in

  for i=1 to m do add_edge (read_pair ()) done;

  let visited = Array.make n false in

  let rec dfs v ac =
    (* only get here if v not yet visited *)
    visited.(v) <- true;
    let ac = v::ac in
    List.fold_left (fun ac w ->
      if visited.(w) then ac else v::(dfs w ac)
    ) ac graph.(v)
  in

  let path = dfs 0 [] in

  (*  List.iter (fun v -> printf "%d " (v+1)) path; *)

  let len = List.length path in

  let path = Array.of_list path in

  let remain = ref len in

  let block = (len+k-1) / k in

  for i=0 to len-1 do
    if i mod block = 0 then (
      if i<>0 then print_newline();
      printf "%d " (min block !remain);
      remain := !remain - block
    );
    printf "%d " (path.(i) + 1)
  done;

  print_newline()


Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn't contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.

The first line contains integer n (1 ≤ n ≤ 105) — the number of trees. Next n lines contain pairs of integers xi, hi (1 ≤ xi, hi ≤ 109) — the coordinate and the height of the і-th tree. The pairs are given in the order of ascending xi. No two trees are located at the point with the same coordinate.

Print a single number — the maximum number of trees that you can cut down by the given rules.

NoteIn the first sample you can fell the trees like that:   fell the 1-st tree to the left — now it occupies segment [ - 1;1]  fell the 2-nd tree to the right — now it occupies segment [2;3]  leave the 3-rd tree — it occupies point 5  leave the 4-th tree — it occupies point 10  fell the 5-th tree to the right — now it occupies segment [19;20] In the second sample you can also fell 4-th tree to the right, after that it will occupy segment [10;19].

open Num

let ni = num_of_int

let solve l =
  let update (total_fall, left_fall, left_pos, left_high) (pos, high) =
    if left_fall
    then
      begin
        (* Printf.printf
           "true: pos - left_pos = %d, high = %d\n"
           (pos - left_pos)
           high; *)
        if ni pos -/ ni left_pos >/ ni high
        then (total_fall + 1, true, pos, high)
        else (total_fall, false, pos, high)
      end
    else
      begin
        (* Printf.printf
           "false: pos - left_pos = %d, high = %d, left_high = %d\n"
           (pos - left_pos)
           high
           left_high; *)

        if ni pos -/ ni left_pos >/ ni left_high +/ ni high
        then (total_fall + 2, true, pos, high)

        else if ni pos -/ ni left_pos >/ ni left_high
        then (total_fall + 1, false, pos, high)

        else if ni pos -/ ni left_pos >/ ni high
        then (total_fall + 1, true, pos, high)
        else (total_fall, false, pos, high)
      end
  in
  let (ans, last, _, _) = List.fold_left update (0, true, -1000000001, 0) l in
  (* Printf.printf "last: %b\n" last; *)
  if last then ans
  else ans + 1

let _ =
  let n = read_int () in

  let rec read_pairs acc = function
    | 0 -> List.rev acc
    | n ->
      let pair =
        begin
          match Str.split (Str.regexp " ") (read_line ()) with
          | x :: y :: [] -> int_of_string x, int_of_string y
          | _            -> failwith "mulformed input"
        end
      in
      read_pairs (pair :: acc) (n - 1)
  in

  let ans = solve (read_pairs [] n) in
  print_endline (string_of_int ans)

let rec f lim = function
	|(a,b)::(c,d)::q -> if a - b > lim
				then 1 + f a ((c,d)::q)
				else if c - a > b
					then 1+f (a+b) ((c,d)::q)
					else f a ((c,d)::q)
	| _		 -> 1

let _ =
	let n = Scanf.scanf "%d" (fun i -> i) and l = ref [] in
	for i = 1 to n do
		Scanf.scanf " %d %d" (fun i j -> l := (i,j)::!l);
	done;
	Printf.printf "%d" (f min_int (List.rev !l))

let solve l =
  let update (total_fall, left_fall, left_pos, left_high) (pos, high) =
    if left_fall
    then
      begin
        (* Printf.printf "true: pos - left_pos = %d, high = %d\n" (pos - left_pos) high; *)
        if pos - left_pos > high then (total_fall + 1, true, pos, high)
        else (total_fall, false, pos, high)
      end
    else
      begin
        (* Printf.printf "false: pos - left_pos = %d, high = %d, left_high = %d\n" (pos - left_pos) high left_high; *)
        if pos - left_pos > left_high + high then (total_fall + 2, true, pos, high)
        else if pos - left_pos > left_high then (total_fall + 1, false, pos, high)
        else if pos - left_pos > high then (total_fall + 1, true, pos, high)
        else (total_fall, false, pos, high)
      end
  in
  let (ans, last, _, _) = List.fold_left update (0, true, -1000000001, 0) l in
  (* Printf.printf "last: %b\n" last; *)
  if last then ans
  else ans + 1

let _ =
  let n = read_int () in

  let rec read_pairs acc = function
    | 0 -> List.rev acc
    | n ->
      let pair =
        begin
          match Str.split (Str.regexp " ") (read_line ()) with
          | x :: y :: [] -> int_of_string x, int_of_string y
          | _            -> failwith "mulformed input"
        end
      in
      read_pairs (pair :: acc) (n - 1)
  in

  let ans = solve (read_pairs [] n) in
  print_endline (string_of_int ans)


Because of budget cuts one IT company established new non-financial reward system instead of bonuses.Two kinds of actions are rewarded: fixing critical bugs and suggesting new interesting features. A man who fixed a critical bug gets "I fixed a critical bug" pennant on his table. A man who suggested a new interesting feature gets "I suggested a new feature" pennant on his table.Because of the limited budget of the new reward system only 5 "I fixed a critical bug" pennants and 3 "I suggested a new feature" pennants were bought.In order to use these pennants for a long time they were made challenge ones. When a man fixes a new critical bug one of the earlier awarded "I fixed a critical bug" pennants is passed on to his table. When a man suggests a new interesting feature one of the earlier awarded "I suggested a new feature" pennants is passed on to his table.One man can have several pennants of one type and of course he can have pennants of both types on his table. There are n tables in the IT company. Find the number of ways to place the pennants on these tables given that each pennant is situated on one of the tables and each table is big enough to contain any number of pennants.

The only line of the input contains one integer n (1 ≤ n ≤ 500) — the number of tables in the IT company.

Output one integer — the amount of ways to place the pennants on n tables.

open Big_int

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

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

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


You are given an array of integers $$$a_1, a_2, \ldots, a_n$$$ and an integer $$$x$$$.You need to select the maximum number of elements in the array, such that for every subsegment $$$a_l, a_{l + 1}, \ldots, a_r$$$ containing strictly more than one element $$$(l < r)$$$, either:   At least one element on this subsegment is not selected, or  $$$a_l + a_{l+1} + \ldots + a_r \geq x \cdot (r - l + 1)$$$.

The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 10$$$): the number of test cases. The descriptions of $$$t$$$ test cases follow, three lines per test case. In the first line you are given one integer $$$n$$$ ($$$1 \leq n \leq 50\,000$$$): the number of integers in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-100\,000 \leq a_i \leq 100\,000$$$). The third line contains one integer $$$x$$$ ($$$-100\,000 \leq x \leq 100\,000$$$).

For each test case, print one integer: the maximum number of elements that you can select.

NoteIn the first example, one valid way to select the elements is $$$[\underline{1}, 2, \underline{3}, \underline{4}, \underline{5}]$$$. All subsegments satisfy at least one of the criteria. For example, for the subsegment $$$l = 1$$$, $$$r = 2$$$ we have that the element $$$2$$$ is not selected, satisfying the first criterion. For the subsegment $$$l = 3$$$, $$$r = 5$$$ we have $$$3 + 4 + 5 = 12 \ge 2 \cdot 3$$$, satisfying the second criterion.We can't select all elements, because in this case for $$$l = 1$$$, $$$r = 2$$$ all elements are selected and we have $$$a_1 + a_2 = 3 < 2 \cdot 2$$$. Thus, the maximum number of selected elements is $$$4$$$.In the second example, one valid solution is $$$[\underline{2}, \underline{4}, 2, \underline{4}, \underline{2}, \underline{4}, 2, \underline{4}, \underline{2}, \underline{4}]$$$.In the third example, one valid solution is $$$[\underline{-10}, -5, \underline{-10}]$$$.In the fourth example, one valid solution is $$$[\underline{9}, \underline{9}, -3]$$$.

(* The key theorem is that if all contiguous groups of 2 and 3 in a region
   are good, then the whole region is good (all contiguous blocks are good).
   The proof is simply that you can partition any contiguous block into
   disjoint blocks of size 2 and 3, and if those are all good then so
   is the whole thing.

   Thus, the question becomes what is the fewest number of things to eliminate
   that eliminate all bad blocks of 2 and 3.  This can be done by a linear time
   DP.
 *)

open Printf
open Scanf

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let sum i j f = fold i j (fun i a -> (f i) + a) 0
let 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 rec bitcount a = if a=0 then 0 else (a land 1) + (bitcount (a lsr 1))

let () =
  let cases = read_int () in
  for case = 1 to cases do
    let n = read_int () in
    let a = Array.init n read_int in
    let x = read_int () in
    if n=1 then printf "1\n"
    else if n=2 then
      let answer = if a.(0) + a.(1) >= 2*x then 2 else 1 in
      printf "%d\n" answer
    else
      let infty = n+1 in
      let dp = Array.make_matrix n 8 infty in
      let bad2 = Array.make n false in
      let bad3 = Array.make n false in
      for i=1 to n-1 do
	bad2.(i) <- a.(i-1) + a.(i) < 2*x;
	if i>1 then bad3.(i) <- a.(i-2) + a.(i-1) + a.(i) < 3*x;
      done;

      for pat = 0 to 3 do
	dp.(1).(pat) <- if bad2.(1) && pat = 0 then infty else bitcount pat
      done;

      for i=2 to n-1 do
	for pat = 0 to 7 do
	  let pat' = pat lsr 1 in
	  let pat'' = pat land 3 in
	  dp.(i).(pat'') <- min dp.(i).(pat'') (
	    if pat'' = 0 && bad2.(i) then infty
	    else if pat = 0 && bad3.(i) then infty
	    else dp.(i-1).(pat') + (pat land 1)
	  )
	done
      done;

      let answer = minf 0 7 (fun pat -> dp.(n-1).(pat)) in
      printf "%d\n" (n - answer)
  done


We have a point $$$A$$$ with coordinate $$$x = n$$$ on $$$OX$$$-axis. We'd like to find an integer point $$$B$$$ (also on $$$OX$$$-axis), such that the absolute difference between the distance from $$$O$$$ to $$$B$$$ and the distance from $$$A$$$ to $$$B$$$ is equal to $$$k$$$.  The description of the first test case. Since sometimes it's impossible to find such point $$$B$$$, we can, in one step, increase or decrease the coordinate of $$$A$$$ by $$$1$$$. What is the minimum number of steps we should do to make such point $$$B$$$ exist?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 6000$$$) — the number of test cases. The only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$0 \le n, k \le 10^6$$$) — the initial position of point $$$A$$$ and desirable absolute difference.

For each test case, print the minimum number of steps to make point $$$B$$$ exist.

NoteIn the first test case (picture above), if we set the coordinate of $$$B$$$ as $$$2$$$ then the absolute difference will be equal to $$$|(2 - 0) - (4 - 2)| = 0$$$ and we don't have to move $$$A$$$. So the answer is $$$0$$$.In the second test case, we can increase the coordinate of $$$A$$$ by $$$3$$$ and set the coordinate of $$$B$$$ as $$$0$$$ or $$$8$$$. The absolute difference will be equal to $$$|8 - 0| = 8$$$, so the answer is $$$3$$$.

(* Codeforces 1401 A Distance and Axis train  *)

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

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

let min_steps n k =
		if n < k then (k - n)
		else if ((n - k) mod 2) == 1 then 1
		else 0;;

let do_one () =
    let k,n = gr(),gr() in
		let min_st = min_steps n k in
		begin
			print_int min_st;
			print_string "\n"
		end;;

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

let main() =
	let t = gr () in
	do_all t;;

main();;


Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is $$$n$$$. There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains $$$2$$$ apartments, every other floor contains $$$x$$$ apartments each. Apartments are numbered starting from one, from the first floor. I.e. apartments on the first floor have numbers $$$1$$$ and $$$2$$$, apartments on the second floor have numbers from $$$3$$$ to $$$(x + 2)$$$, apartments on the third floor have numbers from $$$(x + 3)$$$ to $$$(2 \cdot x + 2)$$$, and so on.Your task is to find the number of floor on which Petya lives. Assume that the house is always high enough to fit at least $$$n$$$ apartments.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n, x \le 1000$$$) — the number of Petya's apartment and the number of apartments on each floor of the house except the first one (there are two apartments on the first floor).

For each test case, print the answer: the number of floor on which Petya lives.

NoteConsider the first test case of the example: the first floor contains apartments with numbers $$$1$$$ and $$$2$$$, the second one contains apartments with numbers $$$3$$$, $$$4$$$ and $$$5$$$, the third one contains apartments with numbers $$$6$$$, $$$7$$$ and $$$8$$$. Therefore, Petya lives on the third floor.In the second test case of the example, Petya lives in the apartment $$$1$$$ which is on the first floor.

let rec case t =
    if t > 0 then
        let solve n x =
            if n <= 2 then 1
            else let rec calc acc n x =
                if n <= x then acc + 1 else calc (acc + 1) (n - x) x
            in calc 1 (n - 2) x
        in Scanf.scanf "%i %i\n" (fun n x -> Printf.printf "%d\n" (solve n x); case (t - 1))
in Scanf.scanf "%d\n" (fun t -> case t)

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

let rec read_ints n =
  match n with
  | 0 -> []
  | x -> read_int () :: (read_ints (n-1))

(* let read_ints () =
 *   let line = read_line () in
 *   let ints = Str.split (Str.regexp " *") line in
 *   List.map int_of_string ints *)

let rec print_list = function
    [] -> ()
  | e::l -> print_int e ; print_string " " ; print_list l

let solve () =
  let n = read_int () in
  let x = read_int () in
  let k = int_of_float
            (ceil ((float_of_int (x + n - 2)) /. (float_of_int x))) in
  print_int (if n <= 2 then 1 else k);
  print_endline ""
(**)

let () =
  let x = read_int () in
  let rec loop n =
    match n with
    | 0 -> ()
    | x -> solve (); loop (n-1) in
  loop x

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

let rec read_ints n =
  match n with
  | 0 -> []
  | x -> read_int () :: (read_ints (n-1))

(* let read_ints () =
 *   let line = read_line () in
 *   let ints = Str.split (Str.regexp " *") line in
 *   List.map int_of_string ints *)

let rec print_list = function
    [] -> ()
  | e::l -> print_int e ; print_string " " ; print_list l

let solve () =
  let n = float_of_int (read_int ()) in
  let x = float_of_int (read_int ()) in
  let k = int_of_float (ceil (1.0 +. (n -. 2.0) /. x)) in
  print_int k;
  print_endline ""
(**)

let () =
  let x = read_int () in
  let rec loop n =
    match n with
    | 0 -> ()
    | x -> solve (); loop (n-1) in
  loop x


3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze, in the forms of a $$$2 \times n$$$ rectangle grid. NEKO's task is to lead a Nekomimi girl from cell $$$(1, 1)$$$ to the gate at $$$(2, n)$$$ and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only $$$q$$$ such moments: the $$$i$$$-th moment toggles the state of cell $$$(r_i, c_i)$$$ (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the $$$q$$$ moments, whether it is still possible to move from cell $$$(1, 1)$$$ to cell $$$(2, n)$$$ without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?

The first line contains integers $$$n$$$, $$$q$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le q \le 10^5$$$). The $$$i$$$-th of $$$q$$$ following lines contains two integers $$$r_i$$$, $$$c_i$$$ ($$$1 \le r_i \le 2$$$, $$$1 \le c_i \le n$$$), denoting the coordinates of the cell to be flipped at the $$$i$$$-th moment. It is guaranteed that cells $$$(1, 1)$$$ and $$$(2, n)$$$ never appear in the query list.

For each moment, if it is possible to travel from cell $$$(1, 1)$$$ to cell $$$(2, n)$$$, print "Yes", otherwise print "No". There should be exactly $$$q$$$ answers, one after every update. You can print the words in any case (either lowercase, uppercase or mixed).

NoteWe'll crack down the example test here:  After the first query, the girl still able to reach the goal. One of the shortest path ways should be: $$$(1,1) \to (1,2) \to (1,3) \to (1,4) \to (1,5) \to (2,5)$$$.  After the second query, it's impossible to move to the goal, since the farthest cell she could reach is $$$(1, 3)$$$.  After the fourth query, the $$$(2, 3)$$$ is not blocked, but now all the $$$4$$$-th column is blocked, so she still can't reach the goal.  After the fifth query, the column barrier has been lifted, thus she can go to the final goal again.

open Printf
open Scanf

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

let () =
  let n = read_int() in
  let q = read_int() in
  let arr = Array.init n
            (fun _ -> Array.make 2 false)
  in
  let sum = ref 0 in
  for i=0 to q-1 do
    let r = read_int() in
    let c = read_int() in
    let r3 = r lxor 3 in
    let count = [-1; 0; 1]
    |> List.map (fun (x: int) -> (r3, c + x))
    |> List.filter (fun (x: int * int) -> 1 <= (snd x) && (snd x) <= n)
    |> List.filter (fun (x: int * int) -> arr.((snd x) - 1).(r3 - 1))
    |> List.length in
    if arr.(c - 1).(r - 1) then (
        arr.(c - 1).(r - 1) <- false;
        sum := !sum - count
    ) else (
        arr.(c - 1).(r - 1) <- true;
        sum := !sum + count
    );
    printf (if !sum > 0 then "No\n" else "Yes\n");
  done;

open Printf
open Scanf

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

let () =
  let n = read_int() in
  let q = read_int() in
  let arr = Array.init n
            (fun _ -> Array.make 2 false)
  in
  let sum = ref 0 in
  for i=0 to q-1 do
    let r = read_int() - 1 in
    let c = read_int() - 1 in
    let r3 = r lxor 1 in
    let count = [-1; 0; 1]
    |> List.map (fun (x: int) -> (r3, c + x))
    |> List.filter (fun (x: int * int) -> 0 <= (snd x) && (snd x) < n)
    |> List.filter (fun (x: int * int) -> arr.(snd x).(r3))
    |> List.length in
    if arr.(c).(r) then (
        arr.(c).(r) <- false;
        sum := !sum - count
    ) else (
        arr.(c).(r) <- true;
        sum := !sum + count
    );
    printf (if !sum > 0 then "No\n" else "Yes\n");
  done;


You are given two circles. Find the area of their intersection.

The first line contains three integers x1, y1, r1 ( - 109 ≤ x1, y1 ≤ 109, 1 ≤ r1 ≤ 109) — the position of the center and the radius of the first circle. The second line contains three integers x2, y2, r2 ( - 109 ≤ x2, y2 ≤ 109, 1 ≤ r2 ≤ 109) — the position of the center and the radius of the second circle.

Print the area of the intersection of the circles. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.

open Big_int

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

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

let precision = 100
let base = power_int_positive_int 10 precision

let atan z =
  let z2 = z *| z in
  let base2 = base *| base in
  let r = ref n0 in
  let p = ref base in
    for n = 0 to 1000 do
      if n > 0 then (
	p := !p *| big_int_of_int (2 * n) *| z2 /|
	    (big_int_of_int (2 * n + 1) *| (base2 +| z2));
      );
      r := !r +| !p;
    done;
    (!r *| z *| base) /| (base2 +| z2)

let pi = atan base *| big_int_of_int 4

let atan z =
  if z >| base
  then pi /| n2 -| atan (base *| base /| z)
  else atan z

let atan z =
  if z <| n0
  then minus_big_int (atan (minus_big_int z))
  else atan z

let atan2 y x =
  if x >| n0
  then atan (y *| base /| x)
  else if x =| n0
  then (
    if y >| n0
    then pi /| n2
    else if y <| n0
    then minus_big_int (pi /| n2)
    else assert false
  ) else (
    if y >=| n0
    then atan (y *| base /| x) +| pi
    else atan (y *| base /| x) -| pi
  )

let _ =
  let sb = Scanf.Scanning.stdib in
  let x1 = Scanf.bscanf sb "%d " (fun s -> s) in
  let y1 = Scanf.bscanf sb "%d " (fun s -> s) in
  let r1 = Scanf.bscanf sb "%d " (fun s -> s) in
  let x2 = Scanf.bscanf sb "%d " (fun s -> s) in
  let y2 = Scanf.bscanf sb "%d " (fun s -> s) in
  let r2 = Scanf.bscanf sb "%d " (fun s -> s) in
  let sqr x = x *| x in
  let x1 = big_int_of_int x1 *| base in
  let y1 = big_int_of_int y1 *| base in
  let r1 = big_int_of_int r1 *| base in
  let x2 = big_int_of_int x2 *| base in
  let y2 = big_int_of_int y2 *| base in
  let r2 = big_int_of_int r2 *| base in
  let d2 = sqr (x1 -| x2) +| sqr (y1 -| y2) in
  let d = sqrt_big_int d2 in
  let res =
    if d <=| r2 -| r1 +| n1
    then pi *| sqr r1 /| (base *| base)
    else if d <=| r1 -| r2 +| n1
    then pi *| sqr r2 /| (base *| base)
    else if d >=| r1 +| r2 -| n1
    then n0
    else (
      let intersect r1 r2 =
	let a = (d2 +| sqr r1 -| sqr r2) /| (n2 *| d) in
	let h = sqrt_big_int (max_big_int n0 (sqr r1 -| sqr a)) in
	let alpha = atan2 h a in
	  alpha *| sqr r1 /| (base *| base) -| a *| h /| base
      in
	intersect r1 r2 +| intersect r2 r1
    )
  in
    (*Printf.printf "%s\n" (string_of_big_int res)*)
    Num.(
      let res = num_of_big_int res // num_of_big_int base in
      let s = approx_num_fix 100 res in
      let _ = assert (s.[0] = '+') in
      let s = String.sub s 1 (String.length s - 1) in
	Printf.printf "%s\n" s
    )

let _ =
  let sb = Scanf.Scanning.stdib in
  let x1 = Scanf.bscanf sb "%f " (fun s -> s) in
  let y1 = Scanf.bscanf sb "%f " (fun s -> s) in
  let r1 = Scanf.bscanf sb "%f " (fun s -> s) in
  let x2 = Scanf.bscanf sb "%f " (fun s -> s) in
  let y2 = Scanf.bscanf sb "%f " (fun s -> s) in
  let r2 = Scanf.bscanf sb "%f " (fun s -> s) in
  let pi = 4.0 *. atan 1.0 in
  let sqr x = x *. x in
  let d2 = sqr (x1 -. x2) +. sqr (y1 -. y2) in
  let d = sqrt d2 in
  let res =
    if d <= r2 -. r1 +. 1e-11
    then pi *. sqr r1
    else if d <= r1 -. r2 +. 1e-11
    then pi *. sqr r2
    else if d >= r1 +. r2 -. 1e-11
    then 0.0
    else (
      let a1 = sqr r1 *. acos ((d2 +. sqr r1 -. sqr r2) /. (2.0 *. d *. r1)) in
      let a2 = sqr r2 *. acos ((d2 +. sqr r2 -. sqr r1) /. (2.0 *. d *. r2)) in
      let a3 =
	sqrt ((-.d +. r1 +. r2) *. (d -. r1 +. r2) *. (d +. r1 -. r2) *.
		(d +. r1 +. r2))
      in
	a1 +. a2 -. a3 /. 2.0
    )
  in
    Printf.printf "%.9f\n" res

let _ =
  let sb = Scanf.Scanning.stdib in
  let x1 = Scanf.bscanf sb "%f " (fun s -> s) in
  let y1 = Scanf.bscanf sb "%f " (fun s -> s) in
  let r1 = Scanf.bscanf sb "%f " (fun s -> s) in
  let x2 = Scanf.bscanf sb "%f " (fun s -> s) in
  let y2 = Scanf.bscanf sb "%f " (fun s -> s) in
  let r2 = Scanf.bscanf sb "%f " (fun s -> s) in
  let sqr x = x *. x in
  let d2 = sqr (x1 -. x2) +. sqr (y1 -. y2) in
  let d = sqrt d2 in
  let res =
    if d >= r1 +. r2
    then 0.0
    else (
      let a1 = sqr r1 *. acos ((d2 +. sqr r1 -. sqr r2) /. (2.0 *. d *. r1)) in
      let a2 = sqr r2 *. acos ((d2 +. sqr r2 -. sqr r1) /. (2.0 *. d *. r2)) in
      let a3 =
	sqrt ((-.d +. r1 +. r2) *. (d -. r1 +. r2) *. (d +. r1 -. r2) *.
		(d +. r1 +. r2))
      in
	a1 +. a2 -. a3 /. 2.0
    )
  in
    Printf.printf "%.9f\n" res

let _ =
  let sb = Scanf.Scanning.stdib in
  let x1 = Scanf.bscanf sb "%f " (fun s -> s) in
  let y1 = Scanf.bscanf sb "%f " (fun s -> s) in
  let r1 = Scanf.bscanf sb "%f " (fun s -> s) in
  let x2 = Scanf.bscanf sb "%f " (fun s -> s) in
  let y2 = Scanf.bscanf sb "%f " (fun s -> s) in
  let r2 = Scanf.bscanf sb "%f " (fun s -> s) in
  let pi = 4.0 *. atan 1.0 in
  let sqr x = x *. x in
  let d2 = sqr (x1 -. x2) +. sqr (y1 -. y2) in
  let d = sqrt d2 in
  let res =
    if d <= r2 -. r1 +. 1e-11
    then pi *. sqr r1
    else if d <= r1 -. r2 +. 1e-11
    then pi *. sqr r2
    else if d >= r1 +. r2 -. 1e-11
    then 0.0
    else (
      let intersect r1 r2 =
	let a = (d2 +. sqr r1 -. sqr r2) /. (2.0 *. d) in
	let h = sqrt (max 0.0 (sqr r1 -. sqr a)) in
	let alpha = atan2 h a in
	  alpha *. sqr r1 -. a *. h
      in
      (*let a1 = sqr r1 *. acos ((d2 +. sqr r1 -. sqr r2) /. (2.0 *. d *. r1)) in
      let a2 = sqr r2 *. acos ((d2 +. sqr r2 -. sqr r1) /. (2.0 *. d *. r2)) in
      let a3 =
	sqrt ((-.d +. r1 +. r2) *. (d -. r1 +. r2) *. (d +. r1 -. r2) *.
		(d +. r1 +. r2))
      in
	a1 +. a2 -. a3 /. 2.0
      *)
	intersect r1 r2 +. intersect r2 r1
    )
  in
    Printf.printf "%.9f\n" res


You are given two positive integer numbers x and y. An array F is called an y-factorization of x iff the following conditions are met:  There are y elements in F, and all of them are integer numbers;  . You have to count the number of pairwise distinct arrays that are y-factorizations of x. Two arrays A and B are considered different iff there exists at least one index i (1 ≤ i ≤ y) such that Ai ≠ Bi. Since the answer can be very large, print it modulo 109 + 7.

The first line contains one integer q (1 ≤ q ≤ 105) — the number of testcases to solve. Then q lines follow, each containing two integers xi and yi (1 ≤ xi, yi ≤ 106). Each of these lines represents a testcase.

Print q integers. i-th integer has to be equal to the number of yi-factorizations of xi modulo 109 + 7.

NoteIn the second testcase of the example there are six y-factorizations:  { - 4,  - 1};  { - 2,  - 2};  { - 1,  - 4};  {1, 4};  {2, 2};  {4, 1}.

open Printf
open Scanf

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

let factor n = (* the list of prime powers that occur when we factor n *)
  let rec loop n p pow ac =
    let ac' = if pow>0 then (pow::ac) else ac in
    if n=1 then ac'
    else if n mod p = 0 then loop (n/p) p (pow+1) ac
    else loop n (p+1) 0 ac'
  in
  List.rev (loop n 2 0 [])

let rec power_in p j = if p>j || j mod p <> 0 then 0 else 1 + power_in p (j/p)

let compute_prime_powers n =
  let sieve = Array.make (n+1) [] in
  let rec loop i = if i <= n then (
    if sieve.(i) = [] then ( (* i is a prime *)
      let rec pass j = if j<=n then (
	sieve.(j) <- (power_in i j)::sieve.(j);
	pass (j+i)
      ) in
      pass i;
    );
    loop (i+1)
  )
  in
  loop 2;
  sieve

let mm = 1_000_000_007L

let ( ** ) a b = (Int64.rem (Int64.mul a b) mm)
let ( // ) a b = Int64.div a b (* non mod division *)
let ( %% ) a b = Int64.rem a b
let ( -- ) a b = Int64.sub a b (* non mod subtraction *)
let ( ++ ) a b = let c = Int64.add a b in
		 if c >= mm then (c -- mm) else c
let long x = Int64.of_int x
let short x = Int64.to_int x

let rec powermod a b =   (* a^b mod m *)
  if b=0 then 1L else
    let r = powermod a (b lsr 1) in
    let r2 = r**r in
      if b land 1 = 0 then r2 else r2**a

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

let inverse a =
  let rec egcd a b =
    (* given a and b this returns (x, y, g) where g = gcd(a,b) and ax+by=g  *)
    if a = 0 then (0,1,b) else
      let (x,y,g) = egcd (b mod a) a in
      (y-(b/a)*x, x, g)
  in
  let (x,_,_) = egcd (short a) (short mm) in
  long (if x >= 0 then x else x+(short mm))

let init_factorial n =
  let f = Array.make (n+1) 1L in
  for i=1 to n do
    f.(i) <- (long i) ** f.(i-1)
  done;
  f

let binom n k f =  (* n choose k (f is the factoral table) *)
  if k < 0 || n < k then 0L else
    f.(n) ** (inverse f.(k)) ** (inverse f.(n-k))

let () =

  let maxy = 1_000_000 in
  let maxx = 1_000_000 in
  let maxk = 20 in
  let fact = init_factorial (maxy+maxk-1) in
  let prime_powers = compute_prime_powers maxx in

  let q = read_int() in
  for i=1 to q do
    let x = read_int() in
    let y = read_int() in

(*    let prime_powers = Array.of_list (factor x) in *)
    let npp = List.length prime_powers.(x) in
    let pparray = Array.of_list prime_powers.(x) in

    let combs = product 0 (npp-1) (fun i ->
      let k = pparray.(i) in
      binom (y+k-1) k fact
    ) in

    let answer = (powermod 2L (y-1)) ** combs in

    printf "%Ld\n" answer
  done


HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read some file.Find the time need to read file split to n fragments. The i-th sector contains the fi-th fragment of the file (1 ≤ fi ≤ n). Note different sectors contains the different fragments. At the start the magnetic head is in the position that contains the first fragment. The file are reading in the following manner: at first the first fragment is read, then the magnetic head moves to the sector that contains the second fragment, then the second fragment is read and so on until the n-th fragment is read. The fragments are read in the order from the first to the n-th.It takes |a - b| time units to move the magnetic head from the sector a to the sector b. Reading a fragment takes no time.

The first line contains a positive integer n (1 ≤ n ≤ 2·105) — the number of fragments. The second line contains n different integers fi (1 ≤ fi ≤ n) — the number of the fragment written in the i-th sector.

Print the only integer — the number of time units needed to read the file.

NoteIn the second example the head moves in the following way:  1->2 means movement from the sector 1 to the sector 5, i.e. it takes 4 time units  2->3 means movement from the sector 5 to the sector 2, i.e. it takes 3 time units  3->4 means movement from the sector 2 to the sector 4, i.e. it takes 2 time units  4->5 means movement from the sector 4 to the sector 3, i.e. it takes 1 time units So the answer to the second example is 4 + 3 + 2 + 1 = 10.

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

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 = 1 to n do
      let k = Scanf.bscanf sb "%d " (fun s -> s) in
	a.(k - 1) <- i
    done;
    let pos = ref a.(0) in
    let res = ref 0L in
      for i = 0 to n - 1 do
	res := !res +| Int64.of_int (abs (a.(i) - !pos));
	pos := a.(i);
      done;
    Printf.printf "%Ld\n" !res


You are given an array $$$a$$$ consisting of $$$n$$$ positive integers, and an array $$$b$$$, with length $$$n$$$. Initially $$$b_i=0$$$ for each $$$1 \leq i \leq n$$$.In one move you can choose an integer $$$i$$$ ($$$1 \leq i \leq n$$$), and add $$$a_i$$$ to $$$b_i$$$ or subtract $$$a_i$$$ from $$$b_i$$$. What is the minimum number of moves needed to make $$$b$$$ increasing (that is, every element is strictly greater than every element before it)?

The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 5000$$$). The second line contains $$$n$$$ integers, $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the elements of the array $$$a$$$.

Print a single integer, the minimum number of moves to make $$$b$$$ increasing.

let _ = read_line ()
let nums_str = read_line ()

let rec split str len n acc nums =
  if n = len then nums @ [Int64.of_string acc]
  else if str.[n] = ' ' then split str len (n + 1) "" (nums @ [Int64.of_string acc])
  else split str len (n + 1) (acc ^ String.make 1 str.[n]) nums

let nums = split nums_str (String.length nums_str) 0 "" []

let rec add lst prev moves =
  match lst with
  | [] -> moves
  | h :: t ->
      let o = Int64.div (Int64.add prev h) h in
      add t
        (Int64.mul h o)
        (Int64.add moves o)

let rec sub lst prev moves =
  match lst with
  | [] -> moves
  | h :: t ->
      let o = Int64.abs (Int64.div (Int64.sub prev h) h) in
      sub t
        (Int64.mul (Int64.neg h) o)
        (Int64.add moves o)

let rec attempt lst rev ans =
  match lst with
  | [] -> ans
  | h :: t -> attempt t (h :: rev) (min ans (Int64.add (sub rev 0L 0L) (add t 0L 0L)))

let ans = attempt nums [] Int64.max_int;;

Printf.printf "%Ld\n" ans

let _ = read_line ()
let nums_str = read_line ()

let rec split str len n acc =
  if n = len then [ int_of_string acc ]
  else if str.[n] = ' ' then int_of_string acc :: split str len (n + 1) ""
  else split str len (n + 1) (acc ^ String.make 1 str.[n])

let nums = split nums_str (String.length nums_str) 0 ""

let rec add lst prev moves =
  match lst with
  | [] -> moves
  | h :: t -> add t (h * ((prev + h) / h)) (moves + ((prev + h) / h))

let rec sub lst prev moves =
  match lst with
  | [] -> moves
  | h :: t ->
      if abs (prev - h) < 0 then -1
      else sub t (-h * (abs (prev - h) / h)) (moves + (abs (prev - h) / h))

let rec attempt lst rev ans =
  match lst with
  | [] -> ans
  | h :: t -> attempt t (h :: rev) (min ans (sub rev 0 0 + add t 0 0))

let ans = attempt nums [] max_int;;

Printf.printf "%d\n" ans

let _ = read_line ()
let nums_str = read_line ()

let rec split str len n acc =
  if n = len then [ int_of_string acc ]
  else if str.[n] = ' ' then int_of_string acc :: split str len (n + 1) ""
  else split str len (n + 1) (acc ^ String.make 1 str.[n])

let nums = split nums_str (String.length nums_str) 0 ""

let rec add lst prev moves =
  match lst with
  | [] -> moves
  | h :: t -> add t (h * ((prev + h) / h)) (moves + ((prev + h) / h))

let rec sub lst prev moves =
  match lst with
  | [] -> moves
  | h :: t -> sub t (-h * (abs (prev - h) / h)) (moves + (abs (prev - h) / h))

let rec attempt lst rev i ans =
  match lst with
  | [] -> ans
  | h :: t -> attempt t (h :: rev) (i + 1) (min ans (sub rev 0 0 + add t 0 0))

let ans = attempt nums [] 0 max_int;;

Printf.printf "%d\n" ans

let _ = read_line ()
let nums_str = read_line ()

let rec split str len n acc =
  if n = len then [ int_of_string acc ]
  else if str.[n] = ' ' then int_of_string acc :: split str len (n + 1) ""
  else split str len (n + 1) (acc ^ String.make 1 str.[n])

let nums = split nums_str (String.length nums_str) 0 ""

let rec add lst prev moves =
  match lst with
  | [] -> moves
  | h :: t -> add t (h * (abs (prev + h) / h)) (moves + (abs (prev + h) / h))

let rec sub lst prev moves =
  match lst with
  | [] -> moves
  | h :: t -> sub t (-h * (abs (prev - h) / h)) (moves + (abs (prev - h) / h))

let rec attempt lst rev i ans =
  match lst with
  | [] -> ans
  | h :: t -> attempt t (h :: rev) (i + 1) (min ans (sub rev 0 0 + add t 0 0))

let ans = attempt nums [] 0 max_int;;

Printf.printf "%d\n" ans

let _ = read_line ()
let nums_str = read_line ()

let rec split str len n acc =
  if n = len then [ int_of_string acc ]
  else if str.[n] = ' ' then int_of_string acc :: split str len (n + 1) ""
  else split str len (n + 1) (acc ^ String.make 1 str.[n])

let nums = split nums_str (String.length nums_str) 0 ""

let rec get_rev lst i =
  match lst with
  | [] -> []
  | h :: t -> if i = 0 then [] else get_rev t (i - 1) @ [ h ]

let rec add lst prev moves =
  match lst with
  | [] -> moves
  | h :: t -> add t (h * abs ((prev + h) / h)) (moves + ((prev + h) / h))

let rec sub lst prev moves =
  match lst with
  | [] -> moves
  | h :: t -> sub t (-h * abs ((prev - h) / h)) (moves + (abs (prev - h) / h))

let rec attempt lst rev i ans =
  match lst with
  | [] -> ans
  | h :: t -> attempt t (h :: rev) (i + 1) (min ans (sub rev 0 0 + add t 0 0))

let ans = attempt nums [] 0 max_int;;

Printf.printf "%d\n" ans

let _ = read_line ()
let nums_str = read_line ()

let rec split str len n acc =
  if n = len then [ int_of_string acc ]
  else if str.[n] = ' ' then int_of_string acc :: split str len (n + 1) ""
  else split str len (n + 1) (acc ^ String.make 1 str.[n])

let nums = split nums_str (String.length nums_str) 0 ""

let rec loop lst =
  match lst with
  | [] -> print_newline ()
  | h :: t ->
      print_string (string_of_int h ^ " ");
      loop t

let () = loop nums

let rec get_rev lst i =
  match lst with
  | [] -> []
  | h :: t -> if i = 0 then [] else get_rev t (i - 1) @ [ h ]

let rec add lst prev moves =
  match lst with
  | [] -> moves
  | h :: t -> add t (h * abs ((prev + h) / h)) (moves + ((prev + h) / h))

let rec sub lst prev moves =
  match lst with
  | [] -> moves
  | h :: t -> sub t (-h * abs ((prev - h) / h)) (moves + (abs (prev - h) / h))

let rec attempt lst i len ans =
  match lst with
  | [] -> ans
  | h :: t ->
      attempt t (i + 1) len (min ans (sub (get_rev nums i) 0 0 + add t 0 0))

let ans = attempt nums 0 (List.length nums) max_int;;

Printf.printf "%d\n" ans


A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.Write a program which for the given n will find a beautiful number such that n can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number n.If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.

The first line of input contains n — a positive integer number without leading zeroes (1 ≤ n < 10100000).

Print one number — any beautiful number obtained by erasing as few as possible digits. If there is no answer, print  - 1.

NoteIn the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two.

let _ =
  let sb = Scanf.Scanning.stdib in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let n = String.length s in
  let c2i c = Char.code c - Char.code '0' in
  let t =
    let t = ref 0 in
      for i = 0 to n - 1 do
	t := !t + c2i s.[i]
      done;
      !t mod 3
  in
    if t = 0
    then Printf.printf "%s\n" s
    else (
      let b = ref 1000000000 in
      let bs = ref "" in
	for i = n - 1 downto 0 do
	  if c2i s.[i] mod 3 = t then (
	    if i > 0 then (
	      if !b > 1 then (
		b := 1;
		bs := String.sub s 0 i ^ String.sub s (i + 1) (n - i - 1)
	      )
	    ) else (
	      let j = ref (n - 1) in
		for i = n - 1 downto 1 do
		  if c2i s.[i] <> 0 then (
		    j := i
		  )
		done;
		if !j > 0 then (
		  if !b > !j then (
		    b := !j;
		    bs := String.sub s !j (n - !j)
		  )
		)
	    )
	  )
	done;
	(let p1 = ref (-1) in
	 let p2 = ref (-1) in
	 let _ =
	   for i = n - 1 downto 0 do
	     if c2i s.[i] mod 3 = 3 - t then (
	       if !p2 < 0
	       then p2 := i
	       else if !p1 < 0
	       then p1 := i
	     )
	   done;
	 in
	 let p1 = !p1
	 and p2 = !p2 in
	   if p1 >= 0 then (
	     if p1 > 0 then (
	       if !b > 2 then (
		 b := 2;
		 bs := String.sub s 0 p1 ^ String.sub s (p1 + 1) (p2 - p1 - 1) ^
		   String.sub s (p2 + 1) (n - p2 - 1)
	       )
	     ) else (
	       let j = ref 1 in
		 while !j < n && (c2i s.[!j] = 0 || !j = p2) do
		   incr j
		 done;
		 if !j < n then (
		   if !j < p2 then (
		     if !b > !j + 1 then (
		       b := !j + 1;
		       bs := String.sub s !j (p2 - !j) ^
			 String.sub s (p2 + 1) (n - p2 - 1)
		     )
		   ) else (
		     if !b > !j then (
		       b := !j;
		       bs := String.sub s !j (n - !j)
		     )
		   )
		 ) else if n > 2 then (
		     if !b > n - 1 then (
		       b := n - 1;
		       bs := "0"
		     )
		 )
	     )
	   )
	);
	if !bs <> ""
	then Printf.printf "%s\n" !bs
	else Printf.printf "-1\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 c2i c = Char.code c - Char.code '0' in
  let t =
    let t = ref 0 in
      for i = 0 to n - 1 do
	t := !t + c2i s.[i]
      done;
      !t mod 3
  in
    if t = 0
    then Printf.printf "%s\n" s
    else (
      let b = ref 1000000000 in
      let bs = ref "" in
	for i = n - 1 downto 0 do
	  if c2i s.[i] mod 3 = t then (
	    if i > 0 then (
	      if !b > 1 then (
		b := 1;
		bs := String.sub s 0 i ^ String.sub s (i + 1) (n - i - 1)
	      )
	    ) else (
	      let j = ref (n - 1) in
		for i = n - 1 downto 1 do
		  if c2i s.[i] <> 0 then (
		    j := i
		  )
		done;
		if !j > 0 then (
		  if !b > !j then (
		    b := !j;
		    bs := String.sub s !j (n - !j)
		  )
		)
	    )
	  )
	done;
	(let p1 = ref (-1) in
	 let p2 = ref (-1) in
	 let _ =
	   for i = n - 1 downto 0 do
	     if c2i s.[i] mod 3 = 3 - t then (
	       if !p2 < 0
	       then p2 := i
	       else if !p1 < 0
	       then p1 := i
	     )
	   done;
	 in
	 let p1 = !p1
	 and p2 = !p2 in
	   if p1 >= 0 then (
	     if p1 > 0 then (
	       if !b > 2 then (
		 b := 2;
		 bs := String.sub s 0 p1 ^ String.sub s (p1 + 1) (p2 - p1 - 1) ^
		   String.sub s (p2 + 1) (n - p2 - 1)
	       )
	     ) else (
	       let j = ref 1 in
		 while !j < n && (c2i s.[!j] = 0 || !j = p2) do
		   incr j
		 done;
		 if !j < n then (
		   if !j < p2 then (
		     if !b > !j + 1 then (
		       b := !j + 1;
		       bs := String.sub s !j (p2 - !j) ^
			 String.sub s (p2 + 1) (n - p2 - 1)
		     )
		   ) else (
		     if !b > !j then (
		       b := !j;
		       bs := String.sub s !j (n - !j)
		     )
		   )
		 ) else if s.[n - 1] = '0' then (
		     if !b > n - 1 then (
		       b := n - 1;
		       bs := String.sub s (n - 1) 1
		     )
		 )
	     )
	   )
	);
	if !bs <> ""
	then Printf.printf "%s\n" !bs
	else Printf.printf "-1\n"
    )


Little Petya likes to play very much. And most of all he likes to play the following game:He is given a sequence of N integer numbers. At each step it is allowed to increase the value of any number by 1 or to decrease it by 1. The goal of the game is to make the sequence non-decreasing with the smallest number of steps. Petya is not good at math, so he asks for your help.The sequence a is called non-decreasing if a1 ≤ a2 ≤ ... ≤ aN holds, where N is the length of the sequence.

The first line of the input contains single integer N (1 ≤ N ≤ 5000) — the length of the initial sequence. The following N lines contain one integer each — elements of the sequence. These numbers do not exceed 109 by absolute value.

Output one integer — minimum number of steps required to achieve the goal.

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

type node = {key: int; child: node; sibling: node}

let rec nil = {key = min_int; child = nil; sibling = nil}
let is_nil a = a.key = min_int

let merge a b =
  if a.key > b.key then
    {a with child = {b with sibling = a.child}}
  else
    {b with child = {a with sibling = b.child}}

let merge_list x =
  let rec go acc x =
    if is_nil x then
      acc
    else
      if is_nil x.sibling then
        x::acc
      else
        go (merge x x.sibling::acc) x.sibling.sibling
  in
  match go [] x with
  | [] -> nil
  | u::us -> List.fold_left (fun u v -> merge u v) u us

let pop x = merge_list x.child

let singleton k = {key = k; child = nil; sibling = nil}

let print x =
  let rec go d x =
    if not (is_nil x) then (
      go (d+1) x.sibling;
      for i = 1 to d do print_string "  " done;
      Printf.printf "%d\n" x.key;
      go (d+1) x.child;
    )
  in go 0 x

let () =
  let n = read_int 0 in
  let a = Array.init n read_int in
  let rec go st i =
    if i >= n then
      st
    else
      let rec f = function
        | (y,yi)::(x,xi)::xs when x.key > y.key ->
          let z = merge x y in
          let z = if (xi-(if xs=[] then -1 else (List.hd xs |> snd))) land 1 <> 0 &&
                (yi-xi) land 1 <> 0 then pop z else z in
          f ((z,yi)::xs)
        | st -> st
      in
      go ((singleton a.(i),i) :: st |> f) (i+1)
  in

  go [] 0
  |> List.rev
  |> List.fold_left (fun (ans,l) (x,xi) ->
    let rec go ans i =
      if i > xi then
        ans
      else
        let open Int64 in
        go (abs (sub (of_int a.(i)) (of_int x.key)) |> add ans) (i+1)
    in
    go ans (l+1), xi
  ) (0L,-1)
  |> fst |> Printf.printf "%Ld\n"

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

type node = {key: int; child: node; sibling: node}

let rec nil = {key = min_int; child = nil; sibling = nil}
let is_nil a = a.key = min_int

let merge a b =
  if a.key > b.key then
    {a with child = {b with sibling = a.child}}
  else
    {b with child = {a with sibling = b.child}}

let merge_list x =
  let rec go acc x =
    if is_nil x then
      acc
    else
      let y = {x with sibling = nil} in
      if is_nil x.sibling then
        y::acc
      else
        let z = {x.sibling with sibling = nil} in
        go (merge y z::acc) x.sibling.sibling
  in
  match go [] x with
  | [] -> nil
  | u::us -> List.fold_left (fun u v -> merge u v) u us

let pop x = merge_list x.child

let singleton k = {key = k; child = nil; sibling = nil}

let push x k = merge x {key = k; child = nil; sibling = nil}

let print x =
  let rec go d x =
    if not (is_nil x) then (
      go (d+1) x.sibling;
      for i = 1 to d do print_string "  " done;
      Printf.printf "%d\n" x.key;
      go (d+1) x.child;
    )
  in go 0 x

let () =
  let n = read_int 0 in
  let a = Array.init n read_int in
  let rec go st i =
    if i >= n then
      st
    else
      let rec f = function
        | (y,yi)::(x,xi)::xs when x.key > y.key ->
          let z = merge x y in
          let z = if (xi-(if xs=[] then -1 else (List.hd xs |> snd))) land 1 <> 0 &&
                (yi-xi) land 1 <> 0 then pop z else z in
          f ((z,yi)::xs)
        | st -> st
      in
      go ((singleton a.(i),i) :: st |> f) (i+1)
  in

  (*let st = go [] 0 in*)
  (*Printf.printf "+ len: %d\n" (List.length st);*)
  (*Printf.printf "+++++++++\n";*)
  (*List.nth st 0 |> snd |> Printf.printf "%d\n";*)
  (*List.nth st 0 |> fst |> print;*)
  (*Printf.printf "+++++++++\n";*)
  (*List.nth st 1 |> snd |> Printf.printf "%d\n";*)
  (*List.nth st 1 |> fst |> print;*)
  go [] 0
  |> List.rev
  |> List.fold_left (fun (ans,l) (x,xi) ->
    let rec go ans i =
      if i > xi then
        ans
      else
        let open Int64 in
        go (abs (sub (of_int a.(i)) (of_int x.key)) |> add ans) (i+1)
    in
    go ans (l+1), xi
  ) (0L,-1)
  |> fst |> Printf.printf "%Ld\n"

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

let lbound a n x =
  let rec go l h =
    if l >= h then
      l
    else
      let m = (l+h)/2 in
      if a.(m) < x then
        go (m+1) h
      else
        go l m
  in go 0 n

let () =
  let n = read_int 0 in
  let a = Array.init n read_int in
  let b = Array.copy a in
  Array.sort compare b;
  for i = 0 to n-1 do
    a.(i) <- lbound b n a.(i)
  done;

  let s = Array.make_matrix 2 n 0L in
  for i = 0 to n-1 do
    s.(0).(i) <- if a.(0) <= i then 0L else b.(a.(0))-b.(i) |> Int64.of_int
  done;
  for i = 1 to n-1 do
    let cur = i land 1 in
    let pre = 1-cur in
    for j = 0 to n-1 do
      s.(cur).(j) <- Int64.add s.(pre).(j) (b.(a.(i))-b.(j) |> abs |> Int64.of_int)
    done;
    for j = 1 to n-1 do
      s.(cur).(j) <- min s.(cur).(j) s.(cur).(j-1)
    done
  done;
  Printf.printf "%Ld\n" s.((n-1) land 1).(n-1)

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

let lbound a n x =
  let rec go l h =
    if l >= h then
      l
    else
      let m = (l+h)/2 in
      if a.(m) < x then
        go (m+1) h
      else
        go l m
  in go 0 n

let () =
  let n = read_int 0 in
  let a = Array.init n read_int in
  let b = Array.copy a in
  Array.sort compare b;
  for i = 0 to n-1 do
    a.(i) <- lbound b n a.(i)
  done;

  let s = Array.make_matrix 2 n 0 in
  for i = 0 to n-1 do
    s.(0).(i) <- if a.(0) <= i then 0 else b.(a.(0))-b.(i)
  done;
  for i = 1 to n-1 do
    let cur = i land 1 in
    let pre = 1-cur in
    for j = 0 to n-1 do
      s.(cur).(j) <- s.(pre).(j) + abs (b.(a.(i))-b.(j))
    done;
    for j = 1 to n-1 do
      s.(cur).(j) <- min s.(cur).(j) s.(cur).(j-1)
    done
  done;
  Printf.printf "%d\n" s.((n-1) land 1).(n-1)

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

type node = {key: int; child: node; sibling: node}

let rec nil = {key = min_int; child = nil; sibling = nil}
let is_nil a = a.key = min_int

let merge a b =
  if a.key > b.key then
    {a with child = {b with sibling = a.child}}
  else
    {b with child = {a with sibling = b.child}}

let merge_list x =
  let rec go acc x =
    if is_nil x then
      acc
    else
      let y = {x with sibling = nil} in
      if is_nil x.sibling then
        y::acc
      else
        let z = {x.sibling with sibling = nil} in
        go (merge y z::acc) x.sibling.sibling
  in
  match go [] x with
  | [] -> nil
  | u::us -> List.fold_left (fun u v -> merge u v) u us

let pop x = merge_list x.child

let singleton k = {key = k; child = nil; sibling = nil}

let push x k = merge x {key = k; child = nil; sibling = nil}

let print x =
  let rec go d x =
    if not (is_nil x) then (
      go (d+1) x.sibling;
      for i = 1 to d do print_string "  " done;
      Printf.printf "%d\n" x.key;
      go (d+1) x.child;
    )
  in go 0 x

let () =
  let n = read_int 0 in
  let a = Array.init n read_int in
  let rec go st i =
    if i >= n then
      st
    else
      let rec f = function
        | (y,yi)::(x,xi)::xs when x.key > y.key ->
          let z = merge x y in
          let z = if (xi-(if xs=[] then -1 else (List.hd xs |> snd))) land 1 <> 0 &&
                (yi-xi) land 1 <> 0 then pop z else z in
          f ((z,yi)::xs)
        | st -> st
      in
      let st' = f st in
      go ((singleton a.(i),i) :: st') (i+1)
  in

  (*Printf.printf "+ len: %d\n" (List.length st);*)
  (*Printf.printf "+++++++++\n";*)
  (*List.nth st 0 |> snd |> Printf.printf "%d\n";*)
  (*Printf.printf "+++++++++\n";*)
  (*List.nth st 1 |> snd |> Printf.printf "%d\n";*)
  (*Printf.printf "+++++++++\n";*)
  (*List.nth st 2 |> snd |> Printf.printf "%d\n";*)
  go [] 0
  |> List.rev
  |> List.fold_left (fun (ans,l) (x,xi) ->
    let rec go ans i =
      if i > xi then
        ans
      else
        let open Int64 in
        go (abs (sub (of_int a.(i)) (of_int x.key)) |> add ans) (i+1)
    in
    go ans (l+1), xi
  ) (0L,-1)
  |> fst |> Printf.printf "%Ld\n"


Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill:   the graph contains exactly 2n + p edges;  the graph doesn't contain self-loops and multiple edges;  for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges. A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices. Your task is to find a p-interesting graph consisting of n vertices.

The first line contains a single integer t (1 ≤ t ≤ 5) — the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 ≤ n ≤ 24; p ≥ 0; ) — the number of vertices in the graph and the interest value for the appropriate test.  It is guaranteed that the required graph exists.

For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n.  Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them.

open Printf
open Scanf

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

let solve n p =
  let m = 2*n + p in
  let a = Array.make m (0,0) in
  let k = ref 0 in
  let add_edge e =
    a.(!k) <- e;
    k := !k + 1
  in
  for i=0 to n-1 do
    add_edge (i, (i+1) mod n);
    add_edge (i, (i+2) mod n);
  done;

  let delta = ref 3 in
  for i=0 to p-1 do
    add_edge (i mod n, (i + !delta) mod n);
    if (i+1) mod n = 0 then delta := !delta+1
  done;
  a

let () =
  let t = read_int () in
  for case = 1 to t do
    let n = read_int() in
    let p = read_int() in
    let a = solve n p in
    for i=0 to 2*n+p-1 do
      let (a,b) = a.(i) in
      printf "%d %d\n" (a+1) (b+1)
    done
  done

open Printf
open Scanf

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

let solve n p =
  let m = 2*n + p in
  let a = Array.make m (0,0) in
  let k = ref 0 in
  let add_edge e =
    a.(!k) <- e;
    k := !k + 1
  in
  for i=0 to n-1 do
    add_edge (i, (i+1) mod n);
    add_edge (i, (i+2) mod n);
  done;

  let delta = ref 3 in
  for i=0 to p-1 do
    add_edge (i mod n, (i + !delta) mod n);
    if i mod n = 0 then delta := !delta+1
  done;
  a

let () =
  let t = read_int () in
  for case = 1 to t do
    let n = read_int() in
    let p = read_int() in
    let a = solve n p in
    for i=0 to 2*n+p-1 do
      let (a,b) = a.(i) in
      printf "%d %d\n" (a+1) (b+1)
    done
  done

open Printf
open Scanf

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

let solve n p =
  let m = 2*n + p in
  let a = Array.make m (0,0) in
  let k = ref 0 in
  let add_edge e =
    a.(!k) <- e;
    k := !k + 1
  in
  for i=0 to n-1 do
    add_edge (i, (i+1) mod n);
    add_edge (i, (i+2) mod n);
  done;

  for i=0 to p-1 do
    add_edge (i, (i+3) mod n);
  done;
  a

let () =
  let t = read_int () in
  for case = 1 to t do
    let n = read_int() in
    let p = read_int() in
    let a = solve n p in
    for i=0 to 2*n+p-1 do
      let (a,b) = a.(i) in
      printf "%d %d\n" (a+1) (b+1)
    done
  done


You are given a directed graph G with n vertices and m arcs (multiple arcs and self-loops are allowed). You have to paint each vertex of the graph into one of the k (k ≤ n) colors in such way that for all arcs of the graph leading from a vertex u to vertex v, vertex v is painted with the next color of the color used to paint vertex u.The colors are numbered cyclically 1 through k. This means that for each color i (i < k) its next color is color i + 1. In addition, the next color of color k is color 1. Note, that if k = 1, then the next color for color 1 is again color 1.Your task is to find and print the largest possible value of k (k ≤ n) such that it's possible to color G as described above with k colors. Note that you don't necessarily use all the k colors (that is, for each color i there does not necessarily exist a vertex that is colored with color i).

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105), denoting the number of vertices and the number of arcs of the given digraph, respectively. Then m lines follow, each line will contain two space-separated integers ai and bi (1 ≤ ai, bi ≤ n), which means that the i-th arc goes from vertex ai to vertex bi. Multiple arcs and self-loops are allowed.

Print a single integer — the maximum possible number of the colors that can be used to paint the digraph (i.e. k, as described in the problem statement). Note that the desired value of k must satisfy the inequality 1 ≤ k ≤ n.

NoteFor the first example, with k = 2, this picture depicts the two colors (arrows denote the next color of that color).  With k = 2 a possible way to paint the graph is as follows.  It can be proven that no larger value for k exists for this test case.For the second example, here's the picture of the k = 5 colors.  A possible coloring of the graph is:  For the third example, here's the picture of the k = 3 colors.  A possible coloring of the graph is:

let rec gcd a b =
  if b = 0
  then a
  else gcd b (a mod b)

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let es = Array.make n [] in
  let () =
    for i = 1 to m do
      let u = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
      let v = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
	es.(u) <- (v, 1) :: es.(u);
	es.(v) <- (u, -1) :: es.(v);
    done;
  in
  let es = Array.map Array.of_list es in
  let used = Array.make n false in
  let a = Array.make n (-1) in
  let res = ref 0 in
  let rec dfs u =
    used.(u) <- true;
    for i = 0 to Array.length es.(u) - 1 do
      let (v, d) = es.(u).(i) in
	if not used.(v) then (
	  a.(v) <- a.(u) + d;
	  dfs v
	) else (
	  res := gcd !res (abs ((a.(u) + d) - a.(v)))
	)
    done;
  in
    for i = 0 to n - 1 do
      if not used.(i) then (
	a.(i) <- 0;
	dfs i
      )
    done;
    if !res = 0
    then res := n;
    Printf.printf "%d\n" !res

let rec gcd a b =
  if b = 0
  then a
  else gcd b (a mod b)

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let es = Array.make n [] in
  let () =
    for i = 1 to m do
      let u = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
      let v = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
	es.(u) <- (v, 1) :: es.(u);
	es.(v) <- (u, -1) :: es.(v);
    done;
  in
  let es = Array.map Array.of_list es in
  let used = Array.make n false in
  let a = Array.make n (-1) in
  let res = ref 0 in
  let pos = ref 0 in
  let stack = Array.make n 0 in
  let rec dfs u =
    used.(u) <- true;
    for i = 0 to Array.length es.(u) - 1 do
      let (v, d) = es.(u).(i) in
	if not used.(v) then (
	  a.(v) <- a.(u) + d;
	  dfs v
	) else (
	  res := gcd !res (abs ((a.(u) + d) - a.(v)))
	)
    done;
  in
  let rec dfs () =
    if !pos > 0 then (
      decr pos;
      let u = stack.(!pos) in
	for i = 0 to Array.length es.(u) - 1 do
	  let (v, d) = es.(u).(i) in
	     if not used.(v) then (
	       a.(v) <- a.(u) + d;
	       stack.(!pos) <- v;
	       incr pos;
	       used.(v) <- true;
	     ) else (
	       res := gcd !res (abs ((a.(u) + d) - a.(v)))
	     )
	done;
	dfs ()
    )
  in
    for i = 0 to n - 1 do
      if not used.(i) then (
	a.(i) <- 0;
	pos := 0;
	stack.(!pos) <- i;
	incr pos;
	used.(i) <- true;
	dfs ()
      )
    done;
    if !res = 0
    then res := n;
    Printf.printf "%d\n" !res


You are given a graph with $$$n$$$ nodes and $$$m$$$ directed edges. One lowercase letter is assigned to each node. We define a path's value as the number of the most frequently occurring letter. For example, if letters on a path are "abaca", then the value of that path is $$$3$$$. Your task is find a path whose value is the largest.

The first line contains two positive integers $$$n, m$$$ ($$$1 \leq n, m \leq 300\,000$$$), denoting that the graph has $$$n$$$ nodes and $$$m$$$ directed edges. The second line contains a string $$$s$$$ with only lowercase English letters. The $$$i$$$-th character is the letter assigned to the $$$i$$$-th node. Then $$$m$$$ lines follow. Each line contains two integers $$$x, y$$$ ($$$1 \leq x, y \leq n$$$), describing a directed edge from $$$x$$$ to $$$y$$$. Note that $$$x$$$ can be equal to $$$y$$$ and there can be multiple edges between $$$x$$$ and $$$y$$$. Also the graph can be not connected.

Output a single line with a single integer denoting the largest value. If the value can be arbitrarily large, output -1 instead.

NoteIn the first sample, the path with largest value is $$$1 \to 3 \to 4 \to 5$$$. The value is $$$3$$$ because the letter 'a' appears $$$3$$$ times.

let n, m = Scanf.scanf " %d %d" (fun x y -> x, y);;
let node = Scanf.scanf " %s" (fun x -> x);;
let adjs = Array.make (n + 1) [];;
let etat = Array.make (n + 1) 0;;
let maxi = Array.make_matrix (n + 1) 26 0;;

for i = 1 to m do
  let u, v = Scanf.scanf " %d %d" (fun x y -> x, y) in
  adjs.(u) <- v :: adjs.(u);
done;;

let rec cycle u =
  match etat.(u) with
  | 1 -> true
  | 2 -> false
  | _ ->
      etat.(u) <- 1;
      let x = List.fold_left (fun x v -> x || cycle v) false adjs.(u) in
      etat.(u) <- 2;
      x;;

let rec calculer u =
  let aux v =
    calculer v;
    let f i x =
      maxi.(u).(i) <- max maxi.(u).(i) x in
    Array.iteri f maxi.(v) in
  if etat.(u) = 0 then (
    etat.(u) <- 1;
    List.iter aux adjs.(u);
    let i = int_of_char node.[u - 1] - int_of_char 'a' in
    maxi.(u).(i) <- maxi.(u).(i) + 1
  );;

let cyclique = ref false in
for u = 1 to n do
  cyclique := !cyclique || cycle u;
done;
if !cyclique then
  print_int (-1)
else (
  Array.fill etat 0 (Array.length etat) 0;
  let r = ref 0 in
  for u = 1 to n do
    calculer u;
    r := max !r (Array.fold_left max 0 maxi.(u));
  done;
  print_int !r
);;

let n, m = Scanf.scanf " %d %d" (fun x y -> x, y);;
let label = Scanf.scanf " %s" (fun x -> x);;
let adjs = Array.make (n + 1) [];;
let etat = Array.make (n + 1) 0;;
let maxi = Array.make_matrix (n + 1) 26 0;;

for i = 1 to m do
  let u, v = Scanf.scanf " %d %d" (fun x y -> x, y) in
  adjs.(u) <- v :: adjs.(u);
done;;

let rec cycle u =
  match etat.(u) with
  | 1 -> true
  | 2 -> false
  | _ ->
      etat.(u) <- 1;
      let x = List.fold_left (fun x v -> x || cycle v) false adjs.(u) in
      etat.(u) <- 2;
      x;;

let rec calculer u =
  let aux v =
    calculer v;
    let f i x =
      maxi.(u).(i) <- max maxi.(u).(i) x in
    Array.iteri f maxi.(v) in
  if etat.(u) = 0 then (
    etat.(u) <- 1;
    List.iter aux adjs.(u);
    let i = int_of_char label.[u - 1] - int_of_char 'a' in
    maxi.(u).(i) <- maxi.(u).(i) + 1
  );;

let cyclique = ref false in
for u = 1 to n do
  cyclique := !cyclique || cycle u;
done;
if !cyclique then
  print_int (-1)
else (
  Array.fill etat 0 (Array.length etat) 0;
  let r = ref 0 in
  for u = 1 to n do
    calculer u;
    r := max !r (Array.fold_left max 0 maxi.(u));
  done;
  print_int !r
);;


Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas). Vasya has come up with an algorithm he will follow while writing a letter. First he chooses two strings, s1 anf s2, consisting of uppercase English letters. Then the boy makes string sk, using a recurrent equation sn = sn - 2 + sn - 1, operation '+' means a concatenation (that is, the sequential record) of strings in the given order. Then Vasya writes down string sk on a piece of paper, puts it in the envelope and sends in to Santa. Vasya is absolutely sure that Santa will bring him the best present if the resulting string sk has exactly x occurrences of substring AC (the short-cut reminds him оf accepted problems). Besides, Vasya decided that string s1 should have length n, and string s2 should have length m. Vasya hasn't decided anything else.At the moment Vasya's got urgent New Year business, so he asks you to choose two strings for him, s1 and s2 in the required manner. Help Vasya.

The first line contains four integers k, x, n, m (3 ≤ k ≤ 50; 0 ≤ x ≤ 109; 1 ≤ n, m ≤ 100).

In the first line print string s1, consisting of n uppercase English letters. In the second line print string s2, consisting of m uppercase English letters. If there are multiple valid strings, print any of them. If the required pair of strings doesn't exist, print "Happy new year!" without the quotes.

(* Okay, never mind coding this up.  But here's how you do it.

   WLOG There are only three choices for the beginning and ending of
   s1 and s2.  Namely A, C, or X.  So there are 81 possibilities for
   these.  We run through each of these.

   Given the above choices, we compute for s1 the maximum number of
   ACs that can occur inside of s1.  (The minimum number can be zero.)
   Call this number A.  A is bounded by 50.

   Now we simulate computing the recurrence for k iterations.  I say
   "simulate" because for each string s_i we compute, we need to know
   what the 3 options for the first char, the 3 options for the last
   char, and the number of ACs that occur inside of it.  This can be
   done in O(1) time per iteration.

   Actually we're going to keep track of the number of ACs that occur
   in s_k in terms of A, the number of ACs inside of s1 and B the
   number of ACs inside of s2.  So in order for there to be the right
   number of ACs we have an equation like this: k*A + l*B = c.  The
   upper case letters are variables, the lower case letters are
   constants.  In order to test if this has a solution we can simply
   run through all the values of, say, A, and for each see in O(1) time
   if there's an appropriate B.

   Anyway, at the end of the day, the running time is going to be
   something on the order of 81*50.  So it's very fast.

*)

open Printf
open Scanf

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

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

let () =
  let k = read_int () in
  let x = Int64.of_int (read_int ()) in
  let len1 = read_int () in
  let len2 = read_int () in

  let cat (s1,a1,b1,c1,e1) (s2,a2,b2,c2,e2) =
    (* concatenate string1 to string2 *)
    let inc = if (e1,s2) = ('A','C') then 1L else 0L in
    (s1, a1++a2, b1++b2, c1++c2++inc, e2)
  in

  let rec iterate k s1 s2 = if k=0 then s1
    else iterate (k-1) s2 (cat s1 s2)
  in

  let sk s1 s2 = iterate (k-1) s1 s2 in

  let solvable (_,a,b,c,_) lo1 hi1 lo2 hi2 =
    let works = ref None in
    for i=lo1 to hi1 do
      for j=lo2 to hi2 do
	let (i',j') = (Int64.of_int i, Int64.of_int j) in
	if x = a**i' ++ b**j' ++ c then works := Some (i,j)
      done
    done;
    !works
  in

  let rec make_options i = if i=4 then [[]] else
      let prepend x = List.map (fun li -> x::li) (make_options (i+1)) in
      (prepend 'A') @ (prepend 'C') @ (prepend 'X')
  in

  (* make_options 0 is [['A'; 'A'; 'A'; 'A']; ['A'; 'A'; 'A'; 'C']; ['A'; 'A'; 'A'; 'X']; ... *)

  let bounds (s,_,_,_,e) len =
    match (len,s,e) with
      | (0,_,_) -> failwith "illegal length"
      | (1,_,_) -> (0,0)
      | (2,'A','C') -> (1, 1)
      | (2, _ , _ ) -> (0, 0)
      | (_,'A','C') -> (0, len/2)
      | (_, _ ,'C') -> (0, (len-1)/2)
      | (_,'A', _ ) -> (0, (len-1)/2)
      | (_, _ , _ ) -> (0, (len-2)/2)
  in

  let solve_options options =
    let o i = List.nth options i in
    let s1 = (o 0, 1L, 0L, 0L, o 1) in
    let s2 = (o 2, 0L, 1L, 0L, o 3) in

    if (len1=1 && o 0 <> o 1) || (len2=1 && o 2 <> o 3) then None else
      let s = sk s1 s2 in
      let (lo1,hi1) = bounds s1 len1 in
      let (lo2,hi2) = bounds s2 len2 in
      solvable s lo1 hi1 lo2 hi2
  in

  let rec find_option = function
    | [] -> None
    | h::t ->
      match solve_options h with
	| None -> find_option t
	| Some (i,j) -> Some (h,i,j)
  in

  let gen_string (s,len,ac_count,e) =
    let str = String.make len 'X' in
    str.[0] <- s;
    str.[len-1] <- e;
    let st = if s = 'A' then 0 else 1 in
    for i = 0 to 2*ac_count-1 do
      str.[i+st] <- if i land 1 = 0 then 'A' else 'C'
    done;
    str
  in

  match find_option (make_options 0) with
    | None -> printf "Happy new year!\n"
    | Some (options,i,j) ->
      let o i = List.nth options i in
      printf "%s\n" (gen_string (o 0, len1, i, o 1));
      printf "%s\n" (gen_string (o 2, len2, j, o 3));


Colonel has n badges. He wants to give one badge to every of his n soldiers. Each badge has a coolness factor, which shows how much it's owner reached. Coolness factor can be increased by one for the cost of one coin. For every pair of soldiers one of them should get a badge with strictly higher factor than the second one. Exact values of their factors aren't important, they just need to have distinct factors. Colonel knows, which soldier is supposed to get which badge initially, but there is a problem. Some of badges may have the same factor of coolness. Help him and calculate how much money has to be paid for making all badges have different factors of coolness.

First line of input consists of one integer n (1 ≤ n ≤ 3000). Next line consists of n integers ai (1 ≤ ai ≤ n), which stand for coolness factor of each badge.

Output single integer — minimum amount of coins the colonel has to pay.

NoteIn first sample test we can increase factor of first badge by 1.In second sample test we can increase factors of the second and the third badge by 1.

let (|>) x f = f x
let ($) f g = fun x -> f (g x)

let solve a =
  let arr = Array.make 10000 0 in
  List.iter
    (fun x -> arr.(x) <- arr.(x) + 1)
    a;
  let res = ref 0 in
  Array.iteri
    (fun i x ->
       if x > 1 then
         (res := !res + x - 1;
          arr.(i + 1) <- arr.(i + 1) + x - 1))
    arr;
  !res

let _ =
  ignore (read_int ());
  let a =
    read_line ()
    |> Str.split (Str.regexp " ")
    |> List.map int_of_string
  in
  print_endline (string_of_int (solve a))

let f tab =
	let res = ref 0 in
	for i=0 to Array.length tab - 2 do
		if tab.(i) > 1
			then begin
				let trop = tab.(i) - 1 in
					tab.(i) <- 1;
					tab.(i+1) <- tab.(i+1) + trop;
					res := trop + !res;
			     end

	done;
	!res

let _ =
	let tab = Array.make 6015 0 and n = Scanf.scanf "%d" (fun i -> i) in
	for i=1 to n do
		Scanf.scanf " %d" (fun j -> tab.(j) <- tab.(j) + 1);
	done;
	Printf.printf "%d" (f tab)


SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is  for SmallR while  for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.

Print a single real number, the probability that SmallR will win the match. The answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.

(* Codeforces contest 300D - Draw Squares - Too slow *)

open Filename;;

(* you can use either gr or rdln but not both *)
let use_input_txt = false;;
let fn = (Filename.dirname Filename.current_dir_name);;
let filename = Filename.concat "." "input.txt";;
let cin = if use_input_txt then Scanf.Scanning.open_in filename
	else Scanf.Scanning.stdin;;

let cout = open_out "output.txt";;
let gr () = Scanf.bscanf cin " %d" (fun i -> i);;
let grf () = Scanf.scanf " %f" (fun i -> i);;
let grl () = Scanf.scanf " %Ld" (fun i -> i);;
let rdln() = input_line Pervasives.stdin;;
(* let spli s = Str.split (Str.regexp " ") s;; *)
let printlisti li = List.iter (fun i -> (print_int i; print_string " ")) li;;
let printlisti64 li = List.iter (fun i -> (print_string (Int64.to_string i); print_string " ")) li;;
let printarri ai = Array.iter (fun i -> (print_int i; print_string " ")) ai;;
let rec readlist n acc = match n with | 0 -> List.rev acc | _ -> readlist (n -1) (gr() :: acc);;
let rec readpairs n acc = match n with
	| 0 -> List.rev acc
	| _ -> readpairs
				(n -1)
				(
					let a = gr() in
					let b = gr() in
					(* let _ = Printf.printf "a,b = %d %d\n" a b in *)
					(a, b) :: acc
				);;
let debug = false;;

let a = gr();;  (* number of test data *)
let b = gr();;  (* number of test data *)
let c = gr();;  (* number of test data *)
let d = gr();;  (* number of test data *)

let main() =
    let af = float_of_int a in
    let bf = float_of_int b in
    let cf = float_of_int c in
    let df = float_of_int d in

	let adf = af *. df in
	let acaf = (af *. df) +. (cf *. bf) -. (af *. cf) in
	let pp = adf /. acaf in
	Printf.printf "%18.12f" pp;;

main();;

(* For the first archer to win, the possibilities are
 * win(a) - lose(a) & lose(b) & win(a)...*)

let main =
  let (a, b, c, d) = Scanf.scanf "%f %f %f %f\n" (fun a b c d -> (a,b,c,d)) in
  let p_win = a /. b in
  let p_retry = (1. -. p_win) *. (1. -. (c /. d)) in
  let result = p_win /. (1. -. p_retry) in
    Printf.printf "%f\n" result


Igor is in the museum and he wants to see as many pictures as possible.Museum can be represented as a rectangular field of n × m cells. Each cell is either empty or impassable. Empty cells are marked with '.', impassable cells are marked with '*'. Every two adjacent cells of different types (one empty and one impassable) are divided by a wall containing one picture.At the beginning Igor is in some empty cell. At every moment he can move to any empty cell that share a side with the current one.For several starting positions you should calculate the maximum number of pictures that Igor can see. Igor is able to see the picture only if he is in the cell adjacent to the wall with this picture. Igor have a lot of time, so he will examine every picture he can see.

First line of the input contains three integers n, m and k (3 ≤ n, m ≤ 1000, 1 ≤ k ≤ min(n·m, 100 000)) — the museum dimensions and the number of starting positions to process. Each of the next n lines contains m symbols '.', '*' — the description of the museum. It is guaranteed that all border cells are impassable, so Igor can't go out from the museum. Each of the last k lines contains two integers x and y (1 ≤ x ≤ n, 1 ≤ y ≤ m) — the row and the column of one of Igor's starting positions respectively. Rows are numbered from top to bottom, columns — from left to right. It is guaranteed that all starting positions are empty cells.

Print k integers — the maximum number of pictures, that Igor can see if he starts in corresponding position.

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make_matrix n m false in
    for i = 0 to n - 1 do
      let s = Scanf.bscanf sb "%s " (fun s -> s) in
	for j = 0 to m - 1 do
	  a.(i).(j) <- s.[j] = '.'
	done
    done;
    let res = Array.make (n * m) (-1) in
    let cnt = ref 0 in
    let c = Array.make_matrix n m (-1) in
    let color = ref 0 in
    let q1 = Array.make (n * m) (0, 0) in
    let l1 = ref 0 in
    let q2 = Array.make (n * m) (0, 0) in
    let l2 = ref 0 in
    let d = [| (-1, 0); (1, 0); (0, 1); (0, -1) |] in
    let rec bfs_step k q1 l1 q2 l2 =
      l2 := 0;
      for i = 0 to !l1 - 1 do
	let (x, y) = q1.(i) in
	  for i = 0 to 3 do
	    let (dx, dy) = d.(i) in
	    let x = x + dx
	    and y = y + dy in
	      if x >= 0 && y >= 0 && x < m && y < n && a.(y).(x) then (
		if c.(y).(x) < 0 then (
		  c.(y).(x) <- !color;
		  q2.(!l2) <- (x, y);
		  incr l2
		);
	      ) else incr cnt;
	  done
      done;
      if !l2 > 0
      then bfs_step (k + 1) q2 l2 q1 l1
    in
      for y = 0 to n - 1 do
	for x = 0 to m - 1 do
	  if a.(y).(x) && c.(y).(x) < 0 then (
	    cnt := 0;
	    c.(y).(x) <- !color;
	    l1 := 0;
	    l2 := 0;
	    q1.(!l1) <- (x, y);
	    incr l1;
	    bfs_step 1 q1 l1 q2 l2;
	    res.(!color) <- !cnt;
	    incr color;
	  )
	done
      done;
	for i = 1 to k do
	  let y = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
	  let x = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
	    Printf.printf "%d\n" res.(c.(y).(x))
	done;