Easy and hard versions are actually different problems, so read statements of both problems completely and carefully.Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will read each book together to end this exercise faster.There are $$$n$$$ books in the family library. The $$$i$$$-th book is described by three integers: $$$t_i$$$ — the amount of time Alice and Bob need to spend to read it, $$$a_i$$$ (equals $$$1$$$ if Alice likes the $$$i$$$-th book and $$$0$$$ if not), and $$$b_i$$$ (equals $$$1$$$ if Bob likes the $$$i$$$-th book and $$$0$$$ if not).So they need to choose some books from the given $$$n$$$ books in such a way that:  Alice likes at least $$$k$$$ books from the chosen set and Bob likes at least $$$k$$$ books from the chosen set;  the total reading time of these books is minimized (they are children and want to play and joy as soon a possible). The set they choose is the same for both Alice an Bob (it's shared between them) and they read all books together, so the total reading time is the sum of $$$t_i$$$ over all books that are in the chosen set.Your task is to help them and find any suitable set of books or determine that it is impossible to find such a set.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$). The next $$$n$$$ lines contain descriptions of books, one description per line: the $$$i$$$-th line contains three integers $$$t_i$$$, $$$a_i$$$ and $$$b_i$$$ ($$$1 \le t_i \le 10^4$$$, $$$0 \le a_i, b_i \le 1$$$), where:   $$$t_i$$$ — the amount of time required for reading the $$$i$$$-th book;  $$$a_i$$$ equals $$$1$$$ if Alice likes the $$$i$$$-th book and $$$0$$$ otherwise;  $$$b_i$$$ equals $$$1$$$ if Bob likes the $$$i$$$-th book and $$$0$$$ otherwise.

If there is no solution, print only one integer -1. Otherwise print one integer $$$T$$$ — the minimum total reading time of the suitable set of books.

module A = Array
module C = Char
module I = Int64
module L = List
module Q = Queue
module S = String

let pf = Printf.printf
let sf = Scanf.scanf
let ssf = Scanf.sscanf

let l_init n f =
  let rec loop acc i =
    if i >= n then acc else loop ((f i) :: acc) (i+1)
  in List.rev (loop [] 0)

let read_int () = sf "%d " (fun x -> x)
let read_int64 () = sf "%Ld " (fun x -> x)
let read_float () = sf "%f " (fun x -> x)
let read_list read n = l_init n (fun _ -> read ())
let read_array read n = A.init n (fun _ -> read ())
let err s = raise (Failure s)

let l_take_opt n l =
  let rec loop acc i = function
    | _ when i = n -> Some (L.rev acc)
    | hd::tl -> loop (hd::acc) (succ i) tl
    | [] -> None
  in loop [] 0 l

let inf = int_of_float 1e18
let eps = 1e-11

let map2_min f l1 l2 =
  let rec loop acc = function
  | (_, []) | ([], _) -> acc
  | (a1::l1, a2::l2) -> loop ((f a1 a2)::acc) (l1, l2)
  in loop [] (l1, l2)

let read_book () =
  let t = read_int64() in
  let a = read_int() in
  let b = read_int() in
  (t, a, b)

let partition books =
  let rec loop common_ts alice_ts bob_ts = function
    | [] -> common_ts, alice_ts, bob_ts
    | (t, a, b)::tl when a = 1 && b = 1 -> loop (t::common_ts) alice_ts bob_ts tl
    | (t, a, b)::tl when a = 1 -> loop common_ts (t::alice_ts) bob_ts tl
    | (t, a, b)::tl when b = 1 -> loop common_ts alice_ts (t::bob_ts) tl
    | _ -> assert false
  in loop [] [] [] books

let ranked_times (ts, a_ts, b_ts) =
  map2_min I.add (L.sort I.compare a_ts) (L.sort I.compare b_ts)
  |> L.append ts
  |> L.sort I.compare

let solve k ts =
  match l_take_opt k ts with
  | None -> -1L
  | Some selection -> L.fold_left I.add 0L selection

let () =
  let rec loop () =
    try let n = read_int() in
        let k = read_int() in
        (read_list read_book n)
        |> L.filter (fun (_, a, b) -> (a != 0) || (b != 0))
        |> partition
        |> ranked_times
        |> solve k
        |> pf "%Ld\n";
        loop ()
    with End_of_file -> ()
  in loop ()

module A = Array
module C = Char
module I = Int64
module L = List
module Q = Queue
module S = String

let pf = Printf.printf
let sf = Scanf.scanf
let ssf = Scanf.sscanf

let l_init n f =
  let rec loop acc i =
    if i >= n then acc else loop ((f i) :: acc) (i+1)
  in List.rev (loop [] 0)

let read_int () = sf "%d " (fun x -> x)
let read_int64 () = sf "%ld " (fun x -> x)
let read_float () = sf "%f " (fun x -> x)
let read_list read n = l_init n (fun _ -> read ())
let read_array read n = A.init n (fun _ -> read ())
let err s = raise (Failure s)

let l_take_opt n l =
  let rec loop acc i = function
    | _ when i = n -> Some (L.rev acc)
    | hd::tl -> loop (hd::acc) (succ i) tl
    | [] -> None
  in loop [] 0 l

let inf = int_of_float 1e18
let eps = 1e-11

let map2_min f l1 l2 =
  let rec loop acc = function
  | (_, []) | ([], _) -> acc
  | (a1::l1, a2::l2) -> loop ((f a1 a2)::acc) (l1, l2)
  in loop [] (l1, l2)

let read_book () =
  let t = read_int() in
  let a = read_int() in
  let b = read_int() in
  (t, a, b)

let partition books =
  let rec loop common_ts alice_ts bob_ts = function
    | [] -> common_ts, alice_ts, bob_ts
    | (t, a, b)::tl when a = 1 && b = 1 -> loop (t::common_ts) alice_ts bob_ts tl
    | (t, a, b)::tl when a = 1 -> loop common_ts (t::alice_ts) bob_ts tl
    | (t, a, b)::tl when b = 1 -> loop common_ts alice_ts (t::bob_ts) tl
    | _ -> assert false
  in loop [] [] [] books

let ranked_times (ts, a_ts, b_ts) =
  map2_min (fun i j -> i + j) (L.sort compare a_ts) (L.sort compare b_ts)
  |> L.append ts
  |> L.sort compare

let solve k ts =
  match l_take_opt k ts with
  | None -> -1
  | Some selection -> L.fold_left (fun i j -> i + j) 0 selection

let () =
  let rec loop () =
    try let n = read_int() in
        let k = read_int() in
        (read_list read_book n)
        |> L.filter (fun (_, a, b) -> (a != 0) || (b != 0))
        |> partition
        |> ranked_times
        |> solve k
        |> pf "%d\n";
        loop ()
    with End_of_file -> ()
  in loop ()


A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000.This new device is equipped with specially designed artificial intelligence (AI). Employees of Pineapple did their best to postpone the release of Lastus 3000 as long as possible. Finally, they found out, that the name of the new artificial intelligence is similar to the name of the phone, that Pineapple released 200 years ago. As all rights on its name belong to Pineapple, they stand on changing the name of Gogol's artificial intelligence.Pineapple insists, that the name of their phone occurs in the name of AI as a substring. Because the name of technology was already printed on all devices, the Gogol's director decided to replace some characters in AI name with "#". As this operation is pretty expensive, you should find the minimum number of characters to replace with "#", such that the name of AI doesn't contain the name of the phone as a substring.Substring is a continuous subsequence of a string.

The first line of the input contains the name of AI designed by Gogol, its length doesn't exceed 100 000 characters. Second line contains the name of the phone released by Pineapple 200 years ago, its length doesn't exceed 30. Both string are non-empty and consist of only small English letters.

Print the minimum number of characters that must be replaced with "#" in order to obtain that the name of the phone doesn't occur in the name of AI as a substring.

NoteIn the first sample AI's name may be replaced with "int#llect".In the second sample Gogol can just keep things as they are.In the third sample one of the new possible names of AI may be "s#ris#ri".

(* started at 8:08 *)

open Printf
open Scanf

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

let () =
  let text = read_string () in
  let pat = read_string () in

  let n = String.length text in
  let m = String.length pat in

  let answer =
    if m > n then 0 else
      let rec loop c i = if i+m-1 > n-1 then c else
	  let e = String.sub text i m in
	  if pat = e then loop (c+1) (i+m) else loop c (i+1)
      in
      loop 0 0
  in

  printf "%d\n" answer


Sereja has an array a, consisting of n integers a1, a2, ..., an. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l1, l2, ..., lm (1 ≤ li ≤ n). For each number li he wants to know how many distinct numbers are staying on the positions li, li + 1, ..., n. Formally, he want to find the number of distinct numbers among ali, ali + 1, ..., an.?Sereja wrote out the necessary array elements but the array was so large and the boy was so pressed for time. Help him, find the answer for the described question for each li.

The first line contains two integers n and m (1 ≤ n, m ≤ 105). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the array elements. Next m lines contain integers l1, l2, ..., lm. The i-th line contains integer li (1 ≤ li ≤ n).

Print m lines — on the i-th line print the answer to the number li.

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

let () =
	let n = read_int ()
	and m = read_int () in
	let a = Array.init n read_int in

	let vis = Array.make 100001 false
	and suf = Array.make (n + 1) 0 in

	for i = n - 1 downto 0 do
		let x = a.(i) in
		suf.(i) <- suf.(i + 1);
		if not vis.(x) then suf.(i) <- suf.(i) + 1;
		vis.(x) <- true
	done;
	for i = 1 to m do
		let l = read_int () in
		printf "%d\n" suf.(l - 1)
	done

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

let n = read_int() and m = read_int() in
let a = Array.init n (fun _ -> read_int()) in
let e = Array.init 100001 (fun _ -> false) in
let b = Array.make n 0 in

b.(n-1) <- 1;
e.(a.(n-1)) <- true;

for i = n-2 downto 0 do
  b.(i) <- b.(i+1);
  if not e.(a.(i)) then
  begin
    e.(a.(i)) <- true;
    b.(i) <- b.(i) + 1;
  end
done;

for i = 1 to m do
  let l = read_int() in
    Printf.printf "%d\n" b.(l-1);
done;

let read_int _ = Scanf.bscanf Scanf.Scanning.stdib " %d " (fun x -> x);;
let print_int x = Printf.printf "%d\n" x;;

let () =
  let n = read_int() in
  let m = read_int() in
  let a = Array.init n read_int in
  let dp = Array.make n 0 in
  let check = Array.make 100000 0 in
  check.(a.(n-1) - 1) <- 1;
  dp.(n-1) <- 1;
  let rec loop = function
    | k -> (if check.(a.(k)-1) = 0
            then
              (check.(a.(k)-1) <- 1;
              dp.(k) <- dp.(k+1) + 1)
            else
              dp.(k) <- dp.(k+1));
           if k > 0 then loop (k-1);
           in
  let rec loop2 = function
    | k when k = m -> ()
    | k -> let t = read_int 0 in
    print_int dp.(t-1); loop2 (k+1) in
  if n > 1 then loop (n-2);
  loop2 0;;

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

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

	let tab = Array.make n 0
	and uzyte = Array.make 100007 false
	and dp = Array.make (n + 1) 0 in

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

	for i = n - 1 downto 0 do
		if uzyte.(tab.(i)) = false then
			dp.(i) <- dp.(i + 1) + 1
		else
			dp.(i) <-  dp.(i + 1);

		uzyte.(tab.(i)) <- true;
	done;

	for i = 1 to m do
		let a = read_int () in
		printf "%d\n" dp.(a - 1);
	done;

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

let list_init n f =
    let rec loop i list =
        if i < n
        then
            let element = f(i) in
            loop (i + 1) (element :: list)
        else
            List.rev list
    in loop 0 []

let input () =
    let n = read () in
    let m = read () in
    let arr = Array.init n (fun n -> read ()) in
    let list = list_init m (fun n -> read ()) in
    (n, arr, list)

let count_duplicates n arr =
    let seen = Array.make 100001 0 in
    let dup_count = Array.make n 0 in
    let rec loop i count =
        if i >= 0
        then
            let a = arr.(i) in
            if seen.(a) = 0
            then
                (seen.(a) <- 1;
                dup_count.(i) <- count;
                loop (i - 1) count)
            else
                (dup_count.(i) <- count + 1;
                loop (i - 1) (count + 1))
        else
            dup_count
    in loop (n - 1) 0

let count_uniques arr i n list =
    let a = n - i - arr.(i) in
    (a :: list)

let solve (n, arr, list) =
    let dups = count_duplicates n arr in
    let rec loop rest uniqs =
        match rest with
        | (i :: tl) -> loop tl (count_uniques dups (i - 1) n uniqs)
        | [] -> List.rev uniqs
    in loop list []

let print list = List.iter (Printf.printf "%d\n") list

let () = print (solve (input ()))

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

let list_init n f =
    let rec loop i list =
        if i < n
        then
            let element = f(i) in
            loop (i + 1) (element :: list)
        else
            List.rev list
    in loop 0 []

let input () =
    let n = read () in
    let m = read () in
    let arr = Array.init n (fun n -> read ()) in
    let list = list_init m (fun n -> read ()) in
    (n, arr, list)

let count_uniqs n arr =
    let seen = Array.make 100001 0 in
    let uniq_count = Array.make n 0 in
    let rec loop i count =
        if i >= 0
        then
            let a = arr.(i) in
            if seen.(a) = 0
            then
                (seen.(a) <- 1;
                uniq_count.(i) <- count + 1;
                loop (i - 1) (count + 1))
            else
                (uniq_count.(i) <- count;
                loop (i - 1) count)
        else
            uniq_count
    in loop (n - 1) 0

let solve (n, arr, list) =
    let uniqs = count_uniqs n arr in
    List.map (fun i -> uniqs.(i - 1)) list

let print list = List.iter (Printf.printf "%d\n") list

let () = print (solve (input ()))


A picture can be represented as an $$$n\times m$$$ grid ($$$n$$$ rows and $$$m$$$ columns) so that each of the $$$n \cdot m$$$ cells is colored with one color. You have $$$k$$$ pigments of different colors. You have a limited amount of each pigment, more precisely you can color at most $$$a_i$$$ cells with the $$$i$$$-th pigment.A picture is considered beautiful if each cell has at least $$$3$$$ toroidal neighbors with the same color as itself.Two cells are considered toroidal neighbors if they toroidally share an edge. In other words, for some integers $$$1 \leq x_1,x_2 \leq n$$$ and $$$1 \leq y_1,y_2 \leq m$$$, the cell in the $$$x_1$$$-th row and $$$y_1$$$-th column is a toroidal neighbor of the cell in the $$$x_2$$$-th row and $$$y_2$$$-th column if one of following two conditions holds:  $$$x_1-x_2 \equiv \pm1 \pmod{n}$$$ and $$$y_1=y_2$$$, or  $$$y_1-y_2 \equiv \pm1 \pmod{m}$$$ and $$$x_1=x_2$$$. Notice that each cell has exactly $$$4$$$ toroidal neighbors. For example, if $$$n=3$$$ and $$$m=4$$$, the toroidal neighbors of the cell $$$(1, 2)$$$ (the cell on the first row and second column) are: $$$(3, 2)$$$, $$$(2, 2)$$$, $$$(1, 3)$$$, $$$(1, 1)$$$. They are shown in gray on the image below:  The gray cells show toroidal neighbors of $$$(1, 2)$$$. Is it possible to color all cells with the pigments provided and create a beautiful picture?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). The description of the test cases follows. The first line of each test case contains three integers $$$n$$$, $$$m$$$, and $$$k$$$ ($$$3 \leq n,m \leq 10^9$$$, $$$1 \leq k \leq 10^5$$$) — the number of rows and columns of the picture and the number of pigments. The next line contains $$$k$$$ integers $$$a_1,a_2,\dots, a_k$$$ ($$$1 \leq a_i \leq 10^9$$$) — $$$a_i$$$ is the maximum number of cells that can be colored with the $$$i$$$-th pigment. It is guaranteed that the sum of $$$k$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print "Yes" (without quotes) if it is possible to color a beautiful picture. Otherwise, print "No" (without quotes).

NoteIn the first test case, one possible solution is as follows:  In the third test case, we can color all cells with pigment $$$1$$$.

open Printf
open Scanf

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

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

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)
let rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)
let sum i j f = fold i j (fun i a -> (long (f i)) ++ a) 0L

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,m) = read_pair() in
    let k = read_int() in
    let a = Array.init k read_int in

    let possible n m =
      let col c = a.(c)/n in (* number of columns filable by this color *)
      let is_a_big_color = exists 0 (k-1) (fun c -> col c >= 3) in
      let usable_size = sum 0 (k-1) (fun c ->
	let x = col c in if x >= 2 then x else 0
      ) in
      usable_size >= long m && (not (m mod 2 = 1 && (not is_a_big_color)))
    in

    let answer = (possible n m) || (possible m n) in
    if answer then printf "Yes\n" else printf "No\n"
  done

open Printf
open Scanf

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)
let rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)
let sum i j f = fold i j (fun i a -> (f i) + a) 0

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_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,m) = read_pair() in
    let k = read_int() in
    let a = Array.init k read_int in

    let possible n m =
      let col c = a.(c)/n in (* number of columns filable by this color *)
      let is_a_big_color = exists 0 (k-1) (fun c -> col c >= 3) in
      let usable_size = sum 0 (k-1) (fun c ->
	let x = col c in if x >= 2 then x else 0
      ) in
      usable_size >= m && (not (m mod 2 = 1 && (not is_a_big_color)))
    in

    let answer = (possible n m) || (possible m n) in
    if answer then printf "Yes\n" else printf "No\n"
  done


Demiurges Shambambukli and Mazukta love to watch the games of ordinary people. Today, they noticed two men who play the following game.There is a rooted tree on n nodes, m of which are leaves (a leaf is a nodes that does not have any children), edges of the tree are directed from parent to children. In the leaves of the tree integers from 1 to m are placed in such a way that each number appears exactly in one leaf.Initially, the root of the tree contains a piece. Two players move this piece in turns, during a move a player moves the piece from its current nodes to one of its children; if the player can not make a move, the game ends immediately. The result of the game is the number placed in the leaf where a piece has completed its movement. The player who makes the first move tries to maximize the result of the game and the second player, on the contrary, tries to minimize the result. We can assume that both players move optimally well.Demiurges are omnipotent, so before the game they can arbitrarily rearrange the numbers placed in the leaves. Shambambukli wants to rearrange numbers so that the result of the game when both players play optimally well is as large as possible, and Mazukta wants the result to be as small as possible. What will be the outcome of the game, if the numbers are rearranged by Shambambukli, and what will it be if the numbers are rearranged by Mazukta? Of course, the Demiurges choose the best possible option of arranging numbers.

The first line contains a single integer n — the number of nodes in the tree (1 ≤ n ≤ 2·105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n) — the ends of the edge of the tree; the edge leads from node ui to node vi. It is guaranteed that the described graph is a rooted tree, and the root is the node 1.

Print two space-separated integers — the maximum possible and the minimum possible result of the game.

NoteConsider the first sample. The tree contains three leaves: 3, 4 and 5. If we put the maximum number 3 at node 3, then the first player moves there and the result will be 3. On the other hand, it is easy to see that for any rearrangement the first player can guarantee the result of at least 2.In the second sample no matter what the arragment is the first player can go along the path that ends with a leaf with number 3.

open Printf
open Scanf

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

let inf = max_int/2

let () =
  let n = read_int () in

  let tree = Array.make n [] in

  if n=1 then printf "1 1\n" else (

    for i=0 to n-2 do
      let a = read_int()-1 in
      let b = read_int()-1 in
      tree.(a) <- b::tree.(a);
      tree.(b) <- a::tree.(b);
    done;

    let rec count_leaves u p =
      if tree.(u) = [p] then 1
      else List.fold_left (fun t v ->
	if v = p then t else t + (count_leaves v u)
      ) 0 tree.(u)
    in

    let m = count_leaves 0 (-1) in

    let rec dfs0 u p =
      if tree.(u) = [p] then 0
      else List.fold_left (fun t v ->
	if v = p then t else min t (dfs1 v u)
      ) inf tree.(u)
    and dfs1 u p =
      if tree.(u) = [p] then 0
      else List.fold_left (fun t v ->
	if v = p then t else 1 + t + (dfs0 v u)
      ) (-1) tree.(u)
    in

    let r0 = dfs0 0 (-1) in
    let r1 = dfs1 0 (-1) in

    printf "%d %d\n" (m-r0) (r1+1)
  )

open Printf
open Scanf

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

let inf = max_int/2

let () =
  let n = read_int () in

  let tree = Array.make n [] in

  for i=0 to n-2 do
    let a = read_int()-1 in
    let b = read_int()-1 in
    tree.(a) <- b::tree.(a);
    tree.(b) <- a::tree.(b);
  done;

  let rec count_leaves u p =
    if tree.(u) = [p] then 1
    else List.fold_left (fun t v ->
      if v = p then t else t + (count_leaves v u)
    ) 0 tree.(u)
  in

  let m = count_leaves 0 (-1) in

  let rec dfs0 u p =
    if tree.(u) = [p] then 0
    else List.fold_left (fun t v ->
      if v = p then t else min t (dfs1 v u)
    ) inf tree.(u)
  and dfs1 u p =
    if tree.(u) = [p] then 0
    else List.fold_left (fun t v ->
      if v = p then t else 1 + t + (dfs0 v u)
    ) (-1) tree.(u)
  in

  let r0 = dfs0 0 (-1) in
  let r1 = dfs1 0 (-1) in

  printf "%d %d\n" (m-r0) (r1+1)


The Two-dimensional kingdom is going through hard times... This morning the Three-Dimensional kingdom declared war on the Two-dimensional one. This (possibly armed) conflict will determine the ultimate owner of the straight line.The Two-dimensional kingdom has a regular army of n people. Each soldier registered himself and indicated the desired size of the bulletproof vest: the i-th soldier indicated size ai. The soldiers are known to be unpretentious, so the command staff assumes that the soldiers are comfortable in any vests with sizes from ai - x to ai + y, inclusive (numbers x, y ≥ 0 are specified). The Two-dimensional kingdom has m vests at its disposal, the j-th vest's size equals bj. Help mobilize the Two-dimensional kingdom's army: equip with vests as many soldiers as possible. Each vest can be used only once. The i-th soldier can put on the j-th vest, if ai - x ≤ bj ≤ ai + y.

The first input line contains four integers n, m, x and y (1 ≤ n, m ≤ 105, 0 ≤ x, y ≤ 109) — the number of soldiers, the number of vests and two numbers that specify the soldiers' unpretentiousness, correspondingly. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) in non-decreasing order, separated by single spaces — the desired sizes of vests.  The third line contains m integers b1, b2, ..., bm (1 ≤ bj ≤ 109) in non-decreasing order, separated by single spaces — the sizes of the available vests.

In the first line print a single integer k — the maximum number of soldiers equipped with bulletproof vests.  In the next k lines print k pairs, one pair per line, as "ui vi" (without the quotes). Pair (ui, vi) means that soldier number ui must wear vest number vi. Soldiers and vests are numbered starting from one in the order in which they are specified in the input. All numbers of soldiers in the pairs should be pairwise different, all numbers of vests in the pairs also should be pairwise different. You can print the pairs in any order. If there are multiple optimal answers, you are allowed to print any of them.

NoteIn the first sample you need the vests' sizes to match perfectly: the first soldier gets the first vest (size 1), the third soldier gets the second vest (size 3). This sample allows another answer, which gives the second vest to the fourth soldier instead of the third one.In the second sample the vest size can differ from the desired size by at most 2 sizes, so all soldiers can be equipped.

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 x = Scanf.bscanf sb "%ld " (fun s -> s) in
  let y = Scanf.bscanf sb "%ld " (fun s -> s) in
  let a = Array.make n 0l in
  let b = Array.make m 0l in
    for i = 0 to n - 1 do
      let k = Scanf.bscanf sb "%ld " (fun s -> s) in
	a.(i) <- k
    done;
    for i = 0 to m - 1 do
      let k = Scanf.bscanf sb "%ld " (fun s -> s) in
	b.(i) <- k
    done;
    let ai = ref 0 in
    let bi = ref 0 in
    let res = ref [] in
      while !ai < n && !bi < m do
	if Int32.sub a.(!ai) x <= b.(!bi) && b.(!bi) <= Int32.add a.(!ai) y
	then (
	  res := (!ai, !bi) :: !res;
	  incr ai;
	  incr bi;
	) else if Int32.sub a.(!ai) x > b.(!bi)
	then incr bi
	else incr ai
      done;
      let k = List.length !res in
	Printf.printf "%d\n" k;
	List.iter (fun (a, b) -> Printf.printf "%d %d\n" (a + 1) (b + 1)) !res


Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do n chores. Each chore is characterized by a single parameter — its complexity. The complexity of the i-th chore equals hi.As Petya is older, he wants to take the chores with complexity larger than some value x (hi > x) to leave to Vasya the chores with complexity less than or equal to x (hi ≤ x). The brothers have already decided that Petya will do exactly a chores and Vasya will do exactly b chores (a + b = n).In how many ways can they choose an integer x so that Petya got exactly a chores and Vasya got exactly b chores?

The first input line contains three integers n, a and b (2 ≤ n ≤ 2000; a, b ≥ 1; a + b = n) — the total number of chores, the number of Petya's chores and the number of Vasya's chores. The next line contains a sequence of integers h1, h2, ..., hn (1 ≤ hi ≤ 109), hi is the complexity of the i-th chore. The numbers in the given sequence are not necessarily different. All numbers on the lines are separated by single spaces.

Print the required number of ways to choose an integer value of x. If there are no such ways, print 0.

NoteIn the first sample the possible values of x are 3, 4 or 5.In the second sample it is impossible to find such x, that Petya got 3 chores and Vasya got 4.

open Array;;

let (|>) x f = f x
let identity = fun x -> x

let flip f y x = f x y

let readInStr _ = Scanf.scanf "%d " identity
let readIntLn _ = Scanf.scanf "%d\n" identity
let main () =
        let n = readInStr () in
        let a = readInStr () in
        let b = readIntLn () in
                let h = init n (fun i -> readInStr())  in
                  fast_sort(-)h;
                 if b <= n-1
                 then h.(b) - h.(b-1) |> print_int
                 else print_int 1
        ;;
main()

open Array;;

let (|>) x f = f x
let identity = fun x -> x

let flip f y x = f x y

let readInStr _ = Scanf.scanf "%d " identity
let readIntLn _ = Scanf.scanf "%d\n" identity
let main () =
        let n = readInStr () in
        let a = readInStr () in
        let b = readIntLn () in
                let h = init n (fun i -> readInStr())  in
                  fast_sort(-)h;
                  h.(b) - h.(b-1) |> print_int
        ;;
main()


Vanya has a table consisting of 100 rows, each row contains 100 cells. The rows are numbered by integers from 1 to 100 from bottom to top, the columns are numbered from 1 to 100 from left to right. In this table, Vanya chose n rectangles with sides that go along borders of squares (some rectangles probably occur multiple times). After that for each cell of the table he counted the number of rectangles it belongs to and wrote this number into it. Now he wants to find the sum of values in all cells of the table and as the table is too large, he asks you to help him find the result.

The first line contains integer n (1 ≤ n ≤ 100) — the number of rectangles. Each of the following n lines contains four integers x1, y1, x2, y2 (1 ≤ x1 ≤ x2 ≤ 100, 1 ≤ y1 ≤ y2 ≤ 100), where x1 and y1 are the number of the column and row of the lower left cell and x2 and y2 are the number of the column and row of the upper right cell of a rectangle.

In a single line print the sum of all values in the cells of the table.

NoteNote to the first sample test:Values of the table in the first three rows and columns will be as follows:121121110So, the sum of values will be equal to 10.Note to the second sample test:Values of the table in the first three rows and columns will be as follows:222222222So, the sum of values will be equal to 18.

let () =
	let n = Scanf.scanf "%d" (fun i -> i) and res = ref 0  in
		for i=1 to n do
			Scanf.scanf " %d %d %d %d" (fun i j k l -> res := !res + (k-i+1)*(l-j+1));
		done;
	Printf.printf "%d" !res

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

let () =
  let n = xint () in
  let sum = ref 0 in
  for i = 1 to n do
    let x1 = xint () in
    let y1 = xint () in
    let x2 = xint () in
    let y2 = xint () in
    sum := !sum + (x2 - x1 + 1) * (y2 - y1 + 1);
  done;
  print_int !sum


There are two sisters Alice and Betty. You have $$$n$$$ candies. You want to distribute these $$$n$$$ candies between two sisters in such a way that:  Alice will get $$$a$$$ ($$$a > 0$$$) candies;  Betty will get $$$b$$$ ($$$b > 0$$$) candies;  each sister will get some integer number of candies;  Alice will get a greater amount of candies than Betty (i.e. $$$a > b$$$);  all the candies will be given to one of two sisters (i.e. $$$a+b=n$$$). Your task is to calculate the number of ways to distribute exactly $$$n$$$ candies between sisters in a way described above. Candies are indistinguishable.Formally, find the number of ways to represent $$$n$$$ as the sum of $$$n=a+b$$$, where $$$a$$$ and $$$b$$$ are positive integers and $$$a>b$$$.You have to answer $$$t$$$ independent test cases.

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

For each test case, print the answer — the number of ways to distribute exactly $$$n$$$ candies between two sisters in a way described in the problem statement. If there is no way to satisfy all the conditions, print $$$0$$$.

NoteFor the test case of the example, the $$$3$$$ possible ways to distribute candies are:  $$$a=6$$$, $$$b=1$$$;  $$$a=5$$$, $$$b=2$$$;  $$$a=4$$$, $$$b=3$$$.

(* Codeforces 1335 A Candies and Two Sisters 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 numa n =
    let amax = Int64.sub n Int64.one in
    let n2 = Int64.div n (Int64.of_int 2) in
    let amin = Int64.add n2 Int64.one in
    let d = Int64.sub amax amin in
    Int64.add d Int64.one;;

let do_one () =
	let n = grl () in
    let na = numa n in
    Printf.printf "%Ld\n" na;;

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

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

main();;


Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1.One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on.The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations.

The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi.  The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1).

In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi.

(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)

open Printf
open Scanf
open Array

module S = String
module Q = Queue
module T = Stack
module H = Hashtbl
module L = List

(* misc *)
let neg_compare x y = - compare x y
let min3 a b c = min a (min b c)
let mid3 a b c = if a < b then max a (min b c) else max b (min a c)
let max3 a b c = max a (max b c)
let min4 a b c d = min (min a b) (min c d)
let max4 a b c d = max (max a b) (max c d)
let itb a = a <> 0
let bti b = if b then 1 else 0
let rec bsearch_min a b test =
  if b - a = 1 then b else
  let mid = (a-b)/2 + b in
  if test mid then bsearch_min a mid test else
  bsearch_min mid b test
let rec bsearch_max a b test =
  if b - a = 1 then a else
  let mid = (a-b)/2 + b in
  if test mid then bsearch_max mid b test else
  bsearch_max a mid test
(* int *)
let sqrt_floor n = bsearch_max 0 (1 lsl 31) (fun i -> i*i <= n)
let sqrt_ceil n = bsearch_min (-1) (1 lsl 31) (fun i -> n <= i*i)
(* float *)
let round f = truncate (f +. 0.5)
let inv_float f = 1. /. f
(* functional *)
let id x = x
let const x _ = x
let (|>) x f = f x
let (^>) x f = f x
let (@@) a b = a b
let on g f a b = g (f a) (f b)
let rec fix f = f (fun x -> fix f x)
let ift cond a = if cond then a
let ifte cond a b = if cond then a else b
let rec for_ i len c f = if i = len then c else for_ (i+1) len (f i c) f
(* predicate *)
let is_odd x = x land 1 = 1
let is_even x = x land 1 = 0
(* option *)
let is_none = function | Some _ -> false | None -> true
let is_some = function | Some _ -> true | None -> false
let default x = function Some y -> y | None -> x
(* ref *)
let (+=) a b = a := !a + b
let (-=) a b = a := !a - b
let ( *= ) a b = a := !a * b
let assign_min x y = x := min !x y
let assign_max x y = x := max !x y
(* array *)
let set_min x i v = x.(i) <- min x.(i) v
let set_max x i v = x.(i) <- max x.(i) v
let swap arr i j = let t = arr.(i) in arr.(i) <- arr.(j); arr.(j) <- t
(* int, int *)
let (+:) (a,b) (c,d) = (a+c,b+d)
let (-:) (a,b) (c,d) = (a-c,b-d)
(* number theory *)
let sieve_under len = (* len > 0 *)
  let sieve  = Array.make len true in
  Array.fill sieve 0 (min len 2) false;
  let rec erase i k = if i >= len then () else (sieve.(i) <- false; erase (i+k) k) in
  for i = 2 to sqrt_floor len do if sieve.(i) then erase (2*i) i done;
  sieve
(* Arithmetic *)
let negate x = -x
let rec factorial n = if n = 0 then 1 else n * factorial (n-1)
let rec gcd a b = if b = 0 then a else gcd b (a mod b)
let rec extgcd a b =
  if b = 0 then 1,0,a else
  let x,y,g = extgcd b (a mod b) in
  y,x-(a/b)*y,g
let rec pow x n = if n = 0 then 1 else
  let n' = n/2 in
  let p = pow x n' in
  if is_odd n then x*p*p else p*p
let rec modpow m x n =
  if n = 0 then 1 else
  let n' = n/2 in
  let p = modpow m x n' in
  if is_even n then (p*p mod m) else
  (x*(p*p mod m) mod m)
let modinv m i = let _,x,_ = extgcd m i in x
(* IO *)
let is_digit c =
  let i = int_of_char c in
  48 <= i && i < 58
let is_space c = c = ' ' || c = '\n' || c = '\t' || c = '\r'
let read_char () = try input_char stdin with End_of_file -> '\000'
let rec read_letter () =
  let c = read_char() in
  if is_space c then read_letter() else c
let read_int () =
  let digit c = int_of_char c - 48 in
  let rec read n =
    let c = read_char() in
    if is_digit c then read (10*n + (digit c)) else
    n
  in
  let rec run c =
    if is_digit c then read (digit c) else
    if c = '-' then begin
      let c = read_char() in
      if is_digit c then -read (digit c) else run c
    end else
    if c = '\000' then 0 else
    run (read_char())
  in
  run (read_char())
let read_float () =
  let digit c = float (int_of_char c - 48) in
  let rec read_decimial m f =
    let c = read_char () in
    if is_digit c then read_decimial (m /. 10.) (f +. m *. digit c) else f
  in
  let rec read_integral n =
    let c = read_char () in
    if is_digit c then read_integral (10. *. n +. digit c) else
    if c = '.' then n +. read_decimial 0.1 0.0 else
    n
  in
  let rec run c = begin
    if is_digit c then read_integral (digit c) else
    if c = '-' then begin
      let c = read_char() in
      if is_digit c then -. read_integral (digit c) else
      run c
    end else
    if c = '.' then read_decimial 0.1 0.0 else
    if c = '\000' then 0.0 else
    run (read_char())
  end in
  run (read_char())
let read_word () =
  let open Buffer in
  let buf = create 128 in
  let rec read c =
    if is_space c || c = '\000' then contents buf else begin
      add_char buf c;
      read (read_char())
    end
  in
  let rec run c =
    if is_space c then run (read_char()) else
    if c = '\000' then "" else
    read c
  in
  run (read_char())
let read_line () =
  let open Buffer in
  let buf = create (4*1024) in
  let rec run c =
    if c = '\n' || c = '\000' then contents buf else begin
      add_char buf c;
      run (read_char())
    end
  in
  run (read_char())
let newline () = print_newline()
let print_tuple s (x,y) = printf s x y
let print_array s arr = Array.iter (printf s) arr; print_newline()
let print_matrix s mat = Array.iter (print_array s) mat
let print_list s lis = List.iter (printf s) lis; print_newline()
;;

let _ =
  let len = read_int() in
  let graph = make len [] in
  for i = 0 to len-2 do
    let a = read_int() - 1 in
    let b = read_int() - 1 in
    graph.(a) <- b :: graph.(a);
    graph.(b) <- a :: graph.(b)
  done;
  let ini = init len (fun i -> read_int() ) in
  let goal = init len (fun i -> read_int() ) in

  let cnt = ref [] in
  let rec dfs lv odd even p i =
    let curr = if is_odd lv then (ini.(i) lxor odd) else (ini.(i) lxor even) in
    if curr <> goal.(i) then begin
      cnt := i :: !cnt;
      let odd  = if is_odd lv then odd lxor 1 else odd in
      let even = if is_even lv then even lxor 1 else even in
      L.iter (fun j -> if j <> p then dfs (lv+1) odd even i j) graph.(i)
    end else
      L.iter (fun j -> if j <> p then dfs (lv+1) odd even i j) graph.(i)
  in
  dfs 0 0 0 (-1) 0;
  printf "%d\n" (L.length !cnt);
  L.iter (fun i -> printf "%d\n" (i+1)) !cnt

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_pair () = let u = read_int() in (u,read_int())
let () =
  let n = read_int () in
  let tree = Array.make n [] in

  for i=0 to n-2 do
    let u = (read_int()) -1 in
    let v = (read_int()) -1 in
    tree.(u) <- v::tree.(u);
    tree.(v) <- u::tree.(v);
  done;

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

  for i=0 to n-1 do
    let b = read_int () in
    init.(i) <- init.(i) lxor b
  done;

  let parent = Array.make n (-1) in

  let rec dfs u p =
    List.iter (fun v ->
      if v <> p then (
	parent.(v) <- u;
	dfs v u
      )
    ) tree.(u)
  in

  dfs 0 (-1);

  let rec loop i ac = if i=n then ac else
      let condadd bit = if bit=0 then ac else i::ac in
      if parent.(i) < 0 || parent.(parent.(i)) < 0 then loop (i+1) (condadd init.(i))
      else loop (i+1) (condadd (init.(i) lxor init.(parent.(parent.(i)))))
  in

  let li = loop 0 [] in
  printf "%d\n" (List.length li);
  List.iter (fun i -> printf "%d\n" (i+1)) (loop 0 [])


In the snake exhibition, there are $$$n$$$ rooms (numbered $$$0$$$ to $$$n - 1$$$) arranged in a circle, with a snake in each room. The rooms are connected by $$$n$$$ conveyor belts, and the $$$i$$$-th conveyor belt connects the rooms $$$i$$$ and $$$(i+1) \bmod n$$$. In the other words, rooms $$$0$$$ and $$$1$$$, $$$1$$$ and $$$2$$$, $$$\ldots$$$, $$$n-2$$$ and $$$n-1$$$, $$$n-1$$$ and $$$0$$$ are connected with conveyor belts.The $$$i$$$-th conveyor belt is in one of three states:  If it is clockwise, snakes can only go from room $$$i$$$ to $$$(i+1) \bmod n$$$.  If it is anticlockwise, snakes can only go from room $$$(i+1) \bmod n$$$ to $$$i$$$.  If it is off, snakes can travel in either direction.   Above is an example with $$$4$$$ rooms, where belts $$$0$$$ and $$$3$$$ are off, $$$1$$$ is clockwise, and $$$2$$$ is anticlockwise.Each snake wants to leave its room and come back to it later. A room is returnable if the snake there can leave the room, and later come back to it using the conveyor belts. How many such returnable rooms are there?

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$): the number of test cases. The description of the test cases follows.   The first line of each test case description contains a single integer $$$n$$$ ($$$2 \le n \le 300\,000$$$): the number of rooms.  The next line of each test case description contains a string $$$s$$$ of length $$$n$$$, consisting of only '<', '>' and '-'.   If $$$s_{i} = $$$ '>', the $$$i$$$-th conveyor belt goes clockwise.  If $$$s_{i} = $$$ '<', the $$$i$$$-th conveyor belt goes anticlockwise.  If $$$s_{i} = $$$ '-', the $$$i$$$-th conveyor belt is off.  It is guaranteed that the sum of $$$n$$$ among all test cases does not exceed $$$300\,000$$$.

For each test case, output the number of returnable rooms.

NoteIn the first test case, all rooms are returnable except room $$$2$$$. The snake in the room $$$2$$$ is trapped and cannot exit. This test case corresponds to the picture from the problem statement. In the second test case, all rooms are returnable by traveling on the series of clockwise belts.

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

let rec count_freq str i (c1, c2, c3) =
  if i >= String.length str then
    (c1, c2, c3)
  else
    let newcnt =
      if str.[i] = '<' then (c1 + 1, c2, c3)
      else if str.[i] = '>' then (c1, c2 + 1, c3)
      else (c1, c2, c3 + 1)
    in
    count_freq str (i + 1) newcnt

let rec check_minus i str1 str2 =
  if i >= String.length str1 then
    0
  else
    let newcnt =
      if str1.[i] = '-' then 1
      else if str2.[i] = '-' then 1
      else 0
    in
    (check_minus (i + 1) str1 str2) + newcnt

let solve_test() =
  let n = read_int() and
      str = read_string() in
  let (cnt1, cnt2, cnt3) = count_freq str 0 (0, 0, 0)
  in
  let ans =
    if ( (cnt1 + cnt3) = n ) then n
    else if ( (cnt2 + cnt3) = n ) then n
    else check_minus 0 str ( (String.make 1 str.[n - 1]) ^ (String.sub str 0 (n - 1)) )
  in
  Printf.printf "%d\n" ans

let t = read_int();;
let () =
  for i = 1 to t do
    solve_test ()
  done


One day, as Sherlock Holmes was tracking down one very important criminal, he found a wonderful painting on the wall. This wall could be represented as a plane. The painting had several concentric circles that divided the wall into several parts. Some parts were painted red and all the other were painted blue. Besides, any two neighboring parts were painted different colors, that is, the red and the blue color were alternating, i. e. followed one after the other. The outer area of the wall (the area that lied outside all circles) was painted blue. Help Sherlock Holmes determine the total area of red parts of the wall.Let us remind you that two circles are called concentric if their centers coincide. Several circles are called concentric if any two of them are concentric.

The first line contains the single integer n (1 ≤ n ≤ 100). The second line contains n space-separated integers ri (1 ≤ ri ≤ 1000) — the circles' radii. It is guaranteed that all circles are different.

Print the single real number — total area of the part of the wall that is painted red. The answer is accepted if absolute or relative error doesn't exceed 10 - 4.

NoteIn the first sample the picture is just one circle of radius 1. Inner part of the circle is painted red. The area of the red part equals π × 12 = π.In the second sample there are three circles of radii 1, 4 and 2. Outside part of the second circle is painted blue. Part between the second and the third circles is painted red. Part between the first and the third is painted blue. And, finally, the inner part of the first circle is painted red. Overall there are two red parts: the ring between the second and the third circles and the inner part of the first circle. Total area of the red parts is equal (π × 42 - π × 22) + π × 12 = π × 12 + π = 13π

let pi = acos(-1.0)

let area lst =
  match
  List.fold_left
    (fun (area, sign) r -> area +.sign *. pi *. r *. r, -.sign)
    (0.0, 1.0)
    (List.fast_sort (fun a b -> - compare a b) lst)
  with (area, _) -> area

let main =
  let rec fix f x y = f (fix f) x y in
  let my_read_float =
    let buffer = String.create 5 in
    (fix (fun self_applied n () ->
      buffer.[n] <- input_char stdin;
      match buffer.[n] with
        | ' ' | '\n' -> float_of_string (String.sub buffer 0 n)
        | _ -> self_applied (n + 1) ())) 0
  in
  let read_list =
    (fix (fun self_applied lst -> function
      | 0 -> lst
      | n -> self_applied ((my_read_float ()) :: lst) (n - 1))) []
  in
  let n = read_int () in
  print_float (area (read_list n));
  print_newline ()

let pi = acos(-1.0)

let area lst =
  match
  List.fold_left
    (fun (area, sign) r -> area +.sign *. pi *. r *. r, -.sign)
    (0.0, 1.0)
    (List.fast_sort compare lst)
  with (area, _) -> area

let main =
  let rec fix f x y = f (fix f) x y in
  let my_read_float =
    let buffer = String.create 3 in
    (fix (fun self_applied n () ->
      buffer.[n] <- input_char stdin;
      match buffer.[n] with
        | ' ' | '\n' -> float_of_string (String.sub buffer 0 n)
        | _ -> self_applied (n + 1) ())) 0
  in
  let read_list =
    (fix (fun self_applied lst -> function
      | 0 -> lst
      | n -> self_applied ((my_read_float ()) :: lst) (n - 1))) []
  in
  let n = read_int () in
  print_float (area (read_list n));
  print_newline ()


You are given a list of $$$n$$$ integers. You can perform the following operation: you choose an element $$$x$$$ from the list, erase $$$x$$$ from the list, and subtract the value of $$$x$$$ from all the remaining elements. Thus, in one operation, the length of the list is decreased by exactly $$$1$$$.Given an integer $$$k$$$ ($$$k>0$$$), find if there is some sequence of $$$n-1$$$ operations such that, after applying the operations, the only remaining element of the list is equal to $$$k$$$.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \leq n \leq 2\cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$), the number of integers in the list, and the target value, respectively. The second line of each test case contains the $$$n$$$ integers of the list $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases is not greater that $$$2 \cdot 10^5$$$.

For each test case, print YES if you can achieve $$$k$$$ with a sequence of $$$n-1$$$ operations. Otherwise, print NO. You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as a positive answer).

NoteIn the first example we have the list $$$\{4, 2, 2, 7\}$$$, and we have the target $$$k = 5$$$. One way to achieve it is the following: first we choose the third element, obtaining the list $$$\{2, 0, 5\}$$$. Next we choose the first element, obtaining the list $$$\{-2, 3\}$$$. Finally, we choose the first element, obtaining the list $$$\{5\}$$$.

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

let isIn x tab = let toto = ref false in for i = 0 to Array.length tab -1 do
    if tab.(i) = x then toto := true ; done ; !toto
;;

exception Tototo;;

let comp x y = x - y;;

let n = int_of_string(input_line stdin) in
for i = 0 to n-1 do
  let len,test = Scanf.sscanf (input_line stdin) "%d  %d" (fun len test -> (len,test)) in
  let str = (input_line stdin) in
  let tab = parse str len in
  try
    let f x =if test>0 then (Int64.add (Int64.of_int x) (Int64.of_int (-test))) else Int64.add (Int64.of_int (-x)) (Int64.of_int test) in
    let tab2 = (Array.map f tab) in
    let toto = Hashtbl.create len in
    for j = 0 to Array.length tab -1 do
      Hashtbl.add  toto (Int64.of_int tab.(j)) 0 ;
    done;
    for j = 0 to Array.length tab2 -1 do
      if Hashtbl.mem toto (tab2.(j)) then raise Tototo
    done;
    print_endline "NO"
  with Tototo -> print_endline "YES"

  (*
    if isIn (tot - test) tab then print_endline "YES" else print_endline "NO"*)
done ;;

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

let isIn x tab = let toto = ref false in for i = 0 to Array.length tab -1 do
    if tab.(i) = x then toto := true ; done ; !toto
;;

exception Tototo;;

let comp x y = x - y;;

let n = int_of_string(input_line stdin) in
for i = 0 to n-1 do
  let len,test = Scanf.sscanf (input_line stdin) "%d  %d" (fun len test -> (len,test)) in
  let str = (input_line stdin) in
  let tab = parse str len in
  try
    let f x = if test>0 then x - test else test-x in
    let tab2 = (Array.map f tab) in
    let toto = Hashtbl.create len in
    for j = 0 to Array.length tab -1 do
      Hashtbl.add  toto (tab.(j)) 0 ;
    done;
    for j = 0 to Array.length tab2 -1 do
      if Hashtbl.mem toto (tab2.(j)) then raise Tototo
    done;
    print_endline "NO"
  with Tototo -> print_endline "YES"

  (*
    if isIn (tot - test) tab then print_endline "YES" else print_endline "NO"*)
done ;;

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

let isIn x tab = let toto = ref false in for i = 0 to Array.length tab -1 do
    if tab.(i) = x then toto := true ; done ; !toto
;;

let n = int_of_string(input_line stdin) in
for i = 0 to n-1 do
  let len,test = Scanf.sscanf (input_line stdin) "%d  %d" (fun len test -> (len,test)) in
  let str = (input_line stdin) in
  let tab,tot = parse str len in
if isIn (tot - test) tab then print_endline "YES" else print_endline "NO"
done ;;


One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. Two pairs are considered different, if they contain different substrings of string s or different subsequences of string t. Read the whole statement to understand the definition of different substrings and subsequences.The length of string s is the number of characters in it. If we denote the length of the string s as |s|, we can write the string as s = s1s2... s|s|.A substring of s is a non-empty string x = s[a... b] = sasa + 1... sb (1 ≤ a ≤ b ≤ |s|). For example, "code" and "force" are substrings or "codeforces", while "coders" is not. Two substrings s[a... b] and s[c... d] are considered to be different if a ≠ c or b ≠ d. For example, if s="codeforces", s[2...2] and s[6...6] are different, though their content is the same.A subsequence of s is a non-empty string y = s[p1p2... p|y|] = sp1sp2... sp|y| (1 ≤ p1 < p2 < ... < p|y| ≤ |s|). For example, "coders" is a subsequence of "codeforces". Two subsequences u = s[p1p2... p|u|] and v = s[q1q2... q|v|] are considered different if the sequences p and q are different.

The input consists of two lines. The first of them contains s (1 ≤ |s| ≤ 5000), and the second one contains t (1 ≤ |t| ≤ 5000). Both strings consist of lowercase Latin letters.

Print a single number — the number of different pairs "x y" such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the same. As the answer can be rather large, print it modulo 1000000007 (109 + 7).

NoteLet's write down all pairs "x y" that form the answer in the first sample: "s[1...1] t[1]", "s[2...2] t[1]", "s[1...1] t[2]","s[2...2] t[2]", "s[1...2] t[1 2]".

let _ =
  let m = 1000000007l in
  let sb = Scanf.Scanning.stdib in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let t = Scanf.bscanf sb "%s " (fun s -> s) in
  let ns = String.length s in
  let nt = String.length t in
  let a = Array.make_matrix (nt + 1) (ns + 1) 0 in
  let res = ref 0l in
    for i = 0 to nt do
      for j = 0 to ns do
	a.(i).(j) <- 0
      done
    done;
    for i = 1 to nt do
      for j = 1 to ns do
	if t.[i - 1] = s.[j - 1]
	then a.(i).(j) <-
	  Int32.(to_int
		   (rem (add
			   (add
			      (of_int a.(i - 1).(j - 1))
			      1l)
			   (of_int a.(i - 1).(j)))
		      m))
	else a.(i).(j) <- a.(i - 1).(j)
      done
    done;
    (*for i = 0 to nt do
      for j = 0 to ns do
	Printf.printf "%d " a.(i).(j)
      done;
      Printf.printf "\n"
    done;*)
    for j = 0 to ns do
      res := Int32.rem (Int32.add !res (Int32.of_int a.(nt).(j))) m
    done;
    Printf.printf "%ld\n" !res


Many schoolchildren look for a job for the summer, and one day, when Gerald was still a schoolboy, he also decided to work in the summer. But as Gerald was quite an unusual schoolboy, he found quite unusual work. A certain Company agreed to pay him a certain sum of money if he draws them three identical circles on a plane. The circles must not interfere with each other (but they may touch each other). He can choose the centers of the circles only from the n options granted by the Company. He is free to choose the radius of the circles himself (all three radiuses must be equal), but please note that the larger the radius is, the more he gets paid. Help Gerald earn as much as possible.

The first line contains a single integer n — the number of centers (3 ≤ n ≤ 3000). The following n lines each contain two integers xi, yi ( - 104 ≤ xi, yi ≤ 104) — the coordinates of potential circle centers, provided by the Company. All given points are distinct.

Print a single real number — maximum possible radius of circles. The answer will be accepted if its relative or absolute error doesn't exceed 10 - 6.

open Printf
open Scanf

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

let pi = 4.0 *. atan 1.0

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

  let sq x = x*x in

  let cross (x1,y1) (x2,y2) = x1*y2 - x2*y1 in

  let sub i j =
    let ((xi,yi),(xj,yj)) = (input.(i), input.(j)) in
      (xi-xj , yi-yj)
  in

  let len2 (x,y) = sq x + sq y in

  let dist2 i j = len2 (sub i j) in

  let angle i j k =
    let v = sub k i in
    let w = sub j i in
    let a = float (len2 (sub k j)) in
    let b = float (len2 v) in
    let c = float (len2 w) in
    let alpha = acos ((a -. b-. c) /. (-.2.0 *. (sqrt (b *. c)))) in
      if cross v w < 0 then -.alpha else alpha
  in

  let best_triangle i =
    let a = Array.init n (fun j -> ((dist2 i j), j)) in
    let () = Array.sort (fun (a,b) (c,d) -> compare c a) a in
    let k = snd a.(0) in
    let rec loop jj maxa mina = if jj=n then None else
      let j = snd a.(jj) in
      let alpha = angle i j k in
      let maxa = max maxa alpha in
      let mina = min mina alpha in
	if maxa -. mina >= pi /. 3.0 then Some j else loop (jj+1) maxa mina
    in
      match loop 1 0.0 0.0 with
	| None -> 0
	| Some j -> dist2 i j
  in

  let rec loop i m = if i=n then m else
    loop (i+1) (max (best_triangle i) m)
  in

    printf "%.9f\n" ((sqrt(float(loop 0 0))) /. 2.0)


One day n students come to the stadium. They want to play football, and for that they need to split into teams, the teams must have an equal number of people.We know that this group of people has archenemies. Each student has at most two archenemies. Besides, if student A is an archenemy to student B, then student B is an archenemy to student A.The students want to split so as no two archenemies were in one team. If splitting in the required manner is impossible, some students will have to sit on the bench.Determine the minimum number of students you will have to send to the bench in order to form the two teams in the described manner and begin the game at last.

The first line contains two integers n and m (2 ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of students and the number of pairs of archenemies correspondingly. Next m lines describe enmity between students. Each enmity is described as two numbers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the indexes of the students who are enemies to each other. Each enmity occurs in the list exactly once. It is guaranteed that each student has no more than two archenemies. You can consider the students indexed in some manner with distinct integers from 1 to n.

Print a single integer — the minimum number of students you will have to send to the bench in order to start the game.

open Scanf
open Printf

let (|>) f x = x f

module DisJoint: sig

  type 'a t
  val create : 'a -> 'a t
  val get    : 'a t -> 'a
  val set    : 'a t -> 'a -> unit
  val same   : 'a t -> 'a t -> bool
  val union  : 'a t -> 'a t -> unit

end = struct

  type 'a root = {
    mutable value: 'a;
    mutable rank: int;
  }

  type 'a t = { mutable parent : 'a parent; }
  and 'a parent =
    | Parent of 'a t
    | Root of 'a root

  let create v =
    { parent = Root { value = v; rank = 0; }; }

  let compress t =
    let rec loop t ac =
      match t.parent with
        | Root _ ->
            let p = Parent t in
            List.iter (fun t -> t.parent <- p) ac;
        | Parent t' -> loop t' (t :: ac)
    in loop t []

  let find t =
    compress t;
    match t.parent with
      | Root r -> (t, r)
      | Parent t ->
          match t.parent with
            | Root r -> (t, r)
            | Parent _ -> assert false

  let root t =
    snd (find t)

  let get t =
    (root t).value

  let set t v =
    (root t).value <- v

  let same t1 t2 =
    (root t1) == (root t2)

  let union t1 t2 =
    let (t1, r1) = find t1 in
    let (t2, r2) = find t2 in
    if r1 == r2 then ()
    else
      if r1.rank < r2.rank then
        t1.parent <- Parent t2
      else
        (t2.parent <- Parent t1;
         if r1.rank = r2.rank then
           r1.rank <- r1.rank + 1)

end

let (n, input) =
  bscanf Scanning.stdib "%d %d " (fun n m ->
    (n, Array.init m (fun _ ->
      bscanf Scanning.stdib "%d %d " (fun a b -> (a, b)))))

let _ =
  let ct = ref 0 in
  let u = Array.init (n + 1) (fun i -> DisJoint.create i) in
  input |> Array.iter (fun (a, b) ->
    if not (DisJoint.same u.(a) u.(b)) then
      DisJoint.union u.(a) u.(b)
    else
      u |> Array.map (fun b -> if DisJoint.same u.(a) b then 1 else 0)
        |> Array.fold_left (+) 0
        |> (fun c -> if c mod 2 = 1 then incr ct));

  printf "%d"
    (if (n - !ct) mod 2 = 0 then !ct else !ct + 1)

open Scanf
open Printf

let (|>) f x = x f

let (n, arr) =
  bscanf Scanning.stdib "%d %d " (fun n m ->
    (n, Array.init m (fun _ ->
      bscanf Scanning.stdib "%d %d " (fun a b -> (a, b)))))

let ct = ref 0

let rec merge (a, b, len) = function
  | [] -> []
  | (a2, b2, len2) :: xs ->
      if (a2 = a && b2 = b) || (a2 = b && b2 = a) then
        if (len + len2) mod 2 = 1 then
          (incr ct; xs)
        else
          xs
      else
        if a2 = a then (b, b2, len + len2) :: xs else
          if a2 = b then (a, b2, len + len2) :: xs else
            if b2 = a then (a2, b, len + len2) :: xs else
              if b2 = b then (a, a2, len + len2) :: xs else
                (a2, b2, len2) :: merge (a, b, len) xs

let rec process = function
  |      [] -> printf "%d" (match (n mod 2, !ct mod 2) with
                                | (0, 0) -> !ct
                                | (0, 1) -> !ct + 1
                                | (1, 0) -> !ct + 1
                                | (1, 1) -> !ct)
  | x :: xs -> process (merge x xs)

let _ = process
  (arr |> Array.to_list
       |> List.map (fun (a, b) -> (a, b, 1)))

open Scanf
open Printf

let (|>) f x = x f

module DisJoint: sig

  type 'a t
  val create : 'a -> 'a t
  val get    : 'a t -> 'a
  val set    : 'a t -> 'a -> unit
  val same   : 'a t -> 'a t -> bool
  val union  : 'a t -> 'a t -> unit

end = struct

  type 'a root = {
    mutable value: 'a;
    mutable rank: int;
  }

  type 'a t = { mutable parent : 'a parent; }
  and 'a parent =
    | Parent of 'a t
    | Root of 'a root

  let create v =
    { parent = Root { value = v; rank = 0; }; }

  let compress t =
    let rec loop t ac =
      match t.parent with
        | Root _ ->
            let p = Parent t in
            List.iter (fun t -> t.parent <- p) ac;
        | Parent t' -> loop t' (t :: ac)
    in loop t []

  let find t =
    compress t;
    match t.parent with
      | Root r -> (t, r)
      | Parent t ->
          match t.parent with
            | Root r -> (t, r)
            | Parent _ -> assert false

  let root t =
    snd (find t)

  let get t =
    (root t).value

  let set t v =
    (root t).value <- v

  let same t1 t2 =
    (root t1) == (root t2)

  let union t1 t2 =
    let (t1, r1) = find t1 in
    let (t2, r2) = find t2 in
    if r1 == r2 then ()
    else
      if r1.rank < r2.rank then
        t1.parent <- Parent t2
      else
        (t2.parent <- Parent t1;
         if r1.rank = r2.rank then
           r1.rank <- r1.rank + 1)

end

let (n, input) =
  bscanf Scanning.stdib "%d %d " (fun n m ->
    (n, Array.init m (fun _ ->
      bscanf Scanning.stdib "%d %d " (fun a b -> (a, b)))))

let _ =
  let ct = ref 0 in
  let u = Array.init (n + 1) (fun i -> DisJoint.create i) in
  input |> Array.iter (fun (a, b) ->
    if DisJoint.same u.(a) u.(b) then
      (let c = u |> Array.map (fun b -> if DisJoint.same u.(a) b then 1 else 0)
                 |> Array.fold_left (+) 0 in
       if c mod 2 = 1 then incr ct)
    else
      DisJoint.union u.(a) u.(b));

  printf "%d"
    (if (n - !ct) mod 2 = 0 then !ct else !ct + 1)

open Scanf
open Printf

let (|>) f x = x f

let (n, arr) =
  bscanf Scanning.stdib "%d %d " (fun n m ->
    (n, Array.init m (fun _ ->
      bscanf Scanning.stdib "%d %d " (fun a b -> (a, b)))))

let ct = ref 0

let rec merge (a, b, len) = function
  | [] -> []
  | (a2, b2, len2) :: xs ->
      if (a2 = a && b2 = b) || (a2 = b && b2 = a) then
        if (len + len2) mod 2 = 1 then
          (incr ct; xs)
        else
          xs
      else
        if a2 = a then (b, b2, len + len2) :: xs else
          if a2 = b then (a, b2, len + len2) :: xs else
            if b2 = a then (a2, b, len + len2) :: xs else
              if b2 = b then (a, a2, len + len2) :: xs else
                (a2, b2, len2) :: merge (a, b, len) xs

let rec process = function
  |      [] -> printf "%d" (if (n + !ct) mod 2 = 0 then !ct else !ct + 1)
  | x :: xs -> process (merge x xs)

let _ = process
  (arr |> Array.to_list
       |> List.map (fun (a, b) -> (a, b, 1)))

open Scanf
open Printf

let (|>) f x = x f

let (n, arr) =
  bscanf Scanning.stdib "%d %d " (fun n m ->
    (n, Array.init m (fun _ ->
      bscanf Scanning.stdib "%d %d " (fun a b -> (a, b)))))

let ct = ref 0

let rec merge (a, b, len) = function
  | [] -> []
  | (a2, b2, len2) :: xs ->
      if (a2 = a && b2 = b) || (a2 = b && b2 = a) then
        if (len + len2) mod 2 = 1 then
          (incr ct; xs)
        else
          xs
      else
        if a2 = a then (b, b2, len + len2) :: xs else
          if a2 = b then (a, b2, len + len2) :: xs else
            if b2 = a then (a2, b, len + len2) :: xs else
              if b2 = b then (a, a2, len + len2) :: xs else
                (a2, b2, len2) :: merge (a, b, len) xs

let rec process = function
  |      [] -> printf "%d" (if n mod 2 = 1 && !ct mod 2 = 0 then !ct + 1 else !ct)
  | x :: xs -> process (merge x xs)

let _ = process
  (arr |> Array.to_list
       |> List.map (fun (a, b) -> (a, b, 1)))

open Scanf
open Printf

let (|>) f x = x f

module DisJoint: sig

  type 'a t
  val create : 'a -> 'a t
  val get    : 'a t -> 'a
  val set    : 'a t -> 'a -> unit
  val same   : 'a t -> 'a t -> bool
  val union  : 'a t -> 'a t -> unit

end = struct

  type 'a root = {
    mutable value: 'a;
    mutable rank: int;
  }

  type 'a t = { mutable parent : 'a parent; }
  and 'a parent =
    | Parent of 'a t
    | Root of 'a root

  let create v =
    { parent = Root { value = v; rank = 0; }; }

  let compress t =
    let rec loop t ac =
      match t.parent with
        | Root _ ->
            let p = Parent t in
            List.iter (fun t -> t.parent <- p) ac;
        | Parent t' -> loop t' (t :: ac)
    in loop t []

  let find t =
    compress t;
    match t.parent with
      | Root r -> (t, r)
      | Parent t ->
          match t.parent with
            | Root r -> (t, r)
            | Parent _ -> assert false

  let root t =
    snd (find t)

  let get t =
    (root t).value

  let set t v =
    (root t).value <- v

  let same t1 t2 =
    (root t1) == (root t2)

  let union t1 t2 =
    let (t1, r1) = find t1 in
    let (t2, r2) = find t2 in
    if r1 == r2 then ()
    else
      if r1.rank < r2.rank then
        t1.parent <- Parent t2
      else
        (t2.parent <- Parent t1;
         if r1.rank = r2.rank then
           r1.rank <- r1.rank + 1)

end

let (n, input) =
  bscanf Scanning.stdib "%d %d " (fun n m ->
    (n, Array.init m (fun _ ->
      bscanf Scanning.stdib "%d %d " (fun a b -> (a, b)))))

let _ =
  let ct = ref 0 in
  let u = Array.init (n + 1) (fun i -> DisJoint.create i) in
  input |> Array.iter (fun (a, b) ->
    if DisJoint.same u.(a) u.(b) then incr ct else
      DisJoint.union u.(a) u.(b));

  printf "%d"
    (if (n - !ct) mod 2 = 0 then !ct else !ct + 1)

open Scanf
open Printf

let (n, arr) =
  bscanf Scanning.stdib "%d %d " (fun n m ->
    (n, Array.init m (fun _ ->
      bscanf Scanning.stdib "%d %d " (fun a b -> (a, b)))))

let ct = ref 0

let rec merge (a, b) = function
  | [] -> []
  | (a2, b2) :: xs ->
      if (a2 = a && b2 = b) || (a2 = b && b2 = a) then
        (incr ct; xs)
      else
        if a2 = a then (b, b2) :: xs else
          if a2 = b then (a, b2) :: xs else
            if b2 = a then (a2, b) :: xs else
              if b2 = b then (a, a2) :: xs else
                (a2, b2) :: merge (a, b) xs

let rec process = function
  |      [] -> printf "%d" (if n mod 2 = 1 && !ct mod 2 = 0 then !ct + 1 else !ct)
  | x :: xs -> process (merge x xs)

let _ = process (Array.to_list arr)

open Scanf
open Printf

let (|>) f x = x f

let (n, arr) =
  bscanf Scanning.stdib "%d %d " (fun n m ->
    (n, Array.init m (fun _ ->
      bscanf Scanning.stdib "%d %d " (fun a b -> (a, b)))))

let ct = ref 0

let rec merge (a, b, len) = function
  | [] -> []
  | (a2, b2, len2) :: xs ->
      if (a2 = a && b2 = b) || (a2 = b && b2 = a) then
        if (len + len2) mod 2 = 1 then
          (incr ct; xs)
        else
          xs
      else
        if a2 = a then (b, b2, len + len2) :: xs else
          if a2 = b then (a, b2, len + len2) :: xs else
            if b2 = a then (a2, b, len + len2) :: xs else
              if b2 = b then (a, a2, len + len2) :: xs else
                (a2, b2, len2) :: merge (a, b, len) xs

let rec process = function
  |      [] -> printf "%d" (if n mod 2 = 1 && !ct mod 2 = 0 then !ct + 1 else !ct)
  | x :: xs -> process (merge x xs)

let _ = process
  (arr |> Array.to_list
       |> List.map (fun (a, b) -> (a, b, 0)))

open Scanf
open Printf

let ct = ref 0

let rec merge (a, b) = function
  | [] -> []
  | (a2, b2) :: xs ->
      if (a2 = a && b2 = b) || (a2 = b && b2 = a) then
        (incr ct; xs)
      else
        if a2 = a then (b, b2) :: xs else
          if a2 = b then (a, b2) :: xs else
            if b2 = a then (a2, b) :: xs else
              if b2 = b then (a, a2) :: xs else
                (a2, b2) :: merge (a, b) xs

let rec process = function
  |      [] -> printf "%d" !ct
  | x :: xs -> process (merge x xs)

let _ = process
  (Array.to_list
     (bscanf Scanning.stdib "%d %d " (fun n m ->
       Array.init m (fun _ ->
         bscanf Scanning.stdib "%d %d " (fun a b -> (a, b))))))


Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question:Given two binary numbers $$$a$$$ and $$$b$$$ of length $$$n$$$. How many different ways of swapping two digits in $$$a$$$ (only in $$$a$$$, not $$$b$$$) so that bitwise OR of these two numbers will be changed? In other words, let $$$c$$$ be the bitwise OR of $$$a$$$ and $$$b$$$, you need to find the number of ways of swapping two bits in $$$a$$$ so that bitwise OR will not be equal to $$$c$$$.Note that binary numbers can contain leading zeros so that length of each number is exactly $$$n$$$.Bitwise OR is a binary operation. A result is a binary number which contains a one in each digit if there is a one in at least one of the two numbers. For example, $$$01010_2$$$ OR $$$10011_2$$$ = $$$11011_2$$$.Well, to your surprise, you are not Rudolf, and you don't need to help him$$$\ldots$$$ You are the security staff! Please find the number of ways of swapping two bits in $$$a$$$ so that bitwise OR will be changed.

The first line contains one integer $$$n$$$ ($$$2\leq n\leq 10^5$$$) — the number of bits in each number. The second line contains a binary number $$$a$$$ of length $$$n$$$. The third line contains a binary number $$$b$$$ of length $$$n$$$.

Print the number of ways to swap two bits in $$$a$$$ so that bitwise OR will be changed.

exception NotSameLength;;
open Num;;

let zero = num_of_int 0;;
let one = num_of_int 1;;

let solver bits1 bits2 =
  let rec aux bits1 bits2 (n0, n1, m0, m1) = match bits1, bits2 with
    | [], [] -> n0, n1, m0, m1
    | b1::q1, b2::q2 when b1 = one-> aux q1 q2 (if (b2 = zero) then (n0, (add_num n1 one), m0, (add_num m1 one)) else (n0, (add_num n1 one), m0, m1))
    | b1::q1, b2::q2 when b1 = zero -> aux q1 q2 (if (b2 = zero) then ((add_num n0 one), n1, (add_num m0 one), m1) else ((add_num n0 one), n1, m0, m1))
    | _ -> raise NotSameLength
  in
  let n0, n1, m0, m1 = aux bits1 bits2 (zero, zero, zero, zero)
  in
  add_num (mult_num m1 n0) (mult_num (sub_num n1 m1) m0);;

let line1 = read_line();;
let line_bits1 = read_line();;
let line_bits2 = read_line();;

let parse_bits line = List.map (fun b -> num_of_string b) (Str.split (Str.regexp "") line);;
let bits1 = parse_bits line_bits1;;
let bits2 = parse_bits line_bits2;;
print_string @@ string_of_num @@ solver bits1 bits2;;

exception NotSameLength;;

let solver bits1 bits2 =
  let rec aux bits1 bits2 (n0, n1, m0, m1) = match bits1, bits2 with
    | [], [] -> n0, n1, m0, m1
    | 1::q1, b2::q2 -> aux q1 q2 (if (b2 == 0) then (n0, (n1 + 1), m0, (m1 + 1)) else (n0, (n1 + 1), m0, m1))
    | 0::q1, b2::q2 -> aux q1 q2 (if (b2 == 0) then ((n0 + 1), n1, (m0 + 1), m1) else ((n0 + 1), n1, m0, m1))
    | _ -> raise NotSameLength
  in
  let n0, n1, m0, m1 = aux bits1 bits2 (0, 0, 0, 0)
  in
  m1 * n0 + (n1 - m1) * m0;;

let bits1_1 = 0::1::0::1::1::[];;
let bits2_1 = 1::1::0::0::1::[];;
let bits1_2 = 0::1::1::0::0::0::[];;
let bits2_2 = 0::1::0::0::1::1::[];;

let line1 = read_line();;
let line_bits1 = read_line();;
let line_bits2 = read_line();;

let parse_bits line = List.map (fun b -> int_of_string b) (Str.split (Str.regexp "") line);;
let bits1 = parse_bits line_bits1;;
let bits2 = parse_bits line_bits2;;
print_int @@ solver bits1 bits2;;

exception NotSameLength;;

let solver bits1 bits2 =
  let rec aux bits1 bits2 (n0, n1, m0, m1) = match bits1, bits2 with
    | [], [] -> n0, n1, m0, m1
    | b1::q1, b2::q2 when b1 == 1 -> aux q1 q2 (if (b2 == 0) then (n0, n1 + 1, m0, m1 + 1) else (n0, n1+ 1, m0, m1))
    | b1::q1, b2::q2 when b1 == 0 -> aux q1 q2 (if (b2 == 0) then (n0 + 1, n1, m0 + 1, m1) else (n0 + 1, n1, m0, m1))
    | _ -> raise NotSameLength
  in
  let n0, n1, m0, m1 = aux bits1 bits2 (0, 0, 0, 0)
  in
  (assert (m1 <= n1));
  m1 * n0 + (n1 - m1) * m0;;

(*
let line1 = read_line();;
let line_bits1 = read_line();;
let line_bits2 = read_line();;

let parse_bits line = List.map (fun b -> int_of_string b) (Str.split (Str.regexp "") line);;
let bits1 = parse_bits line_bits1;;
let bits2 = parse_bits line_bits2;;
print_string @@ string_of_int @@ solver bits1 bits2;;
 *)
let rec f n =
  if n > 0 then begin print_int n; print_newline ();f(n * 10) end;;

f 1;;
print_int max_int;;

exception NotSameLength;;

let solver bits1 bits2 =
  let rec aux bits1 bits2 (n0, n1, m0, m1) = match bits1, bits2 with
    | [], [] -> n0, n1, m0, m1
    | b1::q1, b2::q2 when b1 == 1 -> aux q1 q2 (if (b2 == 0) then (n0, n1 + 1, m0, m1 + 1) else (n0, n1+ 1, m0, m1))
    | b1::q1, b2::q2 when b1 == 0 -> aux q1 q2 (if (b2 == 0) then (n0 + 1, n1, m0 + 1, m1) else (n0 + 1, n1, m0, m1))
    | _ -> raise NotSameLength
  in
  let n0, n1, m0, m1 = aux bits1 bits2 (0, 0, 0, 0)
  in
  m1 * n0 + (n1 - m1) * m0;;

let line1 = read_line();;
let line_bits1 = read_line();;
let line_bits2 = read_line();;

let parse_bits line = List.map (fun b -> int_of_string b) (Str.split (Str.regexp "") line);;
let bits1 = parse_bits line_bits1;;
let bits2 = parse_bits line_bits2;;
print_string @@ string_of_int @@ solver bits1 bits2;;

exception NotSameLength;;
open Num;;

let zero = num_of_int 0;;
let one = num_of_int 1;;

let solver bits1 bits2 =
  let rec aux bits1 bits2 (n0, n1, m0, m1) = match bits1, bits2 with
    | [], [] -> n0, n1, m0, m1
    | b1::q1, b2::q2 when b1 = one-> aux q1 q2 (if (b2 = zero) then (n0, (add_num n1 one), m0, (add_num m1 one)) else (n0, (add_num n1 one), m0, m1))
    | b1::q1, b2::q2 when b1 = zero -> aux q1 q2 (if (b2 = zero) then ((add_num n0 one), n1, (add_num m1 one), m1) else ((add_num n0 one), n1, m0, m1))
    | _ -> raise NotSameLength
  in
  let n0, n1, m0, m1 = aux bits1 bits2 (zero, zero, zero, zero)
  in
  add_num (mult_num m1 n0) (mult_num (sub_num n1 m1) m0);;

let line1 = read_line();;
let line_bits1 = read_line();;
let line_bits2 = read_line();;

let parse_bits line = List.map (fun b -> num_of_string b) (Str.split (Str.regexp "") line);;
let bits1 = parse_bits line_bits1;;
let bits2 = parse_bits line_bits2;;
print_string @@ string_of_num @@ solver bits1 bits2;;

exception NotSameLength;;

let solver bits1 bits2 =
  let rec aux bits1 bits2 (n0, n1, m0, m1) = match bits1, bits2 with
    | [], [] -> n0, n1, m0, m1
    | b1::q1, b2::q2 when b1 == 1 -> aux q1 q2 (if (b2 == 0) then (n0, n1 + 1, m0, m1 + 1) else (n0, n1+ 1, m0, m1))
    | b1::q1, b2::q2 when b1 == 0 -> aux q1 q2 (if (b2 == 0) then (n0 + 1, n1, m0 + 1, m1) else (n0 + 1, n1, m0, m1))
    | _ -> raise NotSameLength
  in
  let n0, n1, m0, m1 = aux bits1 bits2 (0, 0, 0, 0)
  in
  (assert (m1 <= n1));
  m1 * n0 + (n1 - m1) * m0;;

let line1 = read_line();;
let line_bits1 = read_line();;
let line_bits2 = read_line();;

let parse_bits line = List.map (fun b -> int_of_string b) (Str.split (Str.regexp "") line);;
let bits1 = parse_bits line_bits1;;
let bits2 = parse_bits line_bits2;;
print_string @@ string_of_int @@ solver bits1 bits2;;


Everyone knows that long ago on the territory of present-day Berland there lived Bindian tribes. Their capital was surrounded by n hills, forming a circle. On each hill there was a watchman, who watched the neighbourhood day and night.In case of any danger the watchman could make a fire on the hill. One watchman could see the signal of another watchman, if on the circle arc connecting the two hills there was no hill higher than any of the two. As for any two hills there are two different circle arcs connecting them, the signal was seen if the above mentioned condition was satisfied on at least one of the arcs. For example, for any two neighbouring watchmen it is true that the signal of one will be seen by the other.An important characteristics of this watch system was the amount of pairs of watchmen able to see each other's signals. You are to find this amount by the given heights of the hills.

The first line of the input data contains an integer number n (3 ≤ n ≤ 106), n — the amount of hills around the capital. The second line contains n numbers — heights of the hills in clockwise order. All height numbers are integer and lie between 1 and 109.

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

let rec rev a l h =
  if l < h-1 then (
    let t = a.(l) in
    a.(l) <- a.(h-1);
    a.(h-1) <- t;
    rev a (l+1) (h-1)
  )

let rotate a x =
  let n = Array.length a in
  rev a 0 x;
  rev a x n;
  rev a 0 n

let () =
  let open Int64 in
  let addi x y = add x (of_int y) in

  let n = read_int 0 in
  let a = Array.init n read_int in
  let _,ma = Array.fold_left (fun (i,x) y -> (i+1,if x = -1 || y > a.(x) then i else x)) (0,-1) a in
  rotate a ma;

  let l = Array.make n 0
  and c = Array.make n 0 in
  for i = 1 to n-1 do
    let t = ref (i-1) in
    while !t > 0 && a.(i) > a.(!t) do
      t := l.(!t);
    done;
    if a.(i) = a.(!t) then (
      c.(i) <- c.(!t)+1;
      l.(i) <- l.(!t)
    ) else
      l.(i) <- !t
  done;

  let ans = ref 0L
  and r = Array.make n 0 in
  for i = n-1 downto 0 do
    ans := addi !ans c.(i);
    let t = ref (i+1) in
    while !t < n && a.(i) >= a.(!t) do
      t := r.(!t)
    done;
    r.(i) <- !t;
    if a.(i) < a.(0) then
      if l.(i) = 0 && r.(i) = n then
        ans := addi !ans 1
      else
        ans := addi !ans 2
  done;
  Printf.printf "%Ld\n" !ans

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

let rec rev a l h =
  if l < h-1 then (
    let t = a.(l) in
    a.(l) <- a.(h-1);
    a.(h-1) <- t;
    rev a (l+1) (h-1)
  )

let rotate a x =
  let n = Array.length a in
  rev a 0 x;
  rev a x n;
  rev a 0 n

let () =
  let n = read_int 0 in
  let a = Array.init n read_int in
  let _,ma = Array.fold_left (fun (i,x) y -> (i+1,if x = -1 || y > a.(x) then i else x)) (0,-1) a in
  rotate a ma;

  let l = Array.make n 0
  and c = Array.make n 0 in
  for i = 1 to n-1 do
    let t = ref (i-1) in
    while !t > 0 && a.(i) > a.(!t) do
      t := l.(!t);
    done;
    if a.(i) = a.(!t) then (
      c.(i) <- c.(!t)+1;
      l.(i) <- l.(!t)
    ) else
      l.(i) <- !t
  done;

  let ans = ref 0
  and r = Array.make n 0 in
  for i = n-1 downto 0 do
    ans := !ans+c.(i);
    let t = ref (i+1) in
    while !t < n && a.(i) >= a.(!t) do
      t := r.(!t)
    done;
    r.(i) <- !t;
    if a.(i) < a.(0) then
      if l.(i) = 0 && r.(i) = n then
        ans := !ans+1
      else
        ans := !ans+2
  done;
  Printf.printf "%d\n" !ans


Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.Help Kefa cope with this task!

The first line contains integer n (1 ≤ n ≤ 105). The second line contains n integers a1,  a2,  ...,  an (1 ≤ ai ≤ 109).

Print a single integer — the length of the maximum non-decreasing subsegment of sequence a.

NoteIn the first test the maximum non-decreasing subsegment is the numbers from the third to the fifth one.In the second test the maximum non-decreasing subsegment is the numbers from the first to the third one.

open Printf
open List
open Pervasives

let split_on_char sep s =
  let r = ref [] in
  let j = ref (String.length s) in
  for i = String.length s - 1 downto 0 do
    if (String.unsafe_get s i) = sep then begin
      r := String.sub s (i + 1) (!j - i - 1) :: !r;
      j := i
    end
  done;
  String.sub s 0 !j :: !r

(* 2 2 1 3 4 1 *)
let rec longest_non_decr_seq seq last count longest =
  match seq with
  | [] -> longest
  | hd::tl ->
    if last > hd then longest_non_decr_seq tl hd 1 (if count > longest then
                                                      count else longest)
    else longest_non_decr_seq tl hd (count + 1) (if (count + 1) > longest then
                                                   (count + 1 ) else longest)

let get_list_size () =
  int_of_string (read_line ())

let get_input_list () =
  let in_line = read_line() in
  List.map int_of_string (split_on_char ' ' in_line)

let () =
  let expected_len = get_list_size () in
  let list = get_input_list () in
  assert (expected_len = List.length list);
  match list with
  | [] -> printf "0\n"
  | hd::_ -> printf "%d\n" (longest_non_decr_seq list hd 0 0)

let list_init n f =
    let rec read n list =
        if n > 0
        then
            let var = f() in
            read (n - 1) (var :: list)
        else
            List.rev list
    in read n []

let income n = list_init n (fun i -> Scanf.scanf "%d " (fun k -> k))

let input () =
    let days = Scanf.scanf "%d " (fun n -> n) in
    income days

let max a b =
    if a > b
    then
        a
    else
        b

let find_max list =
    let rec loop list prev count max_seen =
        match list with
        |(head :: tail) ->
            if prev <= head
            then
                let new_count = count + 1 in
                loop tail head new_count (max new_count max_seen)
            else
                loop tail head 1 max_seen
        |[] -> max_seen

    in loop list 0 0 0

let solve list = find_max list

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

let () = print (solve (input ()))

let list_init n f =
    let rec read n list =
        if n > 0
        then
            let var = f() in
            read (n - 1) (var :: list)
        else
            List.rev list
    in read n []

let income n = list_init n (fun i -> Scanf.scanf "%d " (fun k -> k))

let input () =
    let days = Scanf.scanf "%d " (fun n -> n) in
    income days

let find_max list =
    let rec loop list prev count max_seen =
        match list with
        |(head :: tail) ->
            if prev <= head
            then
                let new_count = count + 1 in
                loop tail head new_count (Pervasives.max new_count max_seen)
            else
                loop tail head 1 max_seen
        |[] -> max_seen

    in loop list 0 0 0

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

let () = print (find_max (input ()))

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

let () =
  let n = read_int () in
  let ans = ref 0 in
  let rec loop acc prev = function
    | 0 -> ()
    | num -> (
      let curr = read_int () in
      if curr >= prev then
        (ans := max !ans (acc + 1);
        loop (acc + 1) curr (num - 1))
      else
        loop 1 curr (num - 1)
    ) in
  loop 0 0 n;
  Printf.printf "%d\n" !ans

open Big_int;;

let rec biggest aux = function
	|[a]	-> aux
	| a::b::q -> if compare_big_int a b > -1
			then biggest (aux + 1) (b::q)
			else max aux (biggest 1 (b::q));;

let main () =
	let l = ref [] and n = Scanf.scanf "%d" (fun i -> i) in
		for i=1 to n do
			l := (Scanf.scanf " %s" big_int_of_string)::!l;
		done;
	Printf.printf "%d" (biggest 1 !l);;

main ();;

open Printf
open String

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

let a = Array.make n (-1);;

for i = 0 to n-1 do
  let jj = Scanf.bscanf Scanf.Scanning.stdin "%d " (fun x -> x) in
  a.(i) <- jj
done

let c = Array.make n  1;; (* This is the array counting the number of increasing sequence *)

let d = ref 1;;

  for i = 1 to n-1 do
    begin
      if( a.(i) >= a.(i-1) ) then
        c.(i) <- c.(i-1) + 1;
      if( !d < c.(i) ) then d := c.(i)
    end
  done;;

let () = print_int !d; print_endline "";;

let read_int () = Scanf.scanf " %d " (fun x -> x);;
let () =
  let n = read_int () in
  let a = Array.init n (fun _ -> read_int()) in
  let rec go i prev cnt best =
    if i = n then max cnt best else
      if a.(i) >= prev then go (i+1) a.(i) (cnt+1) best else
        go (i+1) a.(i) 1 (max cnt best)
  in
  Printf.printf "%d\n" (go 0 0 0 0);;

let n = int_of_string (input_line stdin);;
let first = Scanf.scanf "%d " (fun v -> v);;

let rec solve num_remaining last acc best =
  if num_remaining == 0 then (max acc best) else
  let v = Scanf.scanf "%d " (fun v -> v) in
  if v >= last then solve (num_remaining - 1) v (acc + 1) best
  else solve (num_remaining - 1) v 1 (max acc best);;

let ans = solve (n - 1) first 1 0 in
Printf.printf "%d\n" ans;

open Pervasives
open Printf

let () = printf "%d\n" 3

open Printf
open List
open Pervasives

let split_on_char sep s =
  let r = ref [] in
  let j = ref (String.length s) in
  for i = String.length s - 1 downto 0 do
    if (String.unsafe_get s i) = sep then begin
      r := String.sub s (i + 1) (!j - i - 1) :: !r;
      j := i
    end
  done;
  String.sub s 0 !j :: !r

let rec longest_non_decr_seq seq last count longest =
  match seq with
  | [] -> longest
  | hd::tl ->
    if last > hd then longest_non_decr_seq tl hd 0 (if count > longest then
                                                      count else longest)
    else longest_non_decr_seq tl hd (count + 1) (if (count + 1) > longest then
                                                   (count + 1 ) else longest)

let get_list_size () =
  int_of_string (read_line ())

let get_input_list () =
  let in_line = read_line() in
  List.map int_of_string (split_on_char ' ' in_line)

let () =
  let expected_len = get_list_size () in
  let list = get_input_list () in
  assert (expected_len = List.length list);
  printf "%d\n" ((longest_non_decr_seq list 2 0 0) + 1)

open Printf
open String

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

let a = Array.make n (-1);;

for i = 0 to n-1 do
  let jj = Scanf.bscanf Scanf.Scanning.stdin "%d " (fun x -> x) in
  a.(i) <- jj
done

let c = Array.make n  1;; (* This is the array counting the number of increasing sequence *)

let d = ref 0;;

  for i = 1 to n-1 do
    begin
      if( a.(i) >= a.(i-1) ) then
        c.(i) <- c.(i-1) + 1;
      if( !d < c.(i) ) then d := c.(i)
    end
  done;;

let () = print_int !d; print_endline "";;


Omkar's most recent follower, Ajit, has entered the Holy Forest. Ajit realizes that Omkar's forest is an $$$n$$$ by $$$m$$$ grid ($$$1 \leq n, m \leq 2000$$$) of some non-negative integers. Since the forest is blessed by Omkar, it satisfies some special conditions:  For any two adjacent (sharing a side) cells, the absolute value of the difference of numbers in them is at most $$$1$$$.  If the number in some cell is strictly larger than $$$0$$$, it should be strictly greater than the number in at least one of the cells adjacent to it. Unfortunately, Ajit is not fully worthy of Omkar's powers yet. He sees each cell as a "0" or a "#". If a cell is labeled as "0", then the number in it must equal $$$0$$$. Otherwise, the number in it can be any nonnegative integer.Determine how many different assignments of elements exist such that these special conditions are satisfied. Two assignments are considered different if there exists at least one cell such that the numbers written in it in these assignments are different. Since the answer may be enormous, find the answer modulo $$$10^9+7$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 2000, nm \geq 2$$$) – the dimensions of the forest. $$$n$$$ lines follow, each consisting of one string of $$$m$$$ characters. Each of these characters is either a "0" or a "#". It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2000$$$ and the sum of $$$m$$$ over all test cases does not exceed $$$2000$$$.

For each test case, print one integer: the number of valid configurations modulo $$$10^9+7$$$.

NoteFor the first test case, the two valid assignments are$$$0000\\ 0000\\ 0000$$$and$$$0000\\ 0010\\ 0000$$$

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 p = 1_000_000_007L

let ( ** ) a b = Int64.rem (Int64.mul a b) p
let ( -- ) a b = let y = Int64.sub a b in if y<0L then Int64.add y p else y

let rec powermod a b =   (* a^b mod p.  b is a short a is a long *)
  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 read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_string _ = bscanf Scanning.stdin " %s " (fun x -> x)

let () =
  let cases = read_int () in
  for case = 1 to cases do
    let n = read_int () in
    let m = read_int () in
    let board = Array.init n read_string in
    let count ch =
      sum 0 (n-1) (fun r ->
	sum 0 (m-1) (fun c -> if board.(r).[c] = ch then 1 else 0))
    in
    let zeros = count '0' in
    let sharps = count '#' in
    let answer = (powermod 2L sharps) -- (if zeros = 0 then 1L else 0L) in
    printf "%Ld\n" answer
  done


The spring is coming and it means that a lot of fruits appear on the counters. One sunny day little boy Valera decided to go shopping. He made a list of m fruits he wanted to buy. If Valera want to buy more than one fruit of some kind, he includes it into the list several times. When he came to the fruit stall of Ashot, he saw that the seller hadn't distributed price tags to the goods, but put all price tags on the counter. Later Ashot will attach every price tag to some kind of fruits, and Valera will be able to count the total price of all fruits from his list. But Valera wants to know now what can be the smallest total price (in case of the most «lucky» for him distribution of price tags) and the largest total price (in case of the most «unlucky» for him distribution of price tags).

The first line of the input contains two integer number n and m (1 ≤ n, m ≤ 100) — the number of price tags (which is equal to the number of different kinds of fruits that Ashot sells) and the number of items in Valera's list. The second line contains n space-separated positive integer numbers. Each of them doesn't exceed 100 and stands for the price of one fruit of some kind. The following m lines contain names of the fruits from the list. Each name is a non-empty string of small Latin letters which length doesn't exceed 32. It is guaranteed that the number of distinct fruits from the list is less of equal to n. Also it is known that the seller has in stock all fruits that Valera wants to buy.

Print two numbers a and b (a ≤ b) — the minimum and the maximum possible sum which Valera may need to buy all fruits from his list.

6 5
3 5 1 6 8 1
peach
grapefruit
banana
orange
orange

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

let cnt b m =
  let c = Array.make m 0 in
  let rec go i j k =
    if i >= m then
      k
    else if j < m && b.(i) = b.(j) then
      go i (j+1) k
    else (
      c.(k) <- j-i;
      go j j (k+1)
    )
  in
  let mm = go 0 0 0 in
  let cc = Array.make mm 0 in
  Array.blit c 0 cc 0 mm;
  Array.sort compare cc;
  mm, cc

let () =
  let n = read_int 0 in
  let m = read_int 0 in
  let a = Array.init n read_int in
  let b = Array.init m read_str in
  Array.sort compare a;
  Array.sort compare b;
  let mm, c = cnt b m in
  let ans1 = ref 0 and ans2 = ref 0 in
  for i = 0 to min n mm - 1 do
    ans1 := !ans1 + a.(i) * c.(mm-1-i);
    ans2 := !ans2 + a.(n-1-i) * c.(mm-1-i);
  done;
  Printf.printf "%d %d\n" !ans1 !ans2

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

let cnt b m =
  let c = Array.make m 0 in
  let rec go i j k =
    if i >= m then
      k
    else if j < m && b.(i) = b.(j) then
      go i (j+1) k
    else (
      c.(k) <- j-i;
      go j j (k+1)
    )
  in
  let mm = go 0 0 0 in
  mm, c

let () =
  let n = read_int 0 in
  let m = read_int 0 in
  let a = Array.init n read_int in
  let b = Array.init m read_str in
  Array.sort compare a;
  Array.sort compare b;
  let mm, c = cnt b m in
  let ans1 = ref 0 and ans2 = ref 0 in
  for i = 0 to min n mm - 1 do
    ans1 := !ans1 + a.(i) * c.(m-1-i);
    ans2 := !ans2 + a.(n-1-i) * c.(i);
  done;
  Printf.printf "%d %d\n" !ans1 !ans2


Let's consider all integers in the range from $$$1$$$ to $$$n$$$ (inclusive).Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of $$$\mathrm{gcd}(a, b)$$$, where $$$1 \leq a < b \leq n$$$.The greatest common divisor, $$$\mathrm{gcd}(a, b)$$$, of two positive integers $$$a$$$ and $$$b$$$ is the biggest integer that is a divisor of both $$$a$$$ and $$$b$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$)  — the number of test cases. The description of the test cases follows. The only line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 10^6$$$).

For each test case, output the maximum value of $$$\mathrm{gcd}(a, b)$$$ among all $$$1 \leq a < b \leq n$$$.

NoteIn the first test case, $$$\mathrm{gcd}(1, 2) = \mathrm{gcd}(2, 3) = \mathrm{gcd}(1, 3) = 1$$$.In the second test case, $$$2$$$ is the maximum possible value, corresponding to $$$\mathrm{gcd}(2, 4)$$$.

let rec main (t : int) =
  if t = 0 then
    ()
  else
    let n = read_int() in
    print_endline (string_of_int (n / 2));
    main (t - 1)
in
let t = read_int () in
main t