At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls.Each class must present two couples to the ball. In Vasya's class, $$$a$$$ boys and $$$b$$$ girls wish to participate. But not all boys and not all girls are ready to dance in pairs.Formally, you know $$$k$$$ possible one-boy-one-girl pairs. You need to choose two of these pairs so that no person is in more than one pair.For example, if $$$a=3$$$, $$$b=4$$$, $$$k=4$$$ and the couples $$$(1, 2)$$$, $$$(1, 3)$$$, $$$(2, 2)$$$, $$$(3, 4)$$$ are ready to dance together (in each pair, the boy's number comes first, then the girl's number), then the following combinations of two pairs are possible (not all possible options are listed below):   $$$(1, 3)$$$ and $$$(2, 2)$$$;  $$$(3, 4)$$$ and $$$(1, 3)$$$; But the following combinations are not possible:   $$$(1, 3)$$$ and $$$(1, 2)$$$ — the first boy enters two pairs;  $$$(1, 2)$$$ and $$$(2, 2)$$$ — the second girl enters two pairs; Find the number of ways to select two pairs that match the condition above. Two ways are considered different if they consist of different pairs.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$a$$$, $$$b$$$ and $$$k$$$ ($$$1 \le a, b, k \le 2 \cdot 10^5$$$) — the number of boys and girls in the class and the number of couples ready to dance together. The second line of each test case contains $$$k$$$ integers $$$a_1, a_2, \ldots a_k$$$. ($$$1 \le a_i \le a$$$), where $$$a_i$$$ is the number of the boy in the pair with the number $$$i$$$. The third line of each test case contains $$$k$$$ integers $$$b_1, b_2, \ldots b_k$$$. ($$$1 \le b_i \le b$$$), where $$$b_i$$$ is the number of the girl in the pair with the number $$$i$$$. It is guaranteed that the sums of $$$a$$$, $$$b$$$, and $$$k$$$ over all test cases do not exceed $$$2 \cdot 10^5$$$. It is guaranteed that each pair is specified at most once in one test case.

For each test case, on a separate line print one integer — the number of ways to choose two pairs that match the condition above.

NoteIn the first test case, the following combinations of pairs fit:   $$$(1, 2)$$$ and $$$(3, 4)$$$;  $$$(1, 3)$$$ and $$$(2, 2)$$$;  $$$(1, 3)$$$ and $$$(3, 4)$$$;  $$$(2, 2)$$$ and $$$(3, 4)$$$. There is only one pair in the second test case.In the third test case, the following combinations of pairs fit:   $$$(1, 1)$$$ and $$$(2, 2)$$$;  $$$(1, 2)$$$ and $$$(2, 1)$$$.

let print_list a =
  let print_elem e =
    print_int e;
    print_string " "
  in List.iter print_elem a;
  print_newline ();;

let print_tuple_list a =
  let print_elem e =
    let a,b = e in
    Printf.printf "(%d, %d) " a b
  in List.iter print_elem a;
  print_newline ();;

module MyInt = struct
  type t = int
  let compare a b =
    if a < b then
      -1
    else if a > b then
      1
    else
      0
end

module IntSet = Set.Make(MyInt)

(*
Represent the possible pairings as a Bipartite Graph, with Boys on one side and Girls on the other.
For each edge (u,v), you can calculate the number of valid pairings by knowing the degrees of
u and v in the graph.

Procedure:
Sum of: for each edge u,v:
  b_degree = number of edges incident with u - 1
  g_degree = number of edges incident with v - 1
  We subtract 1 because one edge is shared (the edge being considered)

  all_other_edges = k-1
  number of possible pairs with u,v = all_other_edges - (b_degree+g_degree)

  return number of possible pairs

The answer is the above sum divided by 2. We divide by two because the above
algorithm considers the pairings a,b and b,a unique. But the problem does not.
So, by dividing by 2 we remove the "symmetrical"/"mirror" pairings.
*)

(* Record for easily getting a,b, and k *)
type constraints = {
  a: int;
  b: int;
  k: int;
}

(* Ripped straight out of the Stdlib because this is only available since 4.05 *)
(* But codeforces is using 4.02.... *)
(* You -can- use a method from Str to split with a regex, but that could be slow. *)
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

(* Helper for reading a,b, and k *)
let read_three_ints () =
  split_on_char ' ' (read_line ())
  |> List.map int_of_string
  |> fun list -> {
    a = List.nth list 0;
    b = List.nth list 1;
    k = List.nth list 2;
  }

(* So thankful there are lots of Haskell answers on stack overflow *)
(* Filters a list down to its unique elements *)
(* This could be really slow.... *)
(* let rec uniq l =
  match l with
  | [] -> []
  | h :: tl -> h :: uniq (List.filter (fun e -> e != h) tl);; *)

(* Lets use a set instead *)
let uniq l =
  IntSet.of_list l |> IntSet.elements

(* Creates a simple array of pairs where each k is paired with how many times it appears *)
let init_assoc keys size =
  let assoc = Array.make size (0,0) in
  let create_tuple k =
    Array.set assoc (k-1) (k, 0)
  in List.iter create_tuple keys;
  assoc;;

(* Increments the 2nd element of the pair at index k-1  *)
let update k assoc =
  let new_value =
    match Array.get assoc (k-1) with
    | (k, v) -> (k, v+1)
  in Array.set assoc (k-1) new_value;;

(*
The dream:
l => [1; 1; 1; 2; 3; 3;]
returns = [(1, 3); (2, 1); (3, 2)]
*)
let compute_vertex_degree keys size =
  let assoc = init_assoc keys size in
  let increment k =
    update k assoc
  in List.iter increment keys;
  assoc;;

let read_int_list () =
  split_on_char ' ' (read_line ())
  |> List.map int_of_string

let iter f n =
  for i = 1 to n do
    f n
  done;;

let fetch_degree degree_array node =
  let _, degree = degree_array.(node-1) in
  degree

let sum list =
  List.fold_left ( Int64.add ) 0L list

let halve n =
  Int64.div n 2L

let lookup_edge n edges =
  Array.get edges (n-1)

let count_pairings edges b_degree g_degree k =
  let count_for_edge e =
    let b, g = e in
    let b_incident = (fetch_degree b_degree b) - 1 in
    let g_incident = (fetch_degree g_degree g) - 1 in
    (k-1) - (b_incident + g_incident)
  in List.map count_for_edge edges
  |> List.map Int64.of_int
  |> sum
  |> halve;;

let num_cases = read_int () in
let process_test test_number =
  (* Read in all the stuff *)
  let constraints = read_three_ints () in
  let bs = read_int_list () in
  let gs = read_int_list () in
  (* Create the edges for looking up edge degrees *)
  let edges = List.combine bs gs in
  (* Compute the degrees *)
  let b_degree = compute_vertex_degree bs constraints.a in
  let g_degree = compute_vertex_degree gs constraints.b in
  (* Compute the number *)
  Printf.printf "%Ld\n" (count_pairings edges b_degree g_degree constraints.k)
in iter process_test num_cases

let print_list a =
  let print_elem e =
    print_int e;
    print_string " "
  in List.iter print_elem a;
  print_newline ();;

let print_tuple_list a =
  let print_elem e =
    let a,b = e in
    Printf.printf "(%d, %d) " a b
  in List.iter print_elem a;
  print_newline ();;

module MyInt = struct
  type t = int64
  let compare a b =
    if a < b then
      -1
    else if a > b then
      1
    else
      0
end

module IntSet = Set.Make(MyInt)

(*
Represent the possible pairings as a Bipartite Graph, with Boys on one side and Girls on the other.
For each edge (u,v), you can calculate the number of valid pairings by knowing the degrees of
u and v in the graph.

Procedure:
Sum of: for each edge u,v:
  b_degree = number of edges incident with u - 1
  g_degree = number of edges incident with v - 1
  We subtract 1 because one edge is shared (the edge being considered)

  all_other_edges = k-1
  number of possible pairs with u,v = all_other_edges - (b_degree+g_degree)

  return number of possible pairs

The answer is the above sum divided by 2. We divide by two because the above
algorithm considers the pairings a,b and b,a unique. But the problem does not.
So, by dividing by 2 we remove the "symmetrical"/"mirror" pairings.
*)

(* Record for easily getting a,b, and k *)
type constraints = {
  a: int;
  b: int;
  k: int;
}

(* Ripped straight out of the Stdlib because this is only available since 4.05 *)
(* But codeforces is using 4.02.... *)
(* You -can- use a method from Str to split with a regex, but that could be slow. *)
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

(* Helper for reading a,b, and k *)
let read_three_ints () =
  split_on_char ' ' (read_line ())
  |> List.map int_of_string
  |> fun list -> {
    a = List.nth list 0;
    b = List.nth list 1;
    k = List.nth list 2;
  }

(* So thankful there are lots of Haskell answers on stack overflow *)
(* Filters a list down to its unique elements *)
(* This could be really slow.... *)
(* let rec uniq l =
  match l with
  | [] -> []
  | h :: tl -> h :: uniq (List.filter (fun e -> e != h) tl);; *)

(* Lets use a set instead *)
let uniq l =
  IntSet.of_list l |> IntSet.elements

(* Creates a simple array of pairs where each k is paired with how many times it appears *)
let init_assoc keys size =
  let assoc = Array.make size (0,0) in
  let create_tuple k =
    Array.set assoc (k-1) (k, 0)
  in List.iter create_tuple keys;
  assoc;;

(* Increments the 2nd element of the pair at index k-1  *)
let update k assoc =
  let new_value =
    match Array.get assoc (k-1) with
    | (k, v) -> (k, v+1)
  in Array.set assoc (k-1) new_value;;

(*
The dream:
l => [1; 1; 1; 2; 3; 3;]
returns = [(1, 3); (2, 1); (3, 2)]
*)
let compute_vertex_degree l size =
  let keys = l in
  let assoc = init_assoc keys size in
  let increment k =
    update k assoc
  in List.iter increment keys;
  assoc;;

let read_int_list () =
  split_on_char ' ' (read_line ())
  |> List.map int_of_string

let iter f n =
  for i = 1 to n do
    f n
  done;;

let fetch_degree degree_array node =
  let _, degree = degree_array.(node-1) in
  degree

let sum list =
  List.fold_left ( + ) 0 list

let halve n =
  n / 2

let lookup_edge n edges =
  Array.get edges (n-1)

let count_pairings edges b_degree g_degree k =
  let count_for_edge e =
    let b, g = e in
    let b_incident = (fetch_degree b_degree b) - 1 in
    let g_incident = (fetch_degree g_degree g) - 1 in
    (k-1) - (b_incident + g_incident)
  in List.map count_for_edge edges |> sum |> halve;;

let num_cases = read_int () in
let process_test test_number =
  (* Read in all the stuff *)
  let constraints = read_three_ints () in
  let bs = read_int_list () in
  let gs = read_int_list () in
  (* Create the edges for looking up edge degrees *)
  let edges = List.combine bs gs in
  (* Compute the degrees *)
  let b_degree = compute_vertex_degree bs constraints.a in
  let g_degree = compute_vertex_degree gs constraints.b in
  (* Compute the number *)
  Printf.printf "%d\n" (count_pairings edges b_degree g_degree constraints.k)
in iter process_test num_cases

let print_list a =
  let print_elem e =
    print_int e;
    print_string " "
  in List.iter print_elem a;
  print_newline ();;

let print_tuple_list a =
  let print_elem e =
    let a,b = e in
    Printf.printf "(%d, %d) " a b
  in List.iter print_elem a;
  print_newline ();;

module MyInt = struct
  type t = int
  let compare a b =
    if a < b then
      -1
    else if a > b then
      1
    else
      0
end

module IntSet = Set.Make(MyInt)

(*
Represent the possible pairings as a Bipartite Graph, with Boys on one side and Girls on the other.
For each edge (u,v), you can calculate the number of valid pairings by knowing the degrees of
u and v in the graph.

Procedure:
Sum of: for each edge u,v:
  b_degree = number of edges incident with u - 1
  g_degree = number of edges incident with v - 1
  We subtract 1 because one edge is shared (the edge being considered)

  all_other_edges = k-1
  number of possible pairs with u,v = all_other_edges - (b_degree+g_degree)

  return number of possible pairs

The answer is the above sum divided by 2. We divide by two because the above
algorithm considers the pairings a,b and b,a unique. But the problem does not.
So, by dividing by 2 we remove the "symmetrical"/"mirror" pairings.
*)

(* Record for easily getting a,b, and k *)
type constraints = {
  a: int;
  b: int;
  k: int;
}

(* Ripped straight out of the Stdlib because this is only available since 4.05 *)
(* But codeforces is using 4.02.... *)
(* You -can- use a method from Str to split with a regex, but that could be slow. *)
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

(* Helper for reading a,b, and k *)
let read_three_ints () =
  split_on_char ' ' (read_line ())
  |> List.map int_of_string
  |> fun list -> {
    a = List.nth list 0;
    b = List.nth list 1;
    k = List.nth list 2;
  }

(* So thankful there are lots of Haskell answers on stack overflow *)
(* Filters a list down to its unique elements *)
(* This could be really slow.... *)
(* let rec uniq l =
  match l with
  | [] -> []
  | h :: tl -> h :: uniq (List.filter (fun e -> e != h) tl);; *)

(* Lets use a set instead *)
let uniq l =
  IntSet.of_list l |> IntSet.elements

(* Creates a simple array of pairs where each k is paired with how many times it appears *)
let init_assoc keys size =
  let assoc = Array.make size (0,0) in
  let create_tuple k =
    Array.set assoc (k-1) (k, 0)
  in List.iter create_tuple keys;
  assoc;;

(* Increments the 2nd element of the pair at index k-1  *)
let update k assoc =
  let new_value =
    match Array.get assoc (k-1) with
    | (k, v) -> (k, v+1)
  in Array.set assoc (k-1) new_value;;

(*
The dream:
l => [1; 1; 1; 2; 3; 3;]
returns = [(1, 3); (2, 1); (3, 2)]
*)
let compute_vertex_degree l size =
  let keys = l in
  let assoc = init_assoc keys size in
  let increment k =
    update k assoc
  in List.iter increment keys;
  assoc;;

let read_int_list () =
  split_on_char ' ' (read_line ())
  |> List.map int_of_string

let iter f n =
  for i = 1 to n do
    f n
  done;;

let fetch_degree degree_array node =
  let _, degree = degree_array.(node-1) in
  degree

let sum list =
  List.fold_left ( + ) 0 list

let halve n =
  n / 2

let lookup_edge n edges =
  Array.get edges (n-1)

let count_pairings edges b_degree g_degree k =
  let count_for_edge e =
    let b, g = e in
    let b_incident = (fetch_degree b_degree b) - 1 in
    let g_incident = (fetch_degree g_degree g) - 1 in
    (k-1) - (b_incident + g_incident)
  in List.map count_for_edge edges |> sum |> halve;;

let num_cases = read_int () in
let process_test test_number =
  (* Read in all the stuff *)
  let constraints = read_three_ints () in
  let bs = read_int_list () in
  let gs = read_int_list () in
  (* Create the edges for looking up edge degrees *)
  let edges = List.combine bs gs in
  (* Compute the degrees *)
  let b_degree = compute_vertex_degree bs constraints.a in
  let g_degree = compute_vertex_degree gs constraints.b in
  (* Compute the number *)
  Printf.printf "%d\n" (count_pairings edges b_degree g_degree constraints.k)
in iter process_test num_cases


Maksim has $$$n$$$ objects and $$$m$$$ boxes, each box has size exactly $$$k$$$. Objects are numbered from $$$1$$$ to $$$n$$$ in order from left to right, the size of the $$$i$$$-th object is $$$a_i$$$.Maksim wants to pack his objects into the boxes and he will pack objects by the following algorithm: he takes one of the empty boxes he has, goes from left to right through the objects, and if the $$$i$$$-th object fits in the current box (the remaining size of the box is greater than or equal to $$$a_i$$$), he puts it in the box, and the remaining size of the box decreases by $$$a_i$$$. Otherwise he takes the new empty box and continues the process above. If he has no empty boxes and there is at least one object not in some box then Maksim cannot pack the chosen set of objects.Maksim wants to know the maximum number of objects he can pack by the algorithm above. To reach this target, he will throw out the leftmost object from the set until the remaining set of objects can be packed in boxes he has. Your task is to say the maximum number of objects Maksim can pack in boxes he has.Each time when Maksim tries to pack the objects into the boxes, he will make empty all the boxes he has before do it (and the relative order of the remaining set of objects will not change).

The first line of the input contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$, $$$1 \le k \le 10^9$$$) — the number of objects, the number of boxes and the size of each box. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the size of the $$$i$$$-th object.

Print the maximum number of objects Maksim can pack using the algorithm described in the problem statement.

NoteIn the first example Maksim can pack only $$$4$$$ objects. Firstly, he tries to pack all the $$$5$$$ objects. Distribution of objects will be $$$[5], [2, 1]$$$. Maxim cannot pack the next object in the second box and he has no more empty boxes at all. Next he will throw out the first object and the objects distribution will be $$$[2, 1], [4, 2]$$$. So the answer is $$$4$$$.In the second example it is obvious that Maksim cannot pack all the objects starting from first, second, third and fourth (in all these cases the distribution of objects is $$$[4]$$$), but he can pack the last object ($$$[1]$$$).In the third example Maksim can pack all the objects he has. The distribution will be $$$[1, 2], [3], [1, 1]$$$.

open Printf open Scanf
module MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end
module MyInt64 = struct
	let (%$) = (mod) let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v)) let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v) let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=" ") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls "" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
	let (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v
	let ceildiv m n = (m+n-1L) / n
	let abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf " %s" (fun v -> v)
	let i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a
	let dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf " %d" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf " %d %d" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done
end open MyInt64

let () =
	let n,m,k = get_3_i64 0 in
	let a = input_i64_array n |> Array.to_list |> List.rev |> Array.of_list
	in
	let cur = ref 0L in
	let boxes = ref 1L in
	let res = ref 0L in
	repi 0 (i32 @@ n-1L) (fun i ->
		let v = a.(i) in
		(* printf "%d %Ld: %Ld %Ld %Ld\n" i v !cur !boxes !res; *)
		if v + !cur <= k then (cur += v; res += 1L; `Ok)
		else (
			boxes += 1L; cur := v;
			if !boxes > m then (
				`Break
			) else (
				res += 1L; `Ok
			)
		)
	);
	!res |> printf "%Ld\n"


Pavel cooks barbecue. There are n skewers, they lay on a brazier in a row, each on one of n positions. Pavel wants each skewer to be cooked some time in every of n positions in two directions: in the one it was directed originally and in the reversed direction.Pavel has a plan: a permutation p and a sequence b1, b2, ..., bn, consisting of zeros and ones. Each second Pavel move skewer on position i to position pi, and if bi equals 1 then he reverses it. So he hope that every skewer will visit every position in both directions.Unfortunately, not every pair of permutation p and sequence b suits Pavel. What is the minimum total number of elements in the given permutation p and the given sequence b he needs to change so that every skewer will visit each of 2n placements? Note that after changing the permutation should remain a permutation as well.There is no problem for Pavel, if some skewer visits some of the placements several times before he ends to cook. In other words, a permutation p and a sequence b suit him if there is an integer k (k ≥ 2n), so that after k seconds each skewer visits each of the 2n placements.It can be shown that some suitable pair of permutation p and sequence b exists for any n.

The first line contain the integer n (1 ≤ n ≤ 2·105) — the number of skewers. The second line contains a sequence of integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the permutation, according to which Pavel wants to move the skewers. The third line contains a sequence b1, b2, ..., bn consisting of zeros and ones, according to which Pavel wants to reverse the skewers.

Print single integer — the minimum total number of elements in the given permutation p and the given sequence b he needs to change so that every skewer will visit each of 2n placements.

NoteIn the first example Pavel can change the permutation to 4, 3, 1, 2.In the second example Pavel can change any element of b to 1.

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let p = Array.make n 0 in
  let b = Array.make n 0 in
  let _ =
    for i = 0 to n - 1 do
      p.(i) <- Scanf.bscanf sb "%d " (fun s -> s) - 1;
    done;
    for i = 0 to n - 1 do
      b.(i) <- Scanf.bscanf sb "%d " (fun s -> s);
    done;
  in
  (*let p' = Array.make (2 * n) 0 in
  let _ =
    for i = 0 to n - 1 do
      if b.(p.(i)) = 0 then (
	p'.(i) <- p.(i);
	p'.(i + n) <- p.(i) + n;
      ) else (
	p'.(i) <- p.(i) + n;
	p'.(i + n) <- p.(i);
      )
    done;
  in
  let p = p' in*)
  let used = Array.make n false in
  let rec dfs i =
    if not used.(i) then (
      used.(i) <- true;
      dfs p.(i)
    )
  in
  let res = ref 0 in
  let c = ref 0 in
  let cb = ref 0 in
    for i = 0 to n - 1 do
      if not used.(i) then (
	dfs i;
	incr c;
      )
    done;
    for i = 0 to n - 1 do
      cb := !cb + b.(i);
    done;
    if !cb mod 2 = 0
    then incr res;
    if !c > 1
    then res := !res + !c;
    Printf.printf "%d\n" !res


Polycarpus just has been out of luck lately! As soon as he found a job in the "Binary Cat" cafe, the club got burgled. All ice-cream was stolen.On the burglary night Polycarpus kept a careful record of all club visitors. Each time a visitor entered the club, Polycarpus put down character "+" in his notes. Similarly, each time a visitor left the club, Polycarpus put character "-" in his notes. We know that all cases of going in and out happened consecutively, that is, no two events happened at the same time. Polycarpus doesn't remember whether there was somebody in the club at the moment when his shift begun and at the moment when it ended.Right now the police wonders what minimum number of distinct people Polycarpus could have seen. Assume that he sees anybody coming in or out of the club. Each person could have come in or out an arbitrary number of times.

The only line of the input contains a sequence of characters "+" and "-", the characters are written one after another without any separators. The characters are written in the order, in which the corresponding events occurred. The given sequence has length from 1 to 300 characters, inclusive.

Print the sought minimum number of people

let tail s =
  (String.sub s 1 ((String.length s) - 1))
in

let minmax record =
  let rec helper record curr (cur_min, cur_max) =
    if record = "" then (cur_min, cur_max)
    else
      let curr =
        match record.[0] with
        | '+' -> curr + 1
        | '-' -> curr - 1
        | _ -> -1000
      in
      let cur_min = min cur_min curr
      and cur_max = max cur_max curr
      in helper (tail record) curr (cur_min, cur_max)
  in helper record 0 (0, 0)
in

let record = Scanf.scanf " %s" (fun x -> x) in
let a, b = minmax record in
Printf.printf "%d\n" (b - a)


You have unweighted tree of $$$n$$$ vertices. You have to assign a positive weight to each edge so that the following condition would hold:  For every two different leaves $$$v_{1}$$$ and $$$v_{2}$$$ of this tree, bitwise XOR of weights of all edges on the simple path between $$$v_{1}$$$ and $$$v_{2}$$$ has to be equal to $$$0$$$. Note that you can put very large positive integers (like $$$10^{(10^{10})}$$$).It's guaranteed that such assignment always exists under given constraints. Now let's define $$$f$$$ as the number of distinct weights in assignment.  In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is $$$0$$$. $$$f$$$ value is $$$2$$$ here, because there are $$$2$$$ distinct edge weights($$$4$$$ and $$$5$$$). In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex $$$1$$$ and vertex $$$6$$$ ($$$3, 4, 5, 4$$$) is not $$$0$$$. What are the minimum and the maximum possible values of $$$f$$$ for the given tree? Find and print both.

The first line contains integer $$$n$$$ ($$$3 \le n \le 10^{5}$$$) — the number of vertices in given tree. The $$$i$$$-th of the next $$$n-1$$$ lines contains two integers $$$a_{i}$$$ and $$$b_{i}$$$ ($$$1 \le a_{i} \lt b_{i} \le n$$$) — it means there is an edge between $$$a_{i}$$$ and $$$b_{i}$$$. It is guaranteed that given graph forms tree of $$$n$$$ vertices.

Print two integers — the minimum and maximum possible value of $$$f$$$ can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.

NoteIn the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.   In the second example, possible assignments for each minimum and maximum are described in picture below. The $$$f$$$ value of valid assignment of this tree is always $$$3$$$.   In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.

(* Solved at at 12:12, 7 minutes late *)

open Printf
open Scanf

let rec exists i j f = (i<=j) && ((f i) || exists (i+1) j f)

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let sum i j f = fold i j (fun i a -> (f i) + a) 0

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

let () =
  let n = read_int() in
  let tree = Array.make n [] in

  let addedge i j =
    tree.(i) <- j::tree.(i);
    tree.(j) <- i::tree.(j)
  in

  for xx=0 to n-2 do
    let i = -1 + read_int() in
    let j = -1 + read_int() in
    addedge i j
  done;

  let is_leaf i = match tree.(i) with [x] -> true | _ -> false  in

  let rec find_root i =
    if not (is_leaf i) then i else find_root (i+1)
  in

  let root = find_root 0 in

  let depth = Array.make n 0 in

  let rec dfs1 p i d =
    depth.(i) <- d;
    List.iter (fun j -> if j <> p then dfs1 i j (d+1)) tree.(i)
  in

  dfs1 (-1) root 0;

  let even = exists 0 (n-1) (fun i -> is_leaf i && depth.(i) mod 2 = 0) in
  let odd = exists 0 (n-1) (fun i -> is_leaf i && depth.(i) mod 2 = 1) in

  let mincount = if odd && even then 3 else 1 in

  let mark = Array.make n 0 in

  let rec dfs2 p i =  (* i is non-leaf *)
    let first = ref true in
    List.iter (fun j -> if j <> p then (
      if is_leaf j then (
	if !first then (
	  mark.(j) <- 1;
	  first := false
	)
      ) else (
	mark.(j) <- 1;
	dfs2 i j
      )
    )) tree.(i)
  in

  dfs2 (-1) root;

  let maxcount = sum 0 (n-1) (fun i -> mark.(i)) in

  printf "%d %d\n" mincount maxcount


Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly ai feet high.   A group of bears is a non-empty contiguous segment of the line. The size of a group is the number of bears in that group. The strength of a group is the minimum height of the bear in that group.Mike is a curious to know for each x such that 1 ≤ x ≤ n the maximum strength among all groups of size x.

The first line of input contains integer n (1 ≤ n ≤ 2 × 105), the number of bears. The second line contains n integers separated by space, a1, a2, ..., an (1 ≤ ai ≤ 109), heights of bears.

Print n integers in one line. For each x from 1 to n, print the maximum strength among all groups of size x.

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

(* Size-keeping union find: the root knows how big the group is *)
let rec find a s i =
  if a.(i) = i then (i, s.(i))
  else let (i',_) as p = find a s a.(i) in (a.(i) <- i'; p)

let rec union a s i j =
  let (i',si) = find a s i in
  let (j',sj) = find a s j in
  if i' = j' then (i', si)
  else (a.(i') <- j'; s.(j') <- si+sj; (j', si+sj))

let _ =
  let n = read_int () in
  let a = Array.init n (fun _ -> read_int ()) in
  let present = Array.make n false in
  let inv = Array.init n (fun i -> (a.(i),i)) in
  let u = Array.init n (fun i -> i) in
  let s = Array.make n 1 in
  let answ = Array.make n 0 in
  Array.sort compare inv;
  (* Add bears in strength order. We get an info "all groups of size < i have strength > s" *)
  for k = n-1 downto 0 do
    let (str,i) = inv.(k) in
    present.(i) <- true;
    if (i > 0 && present.(i-1)) then ignore (union u s (i-1) i);
    if (i+1 < n && present.(i+1)) then ignore (union u s i (i+1));
    let (_,s) = find u s i in
(*    Printf.eprintf "Adding size %d strength %d\n" s str; *)
    answ.(s-1) <- max answ.(s-1) str
  done;
  (* Now update asnw lazily *)
  for i = n-2 downto 0 do
    answ.(i) <- max answ.(i) answ.(i+1);
  done;
  for i = 0 to n-1 do
    Printf.printf "%d%c" answ.(i) (if i = n-1 then '\n' else ' ')
  done


Polycarp has a string $$$s$$$. Polycarp performs the following actions until the string $$$s$$$ is empty ($$$t$$$ is initially an empty string):  he adds to the right to the string $$$t$$$ the string $$$s$$$, i.e. he does $$$t = t + s$$$, where $$$t + s$$$ is a concatenation of the strings $$$t$$$ and $$$s$$$;  he selects an arbitrary letter of $$$s$$$ and removes from $$$s$$$ all its occurrences (the selected letter must occur in the string $$$s$$$ at the moment of performing this action). Polycarp performs this sequence of actions strictly in this order.Note that after Polycarp finishes the actions, the string $$$s$$$ will be empty and the string $$$t$$$ will be equal to some value (that is undefined and depends on the order of removing).E.g. consider $$$s$$$="abacaba" so the actions may be performed as follows:  $$$t$$$="abacaba", the letter 'b' is selected, then $$$s$$$="aacaa";  $$$t$$$="abacabaaacaa", the letter 'a' is selected, then $$$s$$$="c";  $$$t$$$="abacabaaacaac", the letter 'c' is selected, then $$$s$$$="" (the empty string). You need to restore the initial value of the string $$$s$$$ using only the final value of $$$t$$$ and find the order of removing letters from $$$s$$$.

The first line contains one integer $$$T$$$ ($$$1 \le T \le 10^4$$$) — the number of test cases. Then $$$T$$$ test cases follow. Each test case contains one string $$$t$$$ consisting of lowercase letters of the Latin alphabet. The length of $$$t$$$ doesn't exceed $$$5 \cdot 10^5$$$. The sum of lengths of all strings $$$t$$$ in the test cases doesn't exceed $$$5 \cdot 10^5$$$.

For each test case output in a separate line:   $$$-1$$$, if the answer doesn't exist;  two strings separated by spaces. The first one must contain a possible initial value of $$$s$$$. The second one must contain a sequence of letters — it's in what order one needs to remove letters from $$$s$$$ to make the string $$$t$$$. E.g. if the string "bac" is outputted, then, first, all occurrences of the letter 'b' were deleted, then all occurrences of 'a', and then, finally, all occurrences of 'c'. If there are multiple solutions, print any one.

7
abacabaaacaac
nowyouknowthat
polycarppoycarppoyarppyarppyrpprppp
isi
everywherevrywhrvryhrvrhrvhv
haaha
qweqeewew

abacaba bac
-1
polycarp lcoayrp
is si
everywhere ewyrhv
-1
-1

NoteThe first test case is considered in the statement.

(*LMAOOOOOOOOOO'*)

class ['a] vector =
  object (self)
    val mutable a = ([||] : 'a array)
    val mutable size = 0
    method check =
      if size = Array.length a then
        a <- Array.append a a
    method pop =
      if size = 0 then false
      else
        let () = size <- size - 1 in
        true
    method push x =
      if Array.length a = 0 then
        let () = a <- Array.make 1 x in
        size <- 1
      else
        let () = self#check in
        let () = a.(size) <- x in
        size <- size + 1
    method size =
      size
    method get i =
      a.(i)
    method con (other : 'a vector) =
      for i = 0 to other#size do
        self#push (other#get i)
      done
    method sub l r =
      let ans = (new vector : 'a vector) in
      let () =
        for i = l to r do
          ans#push (self#get i)
        done in
      ans
    method from_string s =
      for i = 0 to String.length s - 1 do
        self#push s.[i]
      done
    method eq (other : 'a vector) =
      if self#size <> other#size then false
      else
        let pos = ref true in
        let () =
          for i = 0 to self#size - 1 do
            if (self#get i) <> (other#get i) then pos := false
          done in
        !pos
    method string =
      String.init self#size (fun i -> self#get i)
  end;;

let readInt() = Scanf.scanf " %d" (fun i -> i);;
let readLine() = input_line stdin;;
let print_number x = print_string ((string_of_int x) ^ " ");;
let print_char c = print_string (Char.escaped c);;
let print_array a =
  let () =
    for i = 0 to Array.length a - 1 do
      print_number a.(i)
    done in
  print_string "\n";;
let f c = int_of_char(c) - int_of_char('a');;
let build s1 order =
  let ans = new vector in
  let () =
    let banned = Array.make 26 false in
    for i = 0 to Array.length order - 1 do
      let j = ref 0 in
      let quit_loop = ref false in
      let () =
        while not !quit_loop do
          let () =
            if ans#size = 500000 then quit_loop := true
            else if !j = s1#size then quit_loop := true
            else if not banned.(f (s1#get !j)) then
              ans#push (s1#get !j) in
          j := !j + 1
        done in
      banned.(order.(i)) <- true
    done in
  ans;;

let check s1 s2 order =
  (build s1 order)#eq s2;;

(*let a = new vector in
 let b = new vector in
 let () = a#from_string "abacaba" in
 let () = b#from_string "abacabaaacaac" in
 (build a [|1; 0; 2|])#string;;*)

let da x = ()
let reverse a n = Array.init (n+1) (fun i -> a.(n - i));;
let t = readLine() in
for i = 1 to int_of_string t do
  let inp = readLine() in
  let s = new vector in
  let () = (s#from_string inp) in
  let ptr = ref (-1) in
  let seen = Array.make 26 0 in
  let rev_order = Array.make 26 0 in
  let freq = Array.make 26 0 in
  let possible = ref true in
  let sum = ref 0 in
  let () =
    for j = 0 to s#size - 1 do
      let rj = s#size - 1 - j in
      let c = f (s#get rj) in
      let () =
        freq.(c) <- freq.(c) + 1 in
      if seen.(c) = 0 then
        let () = seen.(c) <- 1 in
        let () = ptr := !ptr + 1 in
        rev_order.(!ptr) <- c
    done in
  let order = reverse rev_order !ptr in
  let () =
    for j = 0 to Array.length order - 1 do
      let c = order.(j) in
      let () =
        if freq.(c) mod (j+1) <> 0 then
          possible := false
        else
          freq.(c) <- freq.(c) / (j+1) in
      sum := !sum + freq.(c)
    done in
  let sb = s#sub 0 (!sum - 1) in
  let ord = String.init (Array.length order) (fun i -> char_of_int (order.(i) + int_of_char('a'))) in
  if (check sb s order) then
    print_string (sb#string ^ " " ^ ord ^ "\n")
  else
    print_string "-1\n"
done;;

(*LMAOOOOOOOOOO*)

class ['a] vector =
  object (self)
    val mutable a = ([||] : 'a array)
    val mutable size = 0
    method check =
      if size = Array.length a then
        a <- Array.append a a
    method pop =
      if size = 0 then false
      else
        let () = size <- size - 1 in
        true
    method push x =
      if Array.length a = 0 then
        let () = a <- Array.make 1 x in
        size <- 1
      else
        let () = self#check in
        let () = a.(size) <- x in
        size <- size + 1
    method size =
      size
    method get i =
      a.(i)
    method con (other : 'a vector) =
      for i = 0 to other#size do
        self#push (other#get i)
      done
    method sub l r =
      let ans = (new vector : 'a vector) in
      let () =
        for i = l to r do
          ans#push (self#get i)
        done in
      ans
    method from_string s =
      for i = 0 to String.length s - 1 do
        self#push s.[i]
      done
    method eq (other : 'a vector) =
      if self#size <> other#size then false
      else
        let pos = ref true in
        let () =
          for i = 0 to self#size - 1 do
            if (self#get i) <> (other#get i) then pos := false
          done in
        !pos
    method string =
      String.init self#size (fun i -> self#get i)
  end;;

let readInt() = Scanf.scanf " %d" (fun i -> i);;
let readLine() = input_line stdin;;
let print_number x = print_string ((string_of_int x) ^ " ");;
let print_char c = print_string (Char.escaped c);;
let print_array a =
  let () =
    for i = 0 to Array.length a - 1 do
      print_number a.(i)
    done in
  print_string "\n";;
let f c = int_of_char(c) - int_of_char('a');;
let build s1 order =
  let ans = new vector in
  let () =
    let banned = Array.make 26 false in
    for i = 0 to Array.length order - 1 do
      let j = ref 0 in
      let quit_loop = ref false in
      let () =
        while not !quit_loop do
          let () =
            if ans#size = 500000 then quit_loop := true
            else if !j = s1#size then quit_loop := true
            else if not banned.(f (s1#get !j)) then
              ans#push (s1#get !j) in
          j := !j + 1
        done in
      banned.(order.(i)) <- true
    done in
  ans;;

let check s1 s2 order =
  (build s1 order)#eq s2;;

(*let a = new vector in
 let b = new vector in
 let () = a#from_string "abacaba" in
 let () = b#from_string "abacabaaacaac" in
 (build a [|1; 0; 2|])#string;;*)

let da x = ()
let reverse a n = Array.init (n+1) (fun i -> a.(n - i));;
let t = readLine() in
for i = 1 to int_of_string t do
  let inp = readLine() in
  let s = new vector in
  let () = (s#from_string inp) in
  let ptr = ref (-1) in
  let seen = Array.make 26 0 in
  let rev_order = Array.make 26 0 in
  let freq = Array.make 26 0 in
  let possible = ref true in
  let sum = ref 0 in
  let () =
    for j = 0 to s#size - 1 do
      let rj = s#size - 1 - j in
      let c = f (s#get rj) in
      let () =
        freq.(c) <- freq.(c) + 1 in
      if seen.(c) = 0 then
        let () = seen.(c) <- 1 in
        let () = ptr := !ptr + 1 in
        rev_order.(!ptr) <- c
    done in
  let order = reverse rev_order !ptr in
  let () =
    for j = 0 to Array.length order - 1 do
      let c = order.(j) in
      let () =
        if freq.(c) mod (j+1) <> 0 then
          possible := false
        else
          freq.(c) <- freq.(c) / (j+1) in
      sum := !sum + freq.(c)
    done in
  let sb = s#sub 0 (!sum - 1) in
  let ord = String.init (Array.length order) (fun i -> char_of_int (order.(i) + int_of_char('a'))) in
  if (check sb s order) then
    print_string (sb#string ^ " " ^ ord ^ "\n")
  else
    print_string "-1\n"
done;;


The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.

The first line contains an integer n (1 ≤ n ≤ 100) — the number of boys. The second line contains sequence a1, a2, ..., an (1 ≤ ai ≤ 100), where ai is the i-th boy's dancing skill. Similarly, the third line contains an integer m (1 ≤ m ≤ 100) — the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≤ bj ≤ 100), where bj is the j-th girl's dancing skill.

Print a single number — the required maximum possible number of pairs.

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

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

let input () =
    let boys = make_list () in
    let girls = make_list () in
    (boys, girls)

let pair boy girl =
    if boy = girl || boy = girl + 1 || boy = girl - 1
    then
        `Paired
    else
        if boy <= girl - 2
        then
            `Next_boy
        else
            `Next_girl

let solve (boys, girls) =
    let rec loop l ll count =
        match (l, ll) with
        | (hd :: tl), (hhd :: ttl) ->
            (match (pair hd hhd) with
            | `Paired -> loop tl ttl (count + 1)
            | `Next_boy -> loop tl ll count
            | `Next_girl -> loop l ttl count)
        | _, [] -> count
        | [], _ -> count
        | [], [] -> count
    in loop boys girls 0

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

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

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

let input () =
    let boys = make_list () in
    let girls = make_list () in
    (boys, girls)

let pair boy girl =
    if boy = girl || boy = girl + 1 || boy = girl - 1
    then
        `Paired
    else
        if boy <= girl - 2
        then
            `Next_boy
        else
            `Next_girl

let solve (boys, girls) =
    let rec loop l ll count =
        match (l, ll) with
        | (hd :: tl), (hhd :: ttl) ->
            (match (pair hd hhd) with
            | `Paired -> loop tl ttl (count + 1)
            | `Next_boy -> loop tl ll count
            | `Next_girl -> loop l ttl count)
        | _, _ -> count
    in loop boys girls 0

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


Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case.

You are given 8 pairs of integers, a pair per line — the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide.

Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers — point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed.

NotePay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = 8 in
  let a = Array.make n (0, 0) in
  let _ =
    for i = 0 to n - 1 do
      let x = Scanf.bscanf sb "%d " (fun s -> s) in
      let y = Scanf.bscanf sb "%d " (fun s -> s) in
	a.(i) <- (x, y)
    done
  in
  let is_right (x, y) (x1, y1) (x2, y2) =
    (x1 - x) * (x2 - x) + (y1 - y) * (y2 - y) = 0
  in
  let is_rect p1 p2 p3 p4 =
    is_right p1 p2 p4 &&
      is_right p2 p1 p3 &&
      is_right p3 p2 p4
  in
  let sqr x = x * x in
  let dist2 (x1, y1) (x2, y2) =
    sqr (x1 - x2) + sqr (y1 - y2)
  in
  let is_square p1 p2 p3 p4 =
    is_rect p1 p2 p3 p4 &&
      dist2 p1 p2 = dist2 p2 p3
  in
  let b = Array.make n 0 in
  let u = Array.make n false in
  let rec bf k =
    if k >= 0 then (
      for i = 0 to n - 1 do
	if not u.(i) then (
	  u.(i) <- true;
	  b.(k) <- i;
	  bf (k - 1);
	  u.(i) <- false;
	)
      done
    ) else (
      if is_square a.(b.(0)) a.(b.(1)) a.(b.(2)) a.(b.(3)) &&
	is_rect a.(b.(4)) a.(b.(5)) a.(b.(6)) a.(b.(7))
      then (
	Printf.printf "YES\n";
	for i = 0 to 3 do
	  Printf.printf "%d " (b.(i) + 1)
	done;
	Printf.printf "\n";
	for i = 4 to 7 do
	  Printf.printf "%d " (b.(i) + 1)
	done;
	Printf.printf "\n";
	exit 0
      )
    )
  in
    bf (n - 1);
    Printf.printf "NO\n"


ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most k bills from it, and the bills may be of at most two distinct denominations.For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at k = 20 such ATM can give sums 100 000 burles and 96 000 burles, but it cannot give sums 99 000 and 101 000 burles.Let's suppose that the country uses bills of n distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash q times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the q of requests for cash withdrawal.

The first line contains two integers n, k (1 ≤ n ≤ 5000, 1 ≤ k ≤ 20). The next line contains n space-separated integers ai (1 ≤ ai ≤ 107) — the denominations of the bills that are used in the country. Numbers ai follow in the strictly increasing order. The next line contains integer q (1 ≤ q ≤ 20) — the number of requests for cash withdrawal that you will make. The next q lines contain numbers xi (1 ≤ xi ≤ 2·108) — the sums of money in burles that you are going to withdraw from the ATM.

For each request for cash withdrawal print on a single line the minimum number of bills it can be done, or print  - 1, if it is impossible to get the corresponding sum.

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 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 k = read_int () in
  let a = Array.init n (fun _ -> read_int()) in
  let q = read_int () in
  let x = Array.init q (fun _ -> read_int()) in

  let h = Hashtbl.create 10 in

  for i = 0 to n-1 do
    for j = 1 to k do
      Hashtbl.replace h (j*a.(i)) j
    done
  done;

  let solve x =
    (* return the answer for an amount x *)
    minf 0 (n-1) (fun i -> minf 1 k (
      fun j ->
	let x' = x - j*a.(i) in
	if x' < 0 then max_int else if x' = 0 then j else
	    let j' = try Hashtbl.find h x' with Not_found -> -1 in
	    if j'<0 || j+j'>k then max_int else j + j'
    ))
  in

  for l=0 to q-1 do
    let answer = solve x.(l) in
    if answer = max_int then printf "-1\n" else printf "%d\n" answer
  done


There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens.Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought $$$n$$$ packets with inflatable balloons, where $$$i$$$-th of them has exactly $$$a_i$$$ balloons inside.They want to divide the balloons among themselves. In addition, there are several conditions to hold:  Do not rip the packets (both Grigory and Andrew should get unbroken packets);  Distribute all packets (every packet should be given to someone);  Give both Grigory and Andrew at least one packet;  To provide more fun, the total number of balloons in Grigory's packets should not be equal to the total number of balloons in Andrew's packets. Help them to divide the balloons or determine that it's impossible under these conditions.

The first line of input contains a single integer $$$n$$$ ($$$1 \le n \le 10$$$) — the number of packets with balloons. The second line contains $$$n$$$ integers: $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_n$$$ ($$$1 \le a_i \le 1000$$$) — the number of balloons inside the corresponding packet.

If it's impossible to divide the balloons satisfying the conditions above, print $$$-1$$$. Otherwise, print an integer $$$k$$$ — the number of packets to give to Grigory followed by $$$k$$$ distinct integers from $$$1$$$ to $$$n$$$ — the indices of those. The order of packets doesn't matter. If there are multiple ways to divide balloons, output any of them.

NoteIn the first test Grigory gets $$$3$$$ balloons in total while Andrey gets $$$1$$$.In the second test there's only one way to divide the packets which leads to equal numbers of balloons.In the third test one of the boys won't get a packet at all.

open Scanf
open Printf

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

let l = Array.to_list (Array.init n (fun i -> i+1, scanf " %d" (fun i -> i)))

let l = List.sort (fun (i, c) (i', c') -> compare c c') l

let rec compute l =
  match l with
  | [] -> None
  | [h] -> None
  | (ih, ch)::t ->
    let s = List.fold_left (fun out (i, c) -> out + c) 0 t in
(*    printf "s = %d and %d\n" s ch;*)
    if s <> ch then
      Some ih
    else
      None

let () =
  match compute l with
  | None -> printf "-1\n"
  | Some i -> printf "1\n%d\n" i


The Bad Luck Island is inhabited by three kinds of species: r rocks, s scissors and p papers. At some moments of time two random individuals meet (all pairs of individuals can meet equiprobably), and if they belong to different species, then one individual kills the other one: a rock kills scissors, scissors kill paper, and paper kills a rock. Your task is to determine for each species what is the probability that this species will be the only one to inhabit this island after a long enough period of time.

The single line contains three integers r, s and p (1 ≤ r, s, p ≤ 100) — the original number of individuals in the species of rock, scissors and paper, respectively.

Print three space-separated real numbers: the probabilities, at which the rocks, the scissors and the paper will be the only surviving species, respectively. The answer will be considered correct if the relative or absolute error of each number doesn't exceed 10 - 9.

let rec solve mat (r,s,p) =
	if mat.(r).(s).(p) = (0.,0.,0.)
		then begin
			let r_s = float (r*s) and s_p = float (s*p)
			and p_r = float (p*r) in
			let tot = r_s +. s_p +. p_r in
			let (a,b,c) = solve mat (r-1,s,p)
			and (aa,bb,cc) = solve mat (r,s-1,p)
			and (aaa,bbb,ccc) = solve mat (r,s,p-1)
			in
			let res =
			((a*.p_r +. aa *. r_s +. aaa *. s_p) /. tot,
			(b*.p_r +. bb *. r_s +. bbb *. s_p) /. tot,
			(c*.p_r +. cc *. r_s +. ccc *. s_p) /. tot)
			in mat.(r).(s).(p) <- res;
			   res
		     end
		else mat.(r).(s).(p)

let f a b c =
	let mat = Array.init (a+1) (fun i -> Array.init (b+1) (fun j -> 	Array.init (c+1) (fun k -> (0.,0.,0.)))) in
		for i=0 to b do
		for j=0 to c do
			mat.(0).(i).(j) <- (0.,1.,0.);
		done;
		done;
		for i=0 to a do
		for j=0 to c do
			mat.(i).(0).(j) <- (0.,0.,1.);
		done;
		done;
		for i=0 to a do
		for j=0 to b do
			mat.(i).(j).(0) <- (1.,0.,0.);
		done;
		done;
		solve mat (a,b,c)

let _ =
	let (a,b,c) = Scanf.scanf "%d %d %d" (fun i j k -> (i,j,k)) in
		let (d,e,f) = f a b c in
			Printf.printf "%F %F %F" d e f

let rec solve mat (r,s,p) =
	if mat.(r).(s).(p) = (0.,0.,0.)
		then begin
			let r_s = float (r*s) and s_p = float (s*p)
			and p_r = float (p*r) in
			let tot = r_s +. s_p +. p_r in
			let (a,b,c) = solve mat (r-1,s,p)
			and (aa,bb,cc) = solve mat (r,s-1,p)
			and (aaa,bbb,ccc) = solve mat (r,s,p-1)
			in
			let res =
			((a*.p_r +. aa *. r_s +. aaa *. s_p) /. tot,
			(b*.p_r +. bb *. r_s +. bbb *. s_p) /. tot,
			(c*.p_r +. cc *. r_s +. ccc *. s_p) /. tot)
			in mat.(r).(s).(p) <- res;
			   res
		     end
		else mat.(r).(s).(p)

let f a b c =
	let mat = Array.init (a+1) (fun i -> Array.init (b+1) (fun j -> 	Array.init (c+1) (fun k -> (0.,0.,0.)))) in
		for i=0 to b do
		for j=0 to c do
			mat.(0).(i).(j) <- (0.,1.,0.);
		done;
		done;
		for i=0 to a do
		for j=0 to c do
			mat.(i).(0).(j) <- (0.,0.,1.);
		done;
		done;
		for i=0 to a do
		for j=0 to b do
			mat.(i).(j).(0) <- (1.,0.,0.);
		done;
		done;
		solve mat (a,b,c)

let _ =
	let (a,b,c) = Scanf.scanf "%d %d %d" (fun i j k -> (i,j,k)) in
		let (d,e,f) = f a b c in
			Printf.printf "%f %f %f" d e f


Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none — in writing a composition.As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written n lines, the i-th line contains ai characters (including spaces). If some line contains k characters, then this line overall contains (k + 1) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (r, c), where r is the number of the line and c is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (r, c), then Vasya pushed key: "Up": if the cursor was located in the first line (r = 1), then it does not move. Otherwise, it moves to the previous line (with number r - 1), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r - 1; "Down": if the cursor was located in the last line (r = n), then it does not move. Otherwise, it moves to the next line (with number r + 1), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r + 1; "Right": if the cursor can move to the right in this line (c < ar + 1), then it moves to the right (to position c + 1). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the "Right" key; "Left": if the cursor can move to the left in this line (c > 1), then it moves to the left (to position c - 1). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the "Left" key.You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position (r1, c1) to position (r2, c2).

The first line of the input contains an integer n (1 ≤ n ≤ 100) — the number of lines in the file. The second line contains n integers a1, a2, ..., an (0 ≤ ai ≤ 105), separated by single spaces. The third line contains four integers r1, c1, r2, c2 (1 ≤ r1, r2 ≤ n, 1 ≤ c1 ≤ ar1 + 1, 1 ≤ c2 ≤ ar2 + 1).

Print a single integer — the minimum number of times Vasya should push a key to move the cursor from position (r1, c1) to position (r2, c2).

NoteIn the first sample the editor contains four lines. Let's represent the cursor's possible positions in the line as numbers. Letter s represents the cursor's initial position, letter t represents the last one. Then all possible positions of the cursor in the text editor are described by the following table.12312123s5671t345One of the possible answers in the given sample is: "Left", "Down", "Left".

let chan = Scanf.Scanning.from_channel (open_in "input.txt")
let read_int () = Scanf.bscanf chan " %d " (fun x -> x)

let ochan = open_out "output.txt"
let print_string s = Printf.fprintf ochan "%s" s

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 () =
  let n = read_int() in
  let len = Array.init n (fun i -> read_int()) in
  let s  = -1 + read_int() in
  let c1 = -1 + read_int() in
  let t  = -1 + read_int() in
  let c2 = -1 + read_int() in

  let minc a b = (* min cursor position in the range a...b inclusive *)
    minf (min a b) (max a b) (fun i -> len.(i))
  in

  let score a b =
    (* the score of the path that goes s-->a-->b-->t *)
    let m = min (min (minc s a) (minc a b)) (min c1 (minc b t)) in
      (abs (s-a)) + (abs (a-b)) + (abs (b-t)) + (abs (c2-m))
  in

  let answer = minf 0 (n-1) (fun a -> minf 0 (n-1) (fun b -> score a b)) in
    print_string (string_of_int answer);
    print_string "\n"

let chan = Scanf.Scanning.from_channel (open_in "input.txt")
let read_int () = Scanf.bscanf chan " %d " (fun x -> x)

let ochan = open_out "output.txt"
let print_string s = Printf.fprintf ochan "%s" s

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 () =
  let n = read_int() in
  let len = Array.init n (fun i -> read_int()) in
  let s  = -1 + read_int() in
  let c1 = -1 + read_int() in
  let t  = -1 + read_int() in
  let c2 = -1 + read_int() in

  let minc a b = (* min cursor position in the range a...b inclusive *)
    minf a b (fun i -> len.(i))
  in

  let score a b =
    (* the score of the path that goes s-->a-->b-->t *)
    let m = min (min (minc s a) (minc a b)) (min c1 (minc b t)) in
      (abs (s-a)) + (abs (a-b)) + (abs (b-t)) + (abs (c2-m))
  in

  let answer = minf 0 (n-1) (fun a -> minf 0 (n-1) (fun b -> score a b)) in
    print_string (string_of_int answer);
    print_string "\n"


There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all.Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this bid and bi is its size. Bids are given in chronological order, meaning bi < bi + 1 for all i < n. Moreover, participant never makes two bids in a row (no one updates his own bid), i.e. ai ≠ ai + 1 for all i < n.Now you are curious with the following question: who (and which bid) will win the auction if some participants were absent? Consider that if someone was absent, all his bids are just removed and no new bids are added.Note, that if during this imaginary exclusion of some participants it happens that some of the remaining participants makes a bid twice (or more times) in a row, only first of these bids is counted. For better understanding take a look at the samples.You have several questions in your mind, compute the answer for each of them.

The first line of the input contains an integer n (1 ≤ n ≤ 200 000) — the number of participants and bids. Each of the following n lines contains two integers ai and bi (1 ≤ ai ≤ n, 1 ≤ bi ≤ 109, bi < bi + 1) — the number of participant who made the i-th bid and the size of this bid. Next line contains an integer q (1 ≤ q ≤ 200 000) — the number of question you have in mind. Each of next q lines contains an integer k (1 ≤ k ≤ n), followed by k integers lj (1 ≤ lj ≤ n) — the number of people who are not coming in this question and their indices. It is guarenteed that lj values are different for a single question. It's guaranteed that the sum of k over all question won't exceed 200 000.

For each question print two integer — the index of the winner and the size of the winning bid. If there is no winner (there are no remaining bids at all), print two zeroes.

NoteConsider the first sample:   In the first question participant number 3 is absent so the sequence of bids looks as follows:   1 10  2 100  1 10 000  2 100 000  Participant number 2 wins with the bid 100 000. In the second question participants 2 and 3 are absent, so the sequence of bids looks:   1 10  1 10 000  The winner is, of course, participant number 1 but the winning bid is 10 instead of 10 000 as no one will ever increase his own bid (in this problem).  In the third question participants 1 and 2 are absent and the sequence is:   3 1 000  3 1 000 000  The winner is participant 3 with the bid 1 000.

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

module IS = Set.Make(Int)
module IM = Map.Make(Int)

let add map x bid =
	if IM.mem x map
		then IM.add x (IS.add bid (IM.find x map)) map
		else IM.add x (IS.singleton bid) map

let rec f map = function
	| [] -> map
	| (a,b)::l -> f (add map a b) l

let trans map =
	List.sort (fun a b -> - (compare a b))
	(IM.fold (fun x bids ans -> (IS.max_elt bids,x)::ans) map [])

let highers set x =
	let (_,_,a) = IS.split x set in
		a

let rec solve map set = function
	| (bid,x)::l when IS.mem x set -> solve map set l
	| x::(_,a)::l when IS.mem a set -> solve map set (x::l)
	| (_,x)::(a,_)::_ -> (IS.min_elt (highers (IM.find x map) a),x)
	| [_,x] -> (IS.min_elt (IM.find x map),x)
	| [] -> (0,0)

let finish req map =
	let l = trans map in
		Printf.printf "LOL\n";
		List.iter (fun (a,b) -> Printf.printf "%d %d\n" a b) l;
		Printf.printf "LOL\n";
		solve map req l

let _ =
	let n = Scanf.scanf "%d" (fun i -> i) in
	let inputs = Array.init n (fun _ -> Scanf.scanf " %d %d"
		(fun a b -> (a,b))) in
	let map = Array.fold_right (fun (a,b) map -> add map a b)
		inputs IM.empty
	in
	let l = trans map in
	let q = Scanf.scanf " %d" (fun q -> q) in
		for i = 1 to q do
			let set = ref IS.empty in
			let sz = Scanf.scanf " %d" (fun sz -> sz) in
				for i = 1 to sz do
					Scanf.scanf " %d" (fun x -> set := IS.add x !set)
				done;
				let (x,y) = solve map !set l in
					Printf.printf "%d %d\n" y x
		done


Bash wants to become a Pokemon master one day. Although he liked a lot of Pokemon, he has always been fascinated by Bulbasaur the most. Soon, things started getting serious and his fascination turned into an obsession. Since he is too young to go out and catch Bulbasaur, he came up with his own way of catching a Bulbasaur.Each day, he takes the front page of the newspaper. He cuts out the letters one at a time, from anywhere on the front page of the newspaper to form the word "Bulbasaur" (without quotes) and sticks it on his wall. Bash is very particular about case — the first letter of "Bulbasaur" must be upper case and the rest must be lower case. By doing this he thinks he has caught one Bulbasaur. He then repeats this step on the left over part of the newspaper. He keeps doing this until it is not possible to form the word "Bulbasaur" from the newspaper.Given the text on the front page of the newspaper, can you tell how many Bulbasaurs he will catch today?Note: uppercase and lowercase letters are considered different.

Input contains a single line containing a string s (1  ≤  |s|  ≤  105) — the text on the front page of the newspaper without spaces and punctuation marks. |s| is the length of the string s. The string s contains lowercase and uppercase English letters, i.e. .

Output a single integer, the answer to the problem.

NoteIn the first case, you could pick: Bulbbasaur.In the second case, there is no way to pick even a single Bulbasaur.In the third case, you can rearrange the string to BulbasaurBulbasauraddrgndgddgargndbb to get two words "Bulbasaur".

let yolo hasht x =
	try
		Hashtbl.find hasht x
	with _ -> 0

let _ =
	let hasht = Hashtbl.create 0 in
	let s = Scanf.scanf "%s" (fun s -> s) in
		for i = 0 to String.length s - 1 do
			let x = s.[i] in
			let a = yolo hasht x in
				Hashtbl.add hasht x (a+1)
		done;
	let bleu = List.fold_left min max_int
		(List.map (yolo hasht) ['B';'l';'b';'s';'r'])
	in
	let rouge = min bleu ((yolo hasht 'u') / 2) in
	let vert = min rouge ((yolo hasht 'a') / 2) in
		print_int vert

let _ =
  let sb = Scanf.Scanning.stdib in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let a = Array.make 256 0 in
  let _ =
    for i = 0 to String.length s - 1 do
      let c = Char.code s.[i] in
	a.(c) <- a.(c) + 1
    done;
  in
  let r = a.(Char.code 'B') in
  let r = min r (a.(Char.code 'u') / 2) in
  let r = min r a.(Char.code 'l') in
  let r = min r a.(Char.code 'b') in
  let r = min r (a.(Char.code 'a') / 2) in
  let r = min r a.(Char.code 's') in
  let r = min r a.(Char.code 'r') in
    Printf.printf "%d\n" r

open Printf
open Scanf

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let sum i j f = fold i j (fun i a -> (f i) + a) 0

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

  let count c = sum 0 (n-1) (fun i -> if s.[i] = c then 1 else 0) in
  let nB = count 'B' in
  let ns = count 's' in
  let nl = count 'l' in
  let nu = count 'u' in
  let nr = count 'r' in
  let na = count 'a' in
  let nb = count 'b' in

  let answer = min nB (min (nu/2) (min nl (min nb (min (na/2) (min ns nr))))) in

  printf "%d\n" answer


Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.Now let's imagine a typical morning in your family. You haven't woken up yet, and Mom is already going to work. She has been so hasty that she has nearly forgotten to leave the two of her darling children some money to buy lunches in the school cafeteria. She fished in the purse and found some number of coins, or to be exact, n coins of arbitrary values a1, a2, ..., an. But as Mom was running out of time, she didn't split the coins for you two. So she scribbled a note asking you to split the money equally.As you woke up, you found Mom's coins and read her note. "But why split the money equally?" — you thought. After all, your twin is sleeping and he won't know anything. So you decided to act like that: pick for yourself some subset of coins so that the sum of values of your coins is strictly larger than the sum of values of the remaining coins that your twin will have. However, you correctly thought that if you take too many coins, the twin will suspect the deception. So, you've decided to stick to the following strategy to avoid suspicions: you take the minimum number of coins, whose sum of values is strictly more than the sum of values of the remaining coins. On this basis, determine what minimum number of coins you need to take to divide them in the described manner.

The first line contains integer n (1 ≤ n ≤ 100) — the number of coins. The second line contains a sequence of n integers a1, a2, ..., an (1 ≤ ai ≤ 100) — the coins' values. All numbers are separated with spaces.

In the single line print the single number — the minimum needed number of coins.

NoteIn the first sample you will have to take 2 coins (you and your twin have sums equal to 6, 0 correspondingly). If you take 1 coin, you get sums 3, 3. If you take 0 coins, you get sums 0, 6. Those variants do not satisfy you as your sum should be strictly more that your twins' sum.In the second sample one coin isn't enough for us, too. You can pick coins with values 1, 2 or 2, 2. In any case, the minimum number of coins equals 2.

let input () = let number_of_coins = Scanf.scanf "%d " (fun n -> n) in
    (*List.init number_of_coins (fun _ -> Scanf.scanf "%d " (fun n -> n))
    *)
    let rec read list n =
        if n > 0
        then
            let var = Scanf.scanf "%d " (fun n -> n) in
            read (var :: list) (n - 1)
        else
            list
    in read [] number_of_coins

let sort list = List.rev(List.sort(Pervasives.compare) list)

let get_total list = List.fold_left(fun a b -> a + b) 0 list

let more_than_half total = (total / 2) + 1

let get_big_coins list amount =
    let rec loop list amount count =
        if amount > 0
        then
            match list with
            |(a :: tail) -> loop tail (amount - a) (count + 1)
            |[] -> failwith "No money. Now cry"
        else
            count
    in loop list amount 0

let solve input = get_big_coins (sort input)(more_than_half(get_total input))

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

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

open Array;;
let main () =
    let a = ref 0
    in let summ = ref 0
    in let n = read_int ()
    in let f n =
        let tmp = Scanf.scanf "%d " (fun x->x)  in
            summ := !summ + tmp; tmp
    in let ar =  init n f
    in fast_sort (-) ar;
      for i = n-1 downto 0 do
            if !a > !summ then( print_int (n-1-i);exit 0)
            else( a:= !a + ar.(i); summ:= !summ - ar.(i); ())
        done;
        print_int n
;;
main()

let sum seq = List.fold_left (+) 0 seq;;

let coins lst =
  let rec inner llst num get rest =
    if rest < get then
      num
    else
      let curr = List.hd llst
      in
      inner (List.tl llst) (num + 1) (get + curr) (rest - curr)
  in
  inner lst 0 0 (sum lst);;

let () =
  let arr = Scanf.scanf "%d "
                        (fun n -> Array.init
                                    n
                                    (fun _ -> Scanf.scanf "%d " (fun m -> m))) in
  let _ = Array.fast_sort compare arr
  in
  Printf.printf "%d\n" (coins (List.rev (Array.to_list arr)));;

open Scanf
open Printf

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

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

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

let sum = Array.fold_left (fun x y -> x + y ) 0 a

let () = Array.sort (fun x y -> y - x) a

(*
let () = printf "%d \n" sum
let () = Array.iter (fun x -> printf "%d " x) a
*)

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

open Array;;
let main () =
    let a = ref 0
    in let summ = ref 0
    in let n = read_int ()
    in let f n =
        let tmp = Scanf.scanf "%d " (fun x->x)  in
            summ := !summ + tmp; tmp
    in let ar =  init n f
    in fast_sort (-) ar;
      for i = n-1 downto 0 do
            if !a > !summ then( print_int (i-1);exit 0)
            else( a:= !a + ar.(i); summ:= !summ - ar.(i); ())
        done;
        print_int n
;;
main()

let sum seq = List.fold_left (+) 0 seq;;

let coins lst =
  let rec inner llst num get rest =
    if rest < get then
      num
    else
      let curr = List.hd llst
      in
      inner (List.tl llst) (num + 1) (get + curr) (rest - curr)
  in
  inner lst 0 0 (sum lst);;

let () =
  let arr = Scanf.scanf "%d "
                        (fun n -> Array.init
                                    n
                                    (fun _ -> Scanf.scanf "%d " (fun m -> m))) in
  let _ = Array.fast_sort compare arr
  in
  Printf.printf "%d\n" (coins (Array.to_list arr));;


Pashmak has fallen in love with an attractive girl called Parmida since one year ago...Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He also remembers that there is exactly one tree on each vertex of the square. Now, Pashmak knows the position of only two of the trees. Help him to find the position of two remaining ones.

The first line contains four space-separated x1, y1, x2, y2 ( - 100 ≤ x1, y1, x2, y2 ≤ 100) integers, where x1 and y1 are coordinates of the first tree and x2 and y2 are coordinates of the second tree. It's guaranteed that the given points are distinct.

If there is no solution to the problem, print -1. Otherwise print four space-separated integers x3, y3, x4, y4 that correspond to the coordinates of the two other trees. If there are several solutions you can output any of them.  Note that x3, y3, x4, y4 must be in the range ( - 1000 ≤ x3, y3, x4, y4 ≤ 1000).

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

let input () =
    let x1 = read () in
    let y1 = read () in
    let x2 = read () in
    let y2 = read () in
    (x1, y1, x2, y2)

let solve (x1, y1, x2, y2) =
    let lx = Pervasives.abs (x1 - x2) in
    let ly = Pervasives.abs (y1 - y2) in
    if lx = 0
    then
        let x3 = ly + x1 in
        let x4 = ly + x2 in
        [x3; y1; x4; y2]
    else
        if ly = 0
        then
            let y3 = lx + y1 in
            let y4 = lx + y2 in
            [x1; y3; x2; y4]
        else
            if lx = ly
            then
                [x1; y2; x2; y1]
            else
                [-1]

let print result = List.iter (Printf.printf "%d ") result

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


After bracket sequences Arthur took up number theory. He has got a new favorite sequence of length n (a1, a2, ..., an), consisting of integers and integer k, not exceeding n.This sequence had the following property: if you write out the sums of all its segments consisting of k consecutive elements (a1  +  a2 ...  +  ak,  a2  +  a3  +  ...  +  ak + 1,  ...,  an - k + 1  +  an - k + 2  +  ...  +  an), then those numbers will form strictly increasing sequence.For example, for the following sample: n = 5,  k = 3,  a = (1,  2,  4,  5,  6) the sequence of numbers will look as follows: (1  +  2  +  4,  2  +  4  +  5,  4  +  5  +  6) = (7,  11,  15), that means that sequence a meets the described property. Obviously the sequence of sums will have n - k + 1 elements.Somebody (we won't say who) replaced some numbers in Arthur's sequence by question marks (if this number is replaced, it is replaced by exactly one question mark). We need to restore the sequence so that it meets the required property and also minimize the sum |ai|, where |ai| is the absolute value of ai.

The first line contains two integers n and k (1 ≤ k ≤ n ≤ 105), showing how many numbers are in Arthur's sequence and the lengths of segments respectively. The next line contains n space-separated elements ai (1 ≤ i ≤ n). If ai  =  ?, then the i-th element of Arthur's sequence was replaced by a question mark.  Otherwise, ai ( - 109 ≤ ai ≤ 109) is the i-th element of Arthur's sequence.

If Arthur is wrong at some point and there is no sequence that could fit the given information, print a single string "Incorrect sequence" (without the quotes). Otherwise, print n integers — Arthur's favorite sequence. If there are multiple such sequences, print the sequence with the minimum sum |ai|, where |ai| is the absolute value of ai. If there are still several such sequences, you are allowed to print any of them. Print the elements of the sequence without leading zeroes.

0 1 2
-10 -9 -8 -7 -6
Incorrect sequence

open Printf
open Scanf

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

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

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

  let q = Array.make n false in

  let a = Array.make n 0 in

  for i=0 to n-1 do
    let s = read_string () in
    if s="?" then q.(i) <- true
    else a.(i) <- int_of_string s;
  done;

  let verify (st,en) =
  (* the chain is [st, st+k, st+2k, ..., en].  If the chain is valid (or
     can be made valid by filling in the variables), set its variables
     to their optimum values, and return true.  otherwise return
     false. The starting point st could be < 0 indicating before the
     start, and en could be >= n, indicating after the end.  *)

    let len = (en-st)/k - 1 in  (* number of variables inside the chain *)
    for i=1 to len do
      a.(st+i*k) <- i-1-(len/2);
    done;

    if st>=0 && st+k<n && a.(st) >= a.(st+k) then (
      (* first constraint violated, so push up all the values *)
      let delta = a.(st) - a.(st+k) + 1 in
      for i=1 to len do
	a.(st+i*k) <- a.(st+i*k) + delta
      done;
      en >=n || en-k<0 || a.(en-k) < a.(en)
    ) else if en<n && en-k >= 0 && a.(en-k) >= a.(en) then (
      let delta = a.(en-k) - a.(en) + 1 in
      for i=1 to len do
	a.(st+i*k) <- a.(st+i*k) - delta
      done;
      st<0 || st+k>=n || a.(st) < a.(st+k)
    ) else true
  in

  let ans = forall 0 (k-1) (
    fun i ->
      let rec loop j = if j>=n then true else
	  let rec chain j =
	    if j>=n || not q.(j) then j
	    else chain (j+k)
	  in

	  let endchain = chain j in
	  let startchain = j-k in
	  (verify (startchain, endchain)) && loop (endchain+k)
      in
      loop i
  )
  in

  if ans then (
    for i=0 to n-1 do
      printf "%d " a.(i)
    done;
    print_newline()
  ) else (
    printf "Incorrect sequence\n"
  )


Author has gone out of the stories about Vasiliy, so here is just a formal task description.You are given q queries and a multiset A, initially containing only integer 0. There are three types of queries:  "+ x" — add integer x to multiset A. "- x" — erase one occurrence of integer x from multiset A. It's guaranteed that at least one x is present in the multiset A before this query. "? x" — you are given integer x and need to compute the value , i.e. the maximum value of bitwise exclusive OR (also know as XOR) of integer x and some integer y from the multiset A.Multiset is a set, where equal elements are allowed.

The first line of the input contains a single integer q (1 ≤ q ≤ 200 000) — the number of queries Vasiliy has to perform. Each of the following q lines of the input contains one of three characters '+', '-' or '?' and an integer xi (1 ≤ xi ≤ 109). It's guaranteed that there is at least one query of the third type. Note, that the integer 0 will always be present in the set A.

For each query of the type '?' print one integer — the maximum value of bitwise exclusive OR (XOR) of integer xi and some integer from the multiset A.

NoteAfter first five operations multiset A contains integers 0, 8, 9, 11, 6 and 1.The answer for the sixth query is integer  — maximum among integers , , ,  and .

type tree = Leaf | Node of tree * tree * int

let rec chain d x =
  if d = -1 then Node (Leaf,Leaf,1) else
    if x land (1 lsl d) = 0 then Node (chain (d-1) x, Leaf, 1)
    else Node (Leaf, chain (d-1) x, 1)

let rec insert t d x =
  match t with
    | Leaf -> chain d x
    | Node (l,r,size) ->
      if d = -1 then Node (l,r,size+1)
      else if x land (1 lsl d) = 0 then Node (insert l (d-1) x, r, size+1)
      else Node (l, insert r (d-1) x, size+1)

let rec delete t d x =
  match t with
    | Leaf -> failwith "deleting from leaf"
    | Node (l,r,size) ->
      if size = 1 then Leaf
      else if d = -1 then Node (l, r, size-1)
      else if x land (1 lsl d) = 0 then Node (delete l (d-1) x, r, size-1)
      else Node (l, delete r (d-1) x, size-1)

let rec find t d x ac =
  match t with
    | Leaf -> failwith "failed find"
    | Node (l,r,size) ->
      let bit = (x lsr d) land 1 in
      if l <> Leaf && bit = 1 then find l (d-1) x (ac + (1 lsl d))
      else if r <> Leaf && bit = 0 then find r (d-1) x (ac + (1 lsl d))
      else if l <> Leaf then find l (d-1) x ac
      else if r <> Leaf then find r (d-1) x ac
      else ac

open Printf
open Scanf

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

let () =
  let q = read_int () in

  let rec loop t i = if i<q then
      let command = read_string() in
      let x = read_int() in
      match command with
	| "+" -> loop (insert t 29 x) (i+1)
	| "-" -> loop (delete t 29 x) (i+1)
	| "?" ->
	  let answer = (find t 29 x 0) in
	  printf "%d\n" answer;
	  loop t (i+1)
	| _ -> failwith "bad input"
  in

  let t = insert Leaf 29 0 in
  loop t 0


You are given an array $$$a_1, a_2, \dots , a_n$$$ consisting of integers from $$$0$$$ to $$$9$$$. A subarray $$$a_l, a_{l+1}, a_{l+2}, \dots , a_{r-1}, a_r$$$ is good if the sum of elements of this subarray is equal to the length of this subarray ($$$\sum\limits_{i=l}^{r} a_i = r - l + 1$$$).For example, if $$$a = [1, 2, 0]$$$, then there are $$$3$$$ good subarrays: $$$a_{1 \dots 1} = [1], a_{2 \dots 3} = [2, 0]$$$ and $$$a_{1 \dots 3} = [1, 2, 0]$$$.Calculate the number of good subarrays of the array $$$a$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the array $$$a$$$. The second line of each test case contains a string consisting of $$$n$$$ decimal digits, where the $$$i$$$-th digit is equal to the value of $$$a_i$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print one integer — the number of good subarrays of the array $$$a$$$.

NoteThe first test case is considered in the statement.In the second test case, there are $$$6$$$ good subarrays: $$$a_{1 \dots 1}$$$, $$$a_{2 \dots 2}$$$, $$$a_{1 \dots 2}$$$, $$$a_{4 \dots 4}$$$, $$$a_{5 \dots 5}$$$ and $$$a_{4 \dots 5}$$$. In the third test case there is only one good subarray: $$$a_{2 \dots 6}$$$.

(* 给定一个仅含 0 到 9 的串，找出有多少个 good subarray *)
(* (Definition) good subarray: the sum of elements of this subarray is equal to the length of this subarray *)

let explode str =
  let len = String.length str in
  let rec f accu i =
    if i = len then accu
    else f (Int64.of_int (Char.code str.[i] - Char.code '1') :: accu) (i + 1)
  in
  f [] 0 |> List.rev

module SumValues = struct
  include Map.Make (Int64)

  let touch key m =
    let count =
      match mem key m with false -> 1L | true -> Int64.add 1L (find key m)
    in
    add key count m
end

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

  for i = 0 to test_cases - 1 do
    let len = Scanf.scanf " %d" (fun x -> x) in

    let xs = Scanf.scanf " %s" explode in

    let f (r, sum, map) x =
      let sum' = Int64.add sum x in
      let r' =
        match SumValues.mem sum' map with
        | true -> Int64.add r (SumValues.find sum' map)
        | false -> r
      in
      (r', sum', SumValues.touch sum' map)
    in
    let r, _, _ = List.fold_left f (0L, 0L, SumValues.(add 0L 1L empty)) xs in

    print_endline (Int64.to_string r)
  done

(* 给定一个仅含 0 到 9 的串，找出有多少个 good subarray *)
(* (Definition) good subarray: the sum of elements of this subarray is equal to the length of this subarray *)

let explode str =
  let len = String.length str in
  let rec f accu i =
    if i = len then accu
    else f ((Char.code str.[i] - Char.code '1') :: accu) (i + 1)
  in
  f [] 0 |> List.rev

module SumValues = struct
  include Map.Make (struct
    type t = int

    let compare = compare
  end)

  let touch key m =
    let count = match mem key m with false -> 1 | true -> 1 + find key m in
    add key count m
end

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

  for i = 0 to test_cases - 1 do
    let len = Scanf.scanf " %d" (fun x -> x) in

    let xs = Scanf.scanf " %s" explode in

    let f (r, sum, map) x =
      let sum' = sum + x in
      let r' =
        match SumValues.mem sum' map with
        | true -> r + SumValues.find sum' map
        | false -> r
      in
      (r', sum', SumValues.touch sum' map)
    in
    let r, _, _ = List.fold_left f (0, 0, SumValues.(add 0 1 empty)) xs in

    print_endline (string_of_int r)
  done


Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing numbers 1 and 0. The boys are very superstitious. They think that they can do well at the Olympiad if they begin with laying all the cards in a row so that:  there wouldn't be a pair of any side-adjacent cards with zeroes in a row;  there wouldn't be a group of three consecutive cards containing numbers one. Today Vanya brought n cards with zeroes and m cards with numbers one. The number of cards was so much that the friends do not know how to put all those cards in the described way. Help them find the required arrangement of the cards or else tell the guys that it is impossible to arrange cards in such a way.

The first line contains two integers: n (1 ≤ n ≤ 106) — the number of cards containing number 0; m (1 ≤ m ≤ 106) — the number of cards containing number 1.

In a single line print the required sequence of zeroes and ones without any spaces. If such sequence is impossible to obtain, print -1.

open Printf
open Scanf

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

  let overlap (a,b) (c,d) =  max a c  <=  min b d in

  let possible n m startwith =  (* n zeros, m ones *)
    let bal n m =
      let zlo = n in
      let zhi = n in
      let olo = (m+1)/2 in
      let ohi = m in
      n>=0 && m>=0 && overlap (zlo,zhi) (olo,ohi)
    in
    if bal n m  then true else
      if startwith = 0 then bal (n-1) m
      else bal n (m-1) || bal n (m-2)
  in

  let mcount = [|1;2|]in

  if not (possible n m 0 || possible n m 1) then printf "-1\n" else (

    let rec loop current maxremain n m =
      if m=0 && n=0 then ()
      else if n=0 then (printf "1"; loop 1 (maxremain-1) n (m-1))
      else if m=0 then (printf "0"; loop 0 (maxremain-1) (n-1) m)
      else (
	if maxremain = 0 then (
	  let current = 1-current in
	  loop current mcount.(current) n m
	) else (
	  let nc = if possible n m current then current else 1-current in
	  printf "%d" nc;
	  let n = if nc = 0 then n-1 else n in
	  let m = if nc = 1 then m-1 else m in
	  let maxremain = if nc=current then maxremain-1 else mcount.(nc)-1 in
	  loop nc maxremain n m
	)
      )
    in

    let current = if possible n m 1 then 1 else 0 in
    printf "%d" current;
    let n = if current = 0 then n-1 else n in
    let m = if current = 1 then m-1 else m in
    loop current (mcount.(current) - 1) n m;
    printf "\n"

  )

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

let rec print_list a b=
if b>a+1 then (if b=2 then print_int 11 else (print_int 110;print_list (a-1) (b-2)))
else if a>b then (print_int 0;print_list (a-1) b)
else if (a=b)&&(a<>0) then (print_int 10;print_list (a-1) (b-1))
else if a+1=b then (if b=1 then print_int 1 else (print_int 10;print_list (a-1) (b-1)));;

if n>m+1 then print_int (-1)
else if (m/2)+(m mod 2)>n+1 then print_int (-1)
else print_list n m;;

open Printf
open Scanf

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

  let overlap (a,b) (c,d) =  max a c  <=  min b d in

  let possible n m startwith =  (* n zeros, m ones *)
    let bal n m =
      let zlo = (n+1)/2 in
      let zhi = n in
      let olo = (m+1)/2 in
      let ohi = m in
      n>=0 && m>=0 && overlap (zlo,zhi) (olo,ohi)
    in
    if bal n m  then true else
      if startwith = 0 then bal (n-1) m || bal (n-2) m
      else bal n (m-1) || bal n (m-2)
  in

  let mcount = [|2;2|]in

  if not (possible n m 0 || possible n m 1) then printf "-1\n" else (

    let rec loop current maxremain n m =
      if m=0 && n=0 then ()
      else if n=0 then (printf "1"; loop 1 (maxremain-1) n (m-1))
      else if m=0 then (printf "0"; loop 0 (maxremain-1) (n-1) m)
      else (
	if maxremain = 0 then (
	  let current = 1-current in
	  loop current mcount.(current) n m
	) else (
	  let nc = if possible n m current then current else 1-current in
	  printf "%d" nc;
	  let n = if nc = 0 then n-1 else n in
	  let m = if nc = 1 then m-1 else m in
	  let maxremain = if nc=current then maxremain-1 else mcount.(nc)-1 in
	  loop nc maxremain n m
	)
      )
    in

    let current = if possible n m 1 then 1 else 0 in
    printf "%d" current;
    let n = if current = 0 then n-1 else n in
    let m = if current = 1 then m-1 else m in
    loop current (mcount.(current) - 1) n m;
    printf "\n"

  )


ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has n rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.ZS and Chris are good friends. They insist to get a pair of neighbouring empty seats. Two seats are considered neighbouring if they are in the same row and in the same pair. Given the configuration of the bus, can you help ZS and Chris determine where they should sit?

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of rows of seats in the bus. Then, n lines follow. Each line contains exactly 5 characters, the first two of them denote the first pair of seats in the row, the third character denotes the walkway (it always equals '|') and the last two of them denote the second pair of seats in the row.  Each character, except the walkway, equals to 'O' or to 'X'. 'O' denotes an empty seat, 'X' denotes an occupied seat. See the sample cases for more details.

If it is possible for Chris and ZS to sit at neighbouring empty seats, print "YES" (without quotes) in the first line. In the next n lines print the bus configuration, where the characters in the pair of seats for Chris and ZS is changed with characters '+'. Thus the configuration should differ from the input one by exactly two charaters (they should be equal to 'O' in the input and to '+' in the output). If there is no pair of seats for Chris and ZS, print "NO" (without quotes) in a single line. If there are multiple solutions, you may print any of them.

NoteNote that the following is an incorrect configuration for the first sample case because the seats must be in the same pair.O+|+XXO|XXOX|OOXX|OXOO|OOOO|XX

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 mod_first list f =
    let rec loop prev list =
        match list with
        | [] -> None
        | (hd :: tl) ->
            match (f hd) with
            | None -> loop (hd :: prev) tl
            | Some hd' -> Some (List.rev_append (hd' :: prev) tl)
    in loop [] list

let read_input () =
    let n = Scanf.scanf "%d " (fun n -> n) in
    let read_row () = Scanf.scanf "%c%c%c%c%c " (fun a b c d e -> ((a, b) :: (d, e) :: [])) in
    let bus = list_init n (fun _ -> read_row ()) in
    bus

let seat bus = mod_first bus (fun row -> mod_first row (fun pair ->
    if pair = ('O', 'O')
    then
        Some ('+', '+')
    else
        None))

let print_row row =
    match row with
    | [a, b; c, d] -> Printf.printf "%c%c|%c%c\n" a b c d
    | _ -> failwith "Invalid bus"

let print_bus bus =
    match bus with
    | Some bus ->
        Printf.printf "YES\n";
        List.iter print_row bus
    | _ -> Printf.printf "NO\n"

let () = print_bus (seat (read_input ()))

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 mod_first list f =
    let rec loop prev list =
        match list with
        | [] -> None
        | (hd :: tl) ->
            match (f hd) with
            | None -> loop (hd :: prev) tl
            | Some hd' -> Some (List.rev_append (hd' :: prev) tl)
    in loop [] list

let read_input () =
    let n = Scanf.scanf "%d " (fun n -> n) in
    let read_row () = Scanf.scanf "%c%c%c%c%c " (fun a b c d e -> ((a, b) :: (d, e) :: [])) in
    let bus = list_init n (fun _ -> read_row ()) in
    bus

let seat bus = mod_first bus (fun row -> mod_first row (fun pair ->
    if pair = ('O', 'O')
    then
        Some ('+', '+')
    else
        None))

let print_char char =
    Printf.printf "%c" char

let print_str str =
    Printf.printf "%s\n" str

let print_side (a, b) =
    Printf.printf "%c%c" a b

let print_row row =
    match row with
    | [left; right] ->
        print_side left;
        print_char '|';
        print_side right;
        print_char '\n'
    | _ -> failwith "Invalid bus"

let print_bus bus =
    match bus with
    | Some bus ->
        print_str "YES";
        List.iter print_row bus
    | _ -> print_str "NO"

let () = print_bus (seat (read_input ()))

let read_int () = Scanf.scanf "%d " (fun n -> n)
let read_char () = Scanf.scanf "%c " (fun c -> c)
let print option =
    match option with
    | Some array -> Printf.printf "YES\n";
        Array.iter (fun row ->
            Array.iter (Printf.printf "%c") row;
            Printf.printf "\n") array
    | None -> Printf.printf "NO\n"

let input () =
    let n = read_int () in
    let all_rows = Array.init n (fun _ -> Array.init 5 (fun _ -> read_char ())) in
    (all_rows, n)

let modify row =
    let rec loop i =
        if i < 5
        then
            let char = row.(i) in
            let prev = row.(i - 1) in
            if char = 'O' && char = prev
            then
                (Array.set row i '+';
                Array.set row (i - 1) '+';
                true)
            else
                loop (i + 1)
        else
            false
    in loop 1

let solve (all_rows, n) =
    let rec loop i =
        if i < n
        then
            let row = all_rows.(i) in
            if modify row
            then
                Some all_rows
            else
                loop (i + 1)
        else
            None
    in loop 0

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

open Scanf

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

type result =
    | YES of (char * char * char * char) list
    | NO

let print_result (r:result) =
    match r with
    | NO -> print_string "NO"
    | YES l ->
        match l with
        | [] -> print_string "NO"
        | l ->
            print_string "YES\n";
            let rec print result_l =
                match result_l with
                | [] -> print_string ""
                | (a,b,c,d)::tl ->
                    Printf.printf "%c%c|%c%c\n" a b c d;
                    print tl
            in print l

let find_and_replace_seats row_arr =
    let row_l = Array.to_list row_arr in
    let rec helper acc row_l =
        match row_l with
        | [] -> NO
        | (a,b,c,d)::tl ->
            if a = 'O' && b = 'O' then YES (List.rev (List.rev tl @ [('+','+',c,d)] @ acc))
            else if c = 'O' && d = 'O' then YES (List.rev (List.rev tl @ [(a,b,'+','+')] @ acc))
            else helper ((a,b,c,d)::acc) tl
    in helper [] row_l

let () =
    let n = read_int () in
    let row_arr = Array.init n (fun _ ->
        let input = read_string () in
        let a = input.[0] in
        let b = input.[1] in
        let c = input.[3] in
        let d = input.[4] in
        (a,b,c,d)
    )
    in
    find_and_replace_seats row_arr
    |> print_result