Little Susie loves strings. Today she calculates distances between them. As Susie is a small girl after all, her strings contain only digits zero and one. She uses the definition of Hamming distance:We will define the distance between two strings s and t of the same length consisting of digits zero and one as the number of positions i, such that si isn't equal to ti. As besides everything else Susie loves symmetry, she wants to find for two strings s and t of length n such string p of length n, that the distance from p to s was equal to the distance from p to t.It's time for Susie to go to bed, help her find such string p or state that it is impossible.

The first line contains string s of length n.  The second line contains string t of length n. The length of string n is within range from 1 to 105. It is guaranteed that both strings contain only digits zero and one.

Print a string of length n, consisting of digits zero and one, that meets the problem statement. If no such string exist, print on a single line "impossible" (without the quotes). If there are multiple possible answers, print any of them.

NoteIn the first sample different answers are possible, namely — 0010, 0011, 0110, 0111, 1000, 1001, 1100, 1101.

let list_of_string s =
  let rec loc i acc =
    if i < 0
    then acc
    else loc (i - 1) (String.get s i :: acc)
  in
  loc (String.length s - 1) []

let combine s t =
  let rec loc acc s t =
    match s, t with
    | [],      []      -> acc
    | x :: rs, y :: rt -> loc ((x, y) :: acc) rs rt
    | _,       _       -> invalid_arg ""
  in
  List.rev (loc [] s t)

exception Impossible

let solve a b =

  let la = list_of_string a
  and lb = list_of_string b in
  let l = combine la lb in
  let n = List.length l in

  let diff =
    List.fold_left
      (fun acc (ca, cb) -> if ca <> cb then acc + 1 else acc)
      0
      l
  in
  if diff mod 2 <> 0 then raise Impossible;

  let ans = String.create n in
  let rec loc i j = function
    | [] -> ()
    | (ca, cb) :: rest ->
      if ca = cb
      then (String.set ans i ca; loc (i + 1) j rest)
      else
        begin
          if j < diff / 2
          then (String.set ans i ca; loc (i + 1) (j + 1) rest)
          else (String.set ans i cb; loc (i + 1) (j + 1) rest)
        end
  in
  loc 0 0 l;
  ans

(* let mk n = String.init n (fun _ -> if Random.bool () then '0' else '1') *)

let _ =
  (* print_endline (mk 100000); *)
  (* print_endline (mk 100000); *)

  let a = read_line ()
  and b = read_line () in
  let ans =
    try solve a b
    with Impossible -> "impossible"
  in
  print_endline ans

let _ =
	let (s1,s2) = Scanf.scanf "%s %s" (fun i j -> (i,j)) in
	let res = String.copy s1 and flg = ref true in
	for i=0 to String.length res - 1 do
		if res.[i] <> s2.[i]
			then begin
				flg := not !flg;
				if !flg
					then res.[i] <- s2.[i]
			      end;
	done;
	Printf.printf "%s" (if !flg then res else "impossible")

let list_of_string s =
  let rec loc i acc =
    if i < 0
    then acc
    else loc (i - 1) (String.get s i :: acc)
  in
  loc (String.length s - 1) []

let combine s t =
  let rec loc acc s t =
    match s, t with
    | [],      []      -> acc
    | x :: rs, y :: rt -> loc ((x, y) :: acc) rs rt
    | _,       _       -> invalid_arg ""
  in
  List.rev (loc [] s t)

exception Impossible

let solve a b =

  let la = list_of_string a
  and lb = list_of_string b in
  let l = combine la lb in
  let n = List.length l in

  let diff =
    List.fold_left
      (fun acc (ca, cb) -> if ca <> cb then acc + 1 else acc)
      0
      l
  in
  if diff mod 2 <> 0 then raise Impossible;

  let ans = String.create n in
  List.iteri
    (fun i (ca, cb) ->
       if i < n / 2
       then String.set ans i ca
       else String.set ans i cb)
    l;
  ans

(* let mk n = String.init n (fun _ -> if Random.bool () then '0' else '1') *)

let _ =
  (* print_endline (mk 100000); *)
  (* print_endline (mk 100000); *)

  let a = read_line ()
  and b = read_line () in
  let ans =
    try solve a b
    with Impossible -> "impossible"
  in
  print_endline ans


You are given n switches and m lamps. The i-th switch turns on some subset of the lamps. This information is given as the matrix a consisting of n rows and m columns where ai, j = 1 if the i-th switch turns on the j-th lamp and ai, j = 0 if the i-th switch is not connected to the j-th lamp.Initially all m lamps are turned off.Switches change state only from "off" to "on". It means that if you press two or more switches connected to the same lamp then the lamp will be turned on after any of this switches is pressed and will remain its state even if any switch connected to this lamp is pressed afterwards.It is guaranteed that if you push all n switches then all m lamps will be turned on.Your think that you have too many switches and you would like to ignore one of them. Your task is to say if there exists such a switch that if you will ignore (not use) it but press all the other n - 1 switches then all the m lamps will be turned on.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 2000) — the number of the switches and the number of the lamps. The following n lines contain m characters each. The character ai, j is equal to '1' if the i-th switch turns on the j-th lamp and '0' otherwise. It is guaranteed that if you press all n switches all m lamps will be turned on.

Print "YES" if there is a switch that if you will ignore it and press all the other n - 1 switches then all m lamps will be turned on. Print "NO" if there is no such switch.

let _ =
  let n, m = Scanf.scanf " %u %u" (fun i j -> i, j) in
  (* n - #switch, m - #lamp *)
  let switches_of_lamp: (int list) array =
    Array.init m (fun _ -> [])
  in

  for i = 0 to n - 1 do
    let s = Scanf.scanf " %s" (fun i -> i) in
    for j = 0 to m - 1 do
      match String.get s j with
      | '1' -> switches_of_lamp.(j) <- i :: switches_of_lamp.(j)
      | _ -> ()
    done
  done;

  let rec f (switch: int): unit =
    if switch >= n
    then print_endline "NO"
    else
      let rec g (lamp: int): bool =
        let rec k (switch_inner: int list): bool =
          match switch_inner with
          | [] -> false
          | x :: xs when x = switch -> k xs
          | _ -> true
        in
        if lamp >= m
        then true
        else if k switches_of_lamp.(lamp)
        then g (lamp + 1)
        else false
      in
      if g 0 then print_endline "YES" else f (switch + 1)
  in
  f 0


Happy PMP is freshman and he is learning about algorithmic problems. He enjoys playing algorithmic games a lot.One of the seniors gave Happy PMP a nice game. He is given two permutations of numbers 1 through n and is asked to convert the first one to the second. In one move he can remove the last number from the permutation of numbers and inserts it back in an arbitrary position. He can either insert last number between any two consecutive numbers, or he can place it at the beginning of the permutation.Happy PMP has an algorithm that solves the problem. But it is not fast enough. He wants to know the minimum number of moves to convert the first permutation to the second.

The first line contains a single integer n (1 ≤ n ≤ 2·105) — the quantity of the numbers in the both given permutations.  Next line contains n space-separated integers — the first permutation. Each number between 1 to n will appear in the permutation exactly once.  Next line describe the second permutation in the same format.

Print a single integer denoting the minimum number of moves required to convert the first permutation to the second.

NoteIn the first sample, he removes number 1 from end of the list and places it at the beginning. After that he takes number 2 and places it between 1 and 3.In the second sample, he removes number 5 and inserts it after 1.In the third sample, the sequence of changes are like this:  1 5 2 3 4 1 4 5 2 3 1 3 4 5 2 1 2 3 4 5  So he needs three moves.

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let b = Array.make n 0 in
  let () =
    for i = 0 to n - 1 do
      let k = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
	a.(k) <- i
    done;
    for i = 0 to n - 1 do
      let k = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
	b.(a.(k)) <- i
    done;
  in
  let res = ref (n - 1) in
    (try
       for i = 1 to n - 1 do
	 if b.(i - 1) < b.(i) then (
	   decr res;
	 ) else raise Not_found
       done;
     with
       | Not_found -> ()
    );
    Printf.printf "%d\n" !res

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let b = Array.make n 0 in
  let () =
    for i = 0 to n - 1 do
      let k = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
	a.(k) <- i
    done;
    for i = 0 to n - 1 do
      let k = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
	b.(a.(k)) <- i
    done;
  in
  let res = ref 0 in
  let d = Array.make n false in
  let c = ref (n - 1) in
    for i = n - 1 downto 0 do
      if b.(i) <> !c then (
	incr res;
	d.(b.(i)) <- true;
      ) else (
	decr c
      );
      while !c >= 0 && d.(!c) do
	decr c
      done;
    done;
    Printf.printf "%d\n" !res


A permutation p of length n is a sequence of distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n). A permutation is an identity permutation, if for any i the following equation holds pi = i. A swap (i, j) is the operation that swaps elements pi and pj in the permutation. Let's assume that f(p) is the minimum number of swaps that you need to make the permutation p an identity permutation. Valera wonders, how he can transform permutation p into any permutation q, such that f(q) = m, using the minimum number of swaps. Help him do that.

The first line contains integer n (1 ≤ n ≤ 3000) — the length of permutation p. The second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — Valera's initial permutation. The last line contains integer m (0 ≤ m < n).

In the first line, print integer k — the minimum number of swaps. In the second line, print 2k integers x1, x2, ..., x2k — the description of the swap sequence. The printed numbers show that you need to consecutively make swaps (x1, x2), (x3, x4), ..., (x2k - 1, x2k).  If there are multiple sequence swaps of the minimum length, print the lexicographically minimum one.

NoteSequence x1, x2, ..., xs is lexicographically smaller than sequence y1, y2, ..., ys, if there is such integer r (1 ≤ r ≤ s), that x1 = y1, x2 = y2, ..., xr - 1 = yr - 1 and xr < yr.

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 split_cycles n m ncycles p mark =
  failwith "split_cycles called"

let merge_cycles n goal ncycles p mark =
  (* The algorithm is to find the smallest element not in
     cycle 0 and swap it with 0, thus putting it in cycle 0.
     The mark array already has 0s in it at cycle 0.  This is O(n).
  *)
  let rec build_swaps i ncyc ac = if ncyc=goal then List.rev ac else
      if mark.(i) = 0 then build_swaps (i+1) ncyc ac else
	let rec loop j = if j=i then () else (
	  mark.(j) <- 0;
	  loop p.(j)
	)
	in
	loop p.(i);
	build_swaps (i+1) (ncyc-1) ((0,i)::ac)
  in

  build_swaps 1 ncycles []

let split_cycles n goal ncycles p mark =
  let rec build_swaps i ncyc ac = if ncyc=goal then List.rev ac else
      if p.(i) = i then build_swaps (i+1) ncyc ac else
	let rec find_smallest j ac = if j=i then ac else
	    find_smallest p.(j) (min ac j)
	in
	let j = find_smallest p.(i) p.(i) in
	let (oi, oj) = (p.(i), p.(j)) in
	p.(i) <- oj;
	p.(j) <- oi;
	build_swaps i (ncyc+1) ((i,j)::ac)
  in
  build_swaps 0 ncycles []

let () =
  let n = read_int () in
  let p = Array.init n (fun _ -> read_int()-1) in
  let m = read_int () in
  let goal = n-m in (* number of cycles of the goal *)

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

  let rec dfs i c = if mark.(i) < 0 then (
    mark.(i) <- c;
    dfs p.(i) c
  ) in

  let rec count_cycles c i =
    if i=n then c
    else if mark.(i) >= 0 then count_cycles c (i+1) else (
      dfs i c;
      count_cycles (c+1) (i+1)
    )
  in

  let ncycles = count_cycles 0 0 in

  printf "%d\n" (abs (ncycles-goal));

  let answer =
    (if ncycles >= goal then merge_cycles else split_cycles) n goal ncycles p mark
  in

  List.iter (fun (i,j) -> printf "%d %d " (i+1) (j+1)) answer;
  print_newline();

open Printf
open Scanf

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

let merge_cycles n goal ncycles p mark =
  let rec build_swaps i ncyc ac = if ncyc=goal then List.rev ac else
      if mark.(i) = 0 then build_swaps (i+1) ncyc ac else
	let rec loop j = if j<>i then (
	  mark.(j) <- 0;
	  loop p.(j)
	)
	in
	loop p.(i);
	build_swaps (i+1) (ncyc-1) ((0,i)::ac)
  in
  build_swaps 1 ncycles []

let split_cycles n goal ncycles p mark =
  let rec build_swaps i ncyc ac = if ncyc=goal then List.rev ac else
      if p.(i) = i then build_swaps (i+1) ncyc ac else
	let rec find_smallest j ac = if j=i then ac else
	    find_smallest p.(j) (min ac j)
	in
	let j = find_smallest p.(i) p.(i) in
	let (oi, oj) = (p.(i), p.(j)) in
	p.(i) <- oj;
	p.(j) <- oi;
	build_swaps i (ncyc+1) ((i,j)::ac)
  in
  build_swaps 0 ncycles []

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

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

  let rec dfs i c = if mark.(i) < 0 then (
    mark.(i) <- c;
    dfs p.(i) c
  ) in

  let rec count_cycles c i =
    if i=n then c
    else if mark.(i) >= 0 then count_cycles c (i+1) else (
      dfs i c;
      count_cycles (c+1) (i+1)
    )
  in

  let ncycles = count_cycles 0 0 in

  printf "%d\n" (abs (ncycles-goal));

  let answer =
    (if ncycles >= goal then merge_cycles else split_cycles) n goal ncycles p mark
  in

  List.iter (fun (i,j) -> printf "%d %d " (i+1) (j+1)) answer;
  print_newline();


A group of tourists is going to kayak and catamaran tour. A rented lorry has arrived to the boat depot to take kayaks and catamarans to the point of departure. It's known that all kayaks are of the same size (and each of them occupies the space of 1 cubic metre), and all catamarans are of the same size, but two times bigger than kayaks (and occupy the space of 2 cubic metres).Each waterborne vehicle has a particular carrying capacity, and it should be noted that waterborne vehicles that look the same can have different carrying capacities. Knowing the truck body volume and the list of waterborne vehicles in the boat depot (for each one its type and carrying capacity are known), find out such set of vehicles that can be taken in the lorry, and that has the maximum total carrying capacity. The truck body volume of the lorry can be used effectively, that is to say you can always put into the lorry a waterborne vehicle that occupies the space not exceeding the free space left in the truck body.

The first line contains a pair of integer numbers n and v (1 ≤ n ≤ 105; 1 ≤ v ≤ 109), where n is the number of waterborne vehicles in the boat depot, and v is the truck body volume of the lorry in cubic metres. The following n lines contain the information about the waterborne vehicles, that is a pair of numbers ti, pi (1 ≤ ti ≤ 2; 1 ≤ pi ≤ 104), where ti is the vehicle type (1 – a kayak, 2 – a catamaran), and pi is its carrying capacity. The waterborne vehicles are enumerated in order of their appearance in the input file.

In the first line print the maximum possible carrying capacity of the set. In the second line print a string consisting of the numbers of the vehicles that make the optimal set. If the answer is not unique, print any of them.

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

let () =
  let n = read_int 0 in
  let v = read_int 0 in
  let one = Array.make n (0,0)
  and two = Array.make n (0,0) in
  let rec input i none ntwo =
    if i >= n then
      none,ntwo
    else (
      let t = read_int 0 in
      let c = read_int 0 in
      if t = 1 then (
        one.(none) <- (c,i);
        input (i+1) (none+1) ntwo
      ) else (
        two.(ntwo) <- (c,i);
        input (i+1) none (ntwo+1)
      )
    ) in
  let none,ntwo = input 0 0 0 in
  Array.sort (fun x y -> compare y x) one;
  Array.sort (fun x y -> compare y x) two;

  let ans = ref 0
  and ansp = ref 0
  and ansq = ref 0
  and qs = ref 0
  and ps = Array.make (none+1) 0 in
  for i = 0 to none-1 do
    ps.(i+1) <- ps.(i)+fst one.(i)
  done;
  for i = 0 to min (v/2) ntwo do
    let rest = min (v-2*i) none in
    if ps.(rest) + !qs > !ans then (
      ans := ps.(rest) + !qs;
      ansp := rest;
      ansq := i
    );
    if i < ntwo then
      qs := !qs+fst two.(i)
  done;

  Printf.printf "%d\n" !ans;
  for i = 0 to !ansp-1 do
    Printf.printf "%d " (snd one.(i)+1)
  done;
  for i = 0 to !ansq-1 do
    Printf.printf "%d " (snd two.(i)+1)
  done

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

type container = {
  cap : int;
  id: int
};;

let comp contA contB =
  - (contA.cap - contB.cap);;

let rec get_best tab1 tab2 size = match (tab1,tab2) with
  | ([],[])
    -> []
  | ([], _) when size < 2
    -> []
  | (_, _) when size = 0
    -> []
  | (first :: tail, _) when size = 1
    -> [first]
  | ([], first :: tail)
    -> first :: get_best [] tail (size - 2)
  | (first :: tail, [])
    -> first :: get_best tail [] (size - 1)
  | (first1 :: [], first2 :: tail2)
    -> if first1.cap >= first2.cap then
      first1 :: get_best [] tab2 (size - 1)
    else
      first2 :: get_best tab1 tail2 (size - 2)
  | (first1 :: second1 :: tail1, first2 :: tail2)
    -> if first1.cap + second1.cap >= first2.cap then
      first1 :: get_best (second1::tail1) tab2 (size - 1)
    else
      first2 :: get_best tab1 tail2 (size - 2);;

(*#trace get_best;;*)

let rec read_input index left = match left with
  | 0 -> [],[]
  | n ->
    let size = read_int () in
    let cap = read_int () in
    let cont = {cap = cap; id = index} in
    let size1,size2 = read_input (index + 1) (left - 1) in
    if size = 1 then
      (cont :: size1, size2)
    else
      (size1, cont :: size2);;

let nbVehi = read_int () in
let maxV = read_int () in
let unsort1,unsort2 = (read_input 1 nbVehi)  in
let tab1 = List.sort comp unsort1 in
let tab2 = List.sort comp unsort2 in
let res = get_best tab1 tab2 maxV in
begin
  let maxC = List.fold_left (fun sum cont -> sum + cont.cap) 0 res in
  Printf.printf "%d\n" maxC;
  List.iter (fun cont -> Printf.printf "%d\n" cont.id) res
end;;

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

type container = {
  cap : int;
  id: int
};;

let comp contA contB =
  - (contA.cap - contB.cap);;

let rec get_best tab1 tab2 size = match (tab1,tab2) with
  | ([],[])
    -> []
  | ([], _) when size < 2
    -> []
  | (_, _) when size = 0
    -> []
  | (first :: tail, _) when size = 1
    -> [first]
  | ([], first :: tail)
    -> first :: get_best [] tail (size - 2)
  | (first :: tail, [])
    -> first :: get_best tail [] (size - 1)
  | (first1 :: second1 :: [], first2 :: tail2) when size > 2
    -> first2 :: get_best tab1 tail2 (size - 2)
  | (first1 :: [], first2 :: tail2)
    -> if first1.cap >= first2.cap then
      first1 :: get_best [] tab2 (size - 1)
    else
      first2 :: get_best tab1 tail2 (size - 2)
  | (first1 :: second1 :: tail1, first2 :: tail2)
    -> if first1.cap + second1.cap >= first2.cap then
      first1 :: second1 :: get_best tail1 tab2 (size - 2)
    else
      first2 :: get_best tab1 tail2 (size - 2);;

(*#trace get_best;;*)

let rec read_input index left = match left with
  | 0 -> [],[]
  | n ->
    let size = read_int () in
    let cap = read_int () in
    let cont = {cap = cap; id = index} in
    let size1,size2 = read_input (index + 1) (left - 1) in
    if size = 1 then
      (cont :: size1, size2)
    else
      (size1, cont :: size2);;

let nbVehi = read_int () in
let maxV = read_int () in
let unsort1,unsort2 = (read_input 1 nbVehi)  in
let tab1 = List.sort comp unsort1 in
let tab2 = List.sort comp unsort2 in
let res = get_best tab1 tab2 maxV in
begin
  let maxC = List.fold_left (fun sum cont -> sum + cont.cap) 0 res in
  Printf.printf "%d\n" maxC;
  List.iter (fun cont -> Printf.printf "%d\n" cont.id) res
end;;

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

type container = {
  cap : int;
  id: int
};;

let comp contA contB =
  - (contA.cap - contB.cap);;

let rec get_best tab1 tab2 size = match (tab1,tab2) with
  | ([],[])
    -> []
  | ([], _) when size < 2
    -> []
  | (_, _) when size = 0
    -> []
  | (first :: [], _) when size = 1
    -> [first]
  | ([], first :: tail)
    -> first :: get_best [] tail (size - 2)
  | (first :: tail, [])
    -> first :: get_best tail [] (size - 1)
  | (first1 :: [], first2 :: tail2)
    -> if first1.cap >= first2.cap then
      first1 :: get_best [] tab2 (size - 1)
    else
      first2 :: get_best tab1 tail2 (size - 2)
  | (first1 :: second1 :: tail1, first2 :: tail2)
    -> if first1.cap + second1.cap >= first2.cap then
      first1 :: second1 :: get_best tail1 tab2 (size - 2)
    else
      first2 :: get_best tab1 tail2 (size - 2);;

(*#trace get_best;;*)

let rec read_input index left = match left with
  | 0 -> [],[]
  | n ->
    let size = read_int () in
    let cap = read_int () in
    let cont = {cap = cap; id = index} in
    let size1,size2 = read_input (index + 1) (left - 1) in
    if size = 1 then
      (cont :: size1, size2)
    else
      (size1, cont :: size2);;

let nbVehi = read_int () in
let maxV = read_int () in
let unsort1,unsort2 = (read_input 1 nbVehi)  in
let tab1 = List.sort comp unsort1 in
let tab2 = List.sort comp unsort2 in
let res = get_best tab1 tab2 maxV in
begin
  let maxC = List.fold_left (fun sum cont -> sum + cont.cap) 0 res in
  Printf.printf "%d\n" maxC;
  List.iter (fun cont -> Printf.printf "%d\n" cont.id) res
end;;

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

type container = {
  vol : int;
  size: int;
  id: int
};;

let comp contA contB =
  - (contA.vol * contB.size - contB.vol * contA.size);;

let rec get_best tab size = match tab with
  | [] -> []
  | curr_best :: suite  ->
    match size with
    | 0 -> []
    | 1 ->
      if curr_best.size == 1 then
      [curr_best]
      else
      get_best suite size
    | n ->
      curr_best :: get_best suite (size - curr_best.size);;

let rec read_input index left = match left with
  | 0 -> []
  | n ->
  let size = read_int () in
  let cap = read_int () in
  let cont = {
    size = size;
    vol = cap;
    id = index;
  } in
  cont :: read_input (index + 1) (left - 1);;

let nbVehi = read_int () in
let maxV = read_int () in
let tableau = read_input 1 nbVehi
    |> List.sort comp in
let res = get_best tableau maxV in
begin
  let maxC = List.fold_left (fun sum cont -> sum + cont.vol) 0 res in
  Printf.printf "%d\n" maxC;
  List.iter (fun cont -> Printf.printf "%d\n" cont.id) res
end;;


There are n incoming messages for Vasya. The i-th message is going to be received after ti minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. After reading the message, Vasya's bank account receives the current cost of this message. Initially, Vasya's bank account is at 0.Also, each minute Vasya's bank account receives C·k, where k is the amount of received but unread messages.Vasya's messages are very important to him, and because of that he wants to have all messages read after T minutes.Determine the maximum amount of money Vasya's bank account can hold after T minutes.

The first line contains five integers n, A, B, C and T (1 ≤ n, A, B, C, T ≤ 1000). The second string contains n integers ti (1 ≤ ti ≤ T).

Output one integer  — the answer to the problem.

NoteIn the first sample the messages must be read immediately after receiving, Vasya receives A points for each message, n·A = 20 in total.In the second sample the messages can be read at any integer moment.In the third sample messages must be read at the moment T. This way Vasya has 1, 2, 3, 4 and 0 unread messages at the corresponding minutes, he gets 40 points for them. When reading messages, he receives (5 - 4·3) + (5 - 3·3) + (5 - 2·3) + (5 - 1·3) + 5 =  - 5 points. This is 35 in total.

let compute n a b c t ts: int =
  Array.sort compare ts;
  if b >= c
  then n * a
  else
    let diffs = Array.map (fun v -> t - v) ts in
    let incomes = Array.map (fun v -> (c - b) * v) diffs in
    let total_income = Array.fold_left (+) 0 incomes in
    total_income + n * a

let _ =
  let n, a, b, c, t = Scanf.scanf " %d %d %d %d %d" (fun a b c d e -> a, b, c, d, e) in
  let ts = Array.init n (fun i -> Scanf.scanf " %d" (fun a -> a)) in
  compute n a b c t ts |> string_of_int |> print_endline


Polycarp remembered the $$$2020$$$-th year, and he is happy with the arrival of the new $$$2021$$$-th year. To remember such a wonderful moment, Polycarp wants to represent the number $$$n$$$ as the sum of a certain number of $$$2020$$$ and a certain number of $$$2021$$$.For example, if:   $$$n=4041$$$, then the number $$$n$$$ can be represented as the sum $$$2020 + 2021$$$;  $$$n=4042$$$, then the number $$$n$$$ can be represented as the sum $$$2021 + 2021$$$;  $$$n=8081$$$, then the number $$$n$$$ can be represented as the sum $$$2020 + 2020 + 2020 + 2021$$$;  $$$n=8079$$$, then the number $$$n$$$ cannot be represented as the sum of the numbers $$$2020$$$ and $$$2021$$$. Help Polycarp to find out whether the number $$$n$$$ can be represented as the sum of a certain number of numbers $$$2020$$$ and a certain number of numbers $$$2021$$$.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 10^6$$$) — the number that Polycarp wants to represent as the sum of the numbers $$$2020$$$ and $$$2021$$$.

For each test case, output on a separate line:    "YES" if the number $$$n$$$ is representable as the sum of a certain number of $$$2020$$$ and a certain number of $$$2021$$$;  "NO" otherwise.  You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).

let calculate_table () =
  let table = Hashtbl.create 1000000 in
  for a = 0 to 500 do
    for b = 0 to 500 do
      let new_value = (a*2020 + b*2021) in
      Hashtbl.add table new_value (a, b)
    done
  done;
  table;;

let find_opt tbl n =
  try
    Some (Hashtbl.find tbl n)
  with Not_found -> None

let solution_exists n solutions =
  let maybe_sol = find_opt solutions n in
  match maybe_sol with
  | Some _ -> true
  | None -> false;;

let cases = read_int () in
let solutions = calculate_table () in
for i = 1 to cases do
  let test = read_int () in
  if solution_exists test solutions then
    print_endline "YES"
  else
    print_endline "NO"
done

module Stdlib = Pervasives
let std_inp = Stdlib.stdin;;
(* let std_inp = Stdlib.open_in "input.txt";; *)
let std_outp = Stdlib.stdout;;

let identity x = x;;

let rec repeat ((f, f_in, f_out) as call) = function
| 0 -> ()
| n ->
  let _ = f f_in f_out in
  repeat call (n - 1);;

let flags =
  let sum_limit = 1_000_000 in
  let flags = Array.make (1 + sum_limit) false in
  let safe_get pos =
    if pos < 0 then false
    else flags.(pos)
  in
  let rec fill n =
    if n > sum_limit then ()
    else
      let _ = flags.(n) <- ((safe_get (n - 2020)) || (safe_get(n - 2021))) in
      fill (n + 1)
  in
  let _ = flags.(0) <- true in
  let _ = fill 1 in
  flags;;

let run_test inp outp =
  let value = let line = input_line inp in Scanf.sscanf line "%d" identity in
  let result = if flags.(value) then "YES" else "NO" in
  let _ = Printf.fprintf outp "%s\n" result in
  ();;

let (_:unit) =
  let inp = std_inp and outp = std_outp in
  let tests_count = let line = input_line inp in Scanf.sscanf line "%d" identity in
  let _ = repeat (run_test, inp, outp) tests_count in
  ();;


Santa Claus likes palindromes very much. There was his birthday recently. k of his friends came to him to congratulate him, and each of them presented to him a string si having the same length n. We denote the beauty of the i-th string by ai. It can happen that ai is negative — that means that Santa doesn't find this string beautiful at all.Santa Claus is crazy about palindromes. He is thinking about the following question: what is the maximum possible total beauty of a palindrome which can be obtained by concatenating some (possibly all) of the strings he has? Each present can be used at most once. Note that all strings have the same length n.Recall that a palindrome is a string that doesn't change after one reverses it.Since the empty string is a palindrome too, the answer can't be negative. Even if all ai's are negative, Santa can obtain the empty string.

The first line contains two positive integers k and n divided by space and denoting the number of Santa friends and the length of every string they've presented, respectively (1 ≤ k, n ≤ 100 000; n·k  ≤ 100 000). k lines follow. The i-th of them contains the string si and its beauty ai ( - 10 000 ≤ ai ≤ 10 000). The string consists of n lowercase English letters, and its beauty is integer. Some of strings may coincide. Also, equal strings can have different beauties.

In the only line print the required maximum possible beauty.

7 3
abb 2
aaa -3
bba -1
zyz -4
abb 5
aaa 7
xyx 4

NoteIn the first example Santa can obtain abbaaaxyxaaabba by concatenating strings 5, 2, 7, 6 and 3 (in this order).

open Printf
open Scanf

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

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

  let s = Array.init k (fun _ ->
    let str = read_string() in
    let cost = read_int() in
    (str,cost)
  ) in

  let h = Hashtbl.create 10 in

  let insert (str,cost) =
    let (li,index) = try Hashtbl.find h str with Not_found -> ([], Hashtbl.length h) in
    Hashtbl.replace h str ((cost::li),index)
  in

  for i=0 to k-1 do insert s.(i) done;

  let rev_string s = String.init n (fun i -> s.[n-i-1]) in

  let nstrings = Hashtbl.length h in

  let pair = Array.make nstrings (-1) in
  let clist = Array.make nstrings [] in

  Hashtbl.iter (fun str (li,index) ->
    clist.(index) <- List.sort (fun a b -> compare b a) li;
    let rstr = rev_string str in
    let (_,rindex) = try Hashtbl.find h rstr with Not_found -> ([], -1) in
    if rindex >= 0 then pair.(index) <- rindex
  ) h;

  let best_correction = ref 0 in

  let score = sum 0 (nstrings-1) (fun i ->
    let j = pair.(i) in
    if j = -1 then 0
    else if j < i then 0
    else if j > i then ( (* a non-palindrome with a pair *)
      let rec loop l1 l2 ac =
	match (l1,l2) with
	  | ([],_) | (_,[]) -> ac
	  | (c1::t1, c2::t2) ->
	    if c1+c2 <= 0 then ac
	    else loop t1 t2 (ac + c1 + c2)
      in
      loop clist.(i) clist.(j) 0
    ) else ( (* a palindrome *)
      let rec loop li rem ac =
	match li with
	  | [] -> (rem,ac)
	  | [c] -> (max rem c, ac)
	  | c1::(c2::t) ->
	    if c1+c2 <= 0 then (max rem c1, ac) else
	      let rem = max rem (-c2) in
	      loop t rem (ac + c1 + c2)
      in
      let (rem,ac) = loop clist.(i) 0 0 in
      best_correction := max !best_correction rem;
      ac
    )
  )
  in

  printf "%d\n" (score + !best_correction)

open Printf
open Scanf

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

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

  let s = Array.init k (fun _ ->
    let str = read_string() in
    let cost = read_int() in
    (str,cost)
  ) in

  let h = Hashtbl.create 10 in

  let insert (str,cost) =
    let (li,index) = try Hashtbl.find h str with Not_found -> ([], Hashtbl.length h) in
    Hashtbl.replace h str ((cost::li),index)
  in

  for i=0 to k-1 do insert s.(i) done;

  let rev_string s = String.init n (fun i -> s.[n-i-1]) in

  let nstrings = Hashtbl.length h in

  let pair = Array.make nstrings (-1) in
  let clist = Array.make nstrings [] in

  Hashtbl.iter (fun str (li,index) ->
    clist.(index) <- List.sort (fun a b -> compare b a) li;
    let rstr = rev_string str in
    let (_,rindex) = try Hashtbl.find h rstr with Not_found -> ([], -1) in
    if rindex >= 0 then pair.(index) <- rindex
  ) h;

  let best_correction = ref 0 in

  let score = sum 0 (nstrings-1) (fun i ->
    let j = pair.(i) in
    if j = -1 then 0
    else if j < i then 0
    else if j > i then ( (* a non-palindrome with a pair *)
      let rec loop l1 l2 ac =
	match (l1,l2) with
	  | ([],_) | (_,[]) -> ac
	  | (c1::t1, c2::t2) ->
	    if c1+c2 <= 0 then ac
	    else loop t1 t2 (ac + c1 + c2)
      in
      loop clist.(i) clist.(j) 0
    ) else ( (* a palindrome *)
      let rec loop li rem ac =
	match li with
	  | [] -> (ac,rem)
	  | [c] -> (ac, max rem c)
	  | c1::(c2::t) ->
	    if c1+c2 <= 0 then (ac,rem) else
	      let rem = max rem (-c2) in
	      loop t rem (ac + c1 + c2)
      in
      let (ac,rem) = loop clist.(i) 0 0 in
      best_correction := max !best_correction rem;
      ac
    )
  )
  in

  printf "%d\n" (score + !best_correction)


A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.

The first input line contains the only integer n (2 ≤ n ≤ 100) which represents the number of soldiers in the line. The second line contains integers a1, a2, ..., an (1 ≤ ai ≤ 100) the values of the soldiers' heights in the order of soldiers' heights' increasing in the order from the beginning of the line to its end. The numbers are space-separated. Numbers a1, a2, ..., an are not necessarily different.

Print the only integer — the minimum number of seconds the colonel will need to form a line-up the general will like.

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

let find_min array l =
    let rec loop min position i =
        if i < l
        then
            let current = array.(i) in
            if current <= min
            then
                loop current i (i + 1)
            else
                loop min position (i + 1)
        else
            position
    in loop array.(0) 0 0

let find_max array l =
    let rec loop max position i =
        if i < l
        then
            let current = array.(i) in
            if current > max
            then
                loop current i (i + 1)
            else
                loop max position (i + 1)
        else
            position
    in loop array.(0) 0 0

let solve () =
    let l = read () in
    let line = Array.init l (fun x -> read ()) in
    let min_i = find_min line l in
    let max_i = find_max line l in
    if max_i > min_i
    then
        (l - 1 - min_i) + (max_i - 1)
    else
        (l - 1 - min_i) + max_i

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

let () = print (solve ())

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

let find_best f array l =
    let rec loop best position i =
        if i < l
        then
            let current = array.(i) in
            if f current best
            then
                loop current i (i + 1)
            else
                loop best position (i + 1)
        else
            position
    in loop array.(0) 0 0

let find_min = find_best (fun x y -> x <= y)
let find_max = find_best (fun x y -> x > y)

let solve () =
    let l = read () in
    let line = Array.init l (fun x -> read ()) in
    let min_i = find_min line l in
    let max_i = find_max line l in
    if max_i > min_i
    then
        (l - 1 - min_i) + (max_i - 1)
    else
        (l - 1 - min_i) + max_i

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

let () = print (solve ())

let rec split s i acc =
begin
  if i > String.length s
  then List.rev acc
  else
      let first =
      if String.contains_from s i ' '
         then  String.index_from s i ' '
         else String.length s
    in split s (first+1) (int_of_string (String.init (first-i) (fun x -> String.get s (i+x))) :: acc)
end in
let n = int_of_string(read_line ()) and
    vals = split (read_line ()) 0 [] in
if n == List.length vals
   then
      let maxval = List.fold_right max (List.tl vals) (List.hd vals) and
          minval = List.fold_right min (List.tl vals) (List.hd vals) in
      if (List.nth vals 0) == maxval && (List.nth vals (n-1)) == minval
         then print_int 0
         else
          let maxpos = ref (n-1) and
              minpos = ref 0 in begin
          List.iteri (fun a b -> if b ==maxval then maxpos := min !maxpos a
                             else if b == minval then minpos := max !minpos a
                             else ()) vals;
      print_int (!maxpos + n - 1 - !minpos - (if !maxpos > !minpos then 1 else 0))
  end
  else ()

let ( |> ) x f = f x
let () =
	let n = read_int ()
	in let a =
		read_line ()
		|> Str.split (Str.regexp "\ ")
		|> List.map int_of_string
	in let ((max, left_most_pos), (min, right_most_pos)) =
		let rec search sublist_of_a pos =
			match sublist_of_a with
				| [] -> invalid_arg ""
				| hd :: [] -> ((hd, pos), (hd, pos))
				| hd :: tl ->
					  let ((max, left_most_pos), (min, right_most_pos)) = (search tl (pos + 1))
					  in let (new_max, new_left_most_pos) =
						  if  hd >= max then
							  (hd, pos)
						  else
							  (max, left_most_pos)
					  in let (new_min, new_right_most_pos) =
						  if hd < min then
							  (hd, pos)
						  else
							  (min, right_most_pos)
					  in ((new_max, new_left_most_pos), (new_min, new_right_most_pos))
		in search a 0
	in begin
		if left_most_pos > right_most_pos then
			(left_most_pos + (n - right_most_pos - 2))
		else
			(left_most_pos + (n - right_most_pos - 1))
	end |> print_int; print_newline ()

let n = read_int () in

let arr = Array.init n (fun i ->
	Scanf.scanf " %d" (fun i->i)
) in

let maxi = ref 0 in
let mini = ref 0 in
let _ = Array.iteri (fun i r ->
	if r <= arr.(!mini) then mini := i;
	if r > arr.(!maxi) then maxi := i
) arr in
print_int (!maxi + (n-1- !mini) - (if !maxi > !mini then 1 else 0))

(* codeforces 103.  Danny Sleator *)
let read_int () = Scanf.bscanf Scanf.Scanning.stdib " %d " (fun x -> x)
let read_string () = Scanf.bscanf Scanf.Scanning.stdib " %s " (fun x -> x)

let () =
  let n = read_int() in
  let a = Array.make n 0 in
  let () = for i=0 to n-1 do a.(i) <- read_int() done in
  let rec find_max i ac = if i=n then ac else find_max (i+1) (if ac < 0 || a.(i) > a.(ac) then i else ac) in
  let rec find_min i ac = if i=n then ac else find_min (i+1) (if ac < 0 || a.(i) <= a.(ac) then i else ac) in
  let mx = find_max 0 (-1) in
  let mi = find_min 0 (-1) in
  let guess = mx + (n-1-mi) in
  let answer = if mx < mi then guess else guess-1 in
    Printf.printf "%d\n" answer

let rec split s i acc =
begin
  if i > String.length s
  then List.rev acc
  else
      let first =
      if String.contains_from s i ' '
         then  String.index_from s i ' '
         else String.length s
    in split s (first+1) (int_of_string (String.init (first-i) (fun x -> String.get s (i+x))) :: acc)
end in
let n = int_of_string(read_line ()) and
    vals = split (read_line ()) 0 [] in
if n == List.length vals
   then begin
      let maxval = List.fold_right max (List.tl vals) (List.hd vals) and
          minval = List.fold_right min (List.tl vals) (List.hd vals) in
      let maxpos = ref (n-1) and
          minpos = ref 0 in
      List.iteri (fun a b -> if b ==maxval then maxpos := min !maxpos a
                             else if b == minval then minpos := max !minpos a
                             else ()) vals;
      print_int (!maxpos + n - 1 - !minpos - (if !maxpos > !minpos then 1 else 0))
  end
  else ()

let ( |> ) x f = f x
let () =
	let n = Scanf.bscanf Scanf.Scanning.stdin "%d" (fun x -> x)
	in let a =
		read_line ()
		|> Str.split (Str.regexp "\ ")
		|> List.map int_of_string
	in let ((max, left_most_pos), (min, right_most_pos)) =
		let rec search sublist_of_a pos =
			match sublist_of_a with
				| [] -> invalid_arg ""
				| hd :: [] -> ((hd, pos), (hd, pos))
				| hd :: tl ->
					  let ((max, left_most_pos), (min, right_most_pos)) = (search tl (pos + 1))
					  in let (new_max, new_left_most_pos) =
						  if  hd >= max then
							  (hd, pos)
						  else
							  (max, left_most_pos)
					  in let (new_min, new_right_most_pos) =
						  if hd < min then
							  (hd, pos)
						  else
							  (min, right_most_pos)
					  in ((new_max, new_left_most_pos), (new_min, new_right_most_pos))
		in search a 0
	in begin
		if left_most_pos > right_most_pos then
			(left_most_pos + (n - right_most_pos - 2))
		else
			(left_most_pos + (n - right_most_pos - 1))
	end |> Printf.printf "%d\n"


One day Ms Swan bought an orange in a shop. The orange consisted of n·k segments, numbered with integers from 1 to n·k. There were k children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote the number of the segment that he would like to get: the i-th (1 ≤ i ≤ k) child wrote the number ai (1 ≤ ai ≤ n·k). All numbers ai accidentally turned out to be different.Now the children wonder, how to divide the orange so as to meet these conditions:  each child gets exactly n orange segments;  the i-th child gets the segment with number ai for sure;  no segment goes to two children simultaneously. Help the children, divide the orange and fulfill the requirements, described above.

The first line contains two integers n, k (1 ≤ n, k ≤ 30). The second line contains k space-separated integers a1, a2, ..., ak (1 ≤ ai ≤ n·k), where ai is the number of the orange segment that the i-th child would like to get. It is guaranteed that all numbers ai are distinct.

Print exactly n·k distinct integers. The first n integers represent the indexes of the segments the first child will get, the second n integers represent the indexes of the segments the second child will get, and so on. Separate the printed numbers with whitespaces. You can print a child's segment indexes in any order. It is guaranteed that the answer always exists. If there are multiple correct answers, print any of them.

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

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

  let b = Array.make (n*k) (-1) in

    let ans = Array.make k [] in

    for i=0 to k-1 do
      b.(a.(i)) <- i;
      ans.(i) <- [a.(i)]
    done;

    let rec loop child count seg =
      if child=k then ()
      else if count=n then loop (child+1) 1 seg
      else if b.(seg) >= 0 then loop child count (seg+1)
      else (
	b.(seg) <- child;
	ans.(child) <- seg::(ans.(child));
	loop child (count+1) (seg+1)
      )
    in

      loop 0 1 0;

      for i=0 to k-1 do
	List.iter (fun e -> Printf.printf "%d " (e+1)) ans.(i);
	print_newline()
      done


Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a.Will the robot be able to build the fence Emuskald wants? In other words, is there a regular polygon which angles are equal to a?

The first line of input contains an integer t (0 < t < 180) — the number of tests. Each of the following t lines contains a single integer a (0 < a < 180) — the angle the robot can make corners at measured in degrees.

For each test, output on a single line "YES" (without quotes), if the robot can build a fence Emuskald wants, and "NO" (without quotes), if it is impossible.

NoteIn the first test case, it is impossible to build the fence, since there is no regular polygon with angle .In the second test case, the fence is a regular triangle, and in the last test case — a square.

let read () = Pervasives.read_int ()
let print string = Pervasives.print_endline string

let () =
    let n = read () in
    let rec loop i =
        if i < n
        then
            let angle = read () in
                if 360 mod (180 - angle) = 0
                then
                    print "YES"
                else
                    print "NO";
                loop (i + 1)
        else
            ()
    in loop 0

let can x = if 360 mod (180 - x) = 0 then "YES\n" else "NO\n" in
let n = read_line () |> int_of_string in
for i = 1 to n do
   print_string (read_line () |> int_of_string |> can)
done

open Scanf
open Printf

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

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

let nd=181
let c = Array.make nd 0;;

for i = 3 to 360 do
  if (360 mod i) = 0 then
    c.(180 - 360/i) <- 1
done

for i = 1 to n do
  let deg = Scanf.scanf "%d " ( fun x -> x ) in
  if c.(deg) = 0 then print_endline "NO" else print_endline "YES"
done

let ok x =
  let an = 180 - x in
  let n = 360 / an
  in an * n = 360 ;;

let test_num = read_int()
in
for i = 1 to test_num do
  let x = read_int()
  in
  if (ok x) then
    Printf.printf "YES\n"
  else
    Printf.printf "NO\n"
done

open Scanf
open Printf

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

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

let nd=181
let c = Array.make nd 0;;

for i = 3 to 360 do
  c.(180 - 360/i) <- 1
done

for i = 1 to n do
  let deg = Scanf.scanf "%d " ( fun x -> x ) in
  if c.(deg) = 0 then print_endline "NO" else print_endline "YES"
done

open Scanf
open Printf

let (a,b) = Scanf.scanf "%d %d " ( fun x y -> (x,y))

let aa = ref a in
let tt = ref a in
let () =
  while ( !aa /b > 0 ) do
    tt := !tt + (!aa)/b; aa := (!aa/b) + (!aa mod b)
  done
in printf "%d\n" !tt

open Scanf
open Printf

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

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

let nd=181
let c = Array.make nd 0;;

for i = 3 to 360 do
  if (360 mod 5) = 0 then
    c.(180 - 360/i) <- 1
done

for i = 1 to n do
  let deg = Scanf.scanf "%d " ( fun x -> x ) in
  if c.(deg) = 0 then print_endline "NO" else print_endline "YES"
done


You are given $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. You choose any subset of the given numbers (possibly, none or all numbers) and negate these numbers (i. e. change $$$x \to (-x)$$$). What is the maximum number of different values in the array you can achieve?

The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 100$$$): the number of test cases. The next lines contain the description of the $$$t$$$ test cases, two lines per a test case. In the first line you are given one integer $$$n$$$ ($$$1 \leq n \leq 100$$$): the number of integers in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-100 \leq a_i \leq 100$$$).

For each test case, print one integer: the maximum number of different elements in the array that you can achieve negating numbers in the array.

NoteIn the first example we can, for example, negate the first and the last numbers, achieving the array $$$[-1, 1, 2, -2]$$$ with four different values.In the second example all three numbers are already different.In the third example negation does not change anything.

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 bound = 100

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let () =
  let cases = read_int () in
  for case = 1 to cases do
    let n = read_int () in
    let a = Array.init n read_int in
    let count = Array.make (bound+1) 0 in
    for i=0 to n-1 do
      let x = abs a.(i) in
      count.(x) <- 1 + count.(x)
    done;
    let answer = sum 1 bound (fun i -> min 2 count.(i)) in
    let answer = answer + (if count.(0) > 0 then 1 else 0) in
    printf "%d\n" answer
  done


While Patrick was gone shopping, Spongebob decided to play a little trick on his friend. The naughty Sponge browsed through Patrick's personal stuff and found a sequence a1, a2, ..., am of length m, consisting of integers from 1 to n, not necessarily distinct. Then he picked some sequence f1, f2, ..., fn of length n and for each number ai got number bi = fai. To finish the prank he erased the initial sequence ai.It's hard to express how sad Patrick was when he returned home from shopping! We will just say that Spongebob immediately got really sorry about what he has done and he is now trying to restore the original sequence. Help him do this or determine that this is impossible.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100 000) — the lengths of sequences fi and bi respectively. The second line contains n integers, determining sequence f1, f2, ..., fn (1 ≤ fi ≤ n). The last line contains m integers, determining sequence b1, b2, ..., bm (1 ≤ bi ≤ n).

Print "Possible" if there is exactly one sequence ai, such that bi = fai for all i from 1 to m. Then print m integers a1, a2, ..., am. If there are multiple suitable sequences ai, print "Ambiguity". If Spongebob has made a mistake in his calculations and no suitable sequence ai exists, print "Impossible".

NoteIn the first sample 3 is replaced by 1 and vice versa, while 2 never changes. The answer exists and is unique.In the second sample all numbers are replaced by 1, so it is impossible to unambiguously restore the original sequence.In the third sample fi ≠ 3 for all i, so no sequence ai transforms into such bi and we can say for sure that Spongebob has made a mistake.

open Printf
open Scanf

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

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

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

  let lv = Array.make (n+1) [] in
  for j=1 to n do
    let f = read_int () in
    lv.(f) <- j::lv.(f)
  done;

  let b = Array.init m (fun i -> read_int()) in

  if exists 0 (m-1) (fun i -> lv.(b.(i)) = []) then printf "Impossible\n" else (
    if maxf 0 (m-1) (fun i -> List.length lv.(b.(i))) > 1 then printf "Ambiguity\n" else (
      printf "Possible\n";
      for i=0 to m-1 do
	printf "%d " (List.hd (lv.(b.(i))))
      done;
      print_newline()
    )
  )

open Printf
open Scanf

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

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

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

  let lv = Array.make (n+1) [] in
  for j=1 to n do
    let f = read_int () in
    lv.(f) <- j::lv.(f)
  done;

  let b = Array.init m (fun i -> read_int()) in

  if exists 0 (m-1) (fun i -> lv.(b.(i)) = []) then printf "Impossible\n" else (
    if maxf 0 (m-1) (fun i -> List.length lv.(b.(i))) > 1 then printf "Ambiguous\n" else (
      printf "Possible\n";
      for i=0 to m-1 do
	printf "%d " (List.hd (lv.(b.(i))))
      done;
      print_newline()
    )
  )


One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.Alex has grown up since then, so he easily wins the most difficult levels. This quickly bored him, and he thought: what if the computer gave him invalid fields in the childhood and Alex could not win because of it?He needs your help to check it.A Minesweeper field is a rectangle $$$n \times m$$$, where each cell is either empty, or contains a digit from $$$1$$$ to $$$8$$$, or a bomb. The field is valid if for each cell:   if there is a digit $$$k$$$ in the cell, then exactly $$$k$$$ neighboring cells have bombs.  if the cell is empty, then all neighboring cells have no bombs. Two cells are neighbors if they have a common side or a corner (i. e. a cell has at most $$$8$$$ neighboring cells).

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 100$$$) — the sizes of the field. The next $$$n$$$ lines contain the description of the field. Each line contains $$$m$$$ characters, each of them is "." (if this cell is empty), "*" (if there is bomb in this cell), or a digit from $$$1$$$ to $$$8$$$, inclusive.

Print "YES", if the field is valid and "NO" otherwise. You can choose the case (lower or upper) for each letter arbitrarily.

NoteIn the second example the answer is "NO" because, if the positions of the bombs are preserved, the first line of the field should be *2*1.You can read more about Minesweeper in Wikipedia's article.

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 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 m = read_int () in

  let board = Array.init n read_string in

  let get i j =
    let x = (board.(i)).[j] in
    if x = '.' then '0' else x
  in

  let count_neighbors (i,j) =
    sum (max (i-1) 0) (min (i+1) (n-1)) (fun i ->
      sum (max (j-1) 0) (min (j+1) (m-1)) (fun j ->
	if get i j = '*' then 1 else 0
      )
    )
  in

  let l2n c = (int_of_char c) - (int_of_char '0') in

  let answer = forall 0 (n-1) (fun i ->
    forall 0 (m-1) (fun j ->
      get i j = '*' || count_neighbors (i,j) = l2n (get i j)
    )
  ) in

  if answer then printf "YES\n" else printf "NO\n"


Every day Ruslan tried to count sheep to fall asleep, but this didn't help. Now he has found a more interesting thing to do. First, he thinks of some set of circles on a plane, and then tries to choose a beautiful set of points, such that there is at least one point from the set inside or on the border of each of the imagined circles.Yesterday Ruslan tried to solve this problem for the case when the set of points is considered beautiful if it is given as (xt = f(t), yt = g(t)), where argument t takes all integer values from 0 to 50. Moreover, f(t) and g(t) should be correct functions.Assume that w(t) and h(t) are some correct functions, and c is an integer ranging from 0 to 50. The function s(t) is correct if it's obtained by one of the following rules:  s(t) = abs(w(t)), where abs(x) means taking the absolute value of a number x, i.e. |x|; s(t) = (w(t) + h(t)); s(t) = (w(t) - h(t)); s(t) = (w(t) * h(t)), where  *  means multiplication, i.e. (w(t)·h(t)); s(t) = c; s(t) = t;Yesterday Ruslan thought on and on, but he could not cope with the task. Now he asks you to write a program that computes the appropriate f(t) and g(t) for any set of at most 50 circles.In each of the functions f(t) and g(t) you are allowed to use no more than 50 multiplications. The length of any function should not exceed 100·n characters. The function should not contain spaces.Ruslan can't keep big numbers in his memory, so you should choose f(t) and g(t), such that for all integer t from 0 to 50 value of f(t) and g(t) and all the intermediate calculations won't exceed 109 by their absolute value.

The first line of the input contains number n (1 ≤ n ≤ 50) — the number of circles Ruslan thinks of. Next follow n lines, each of them containing three integers xi, yi and ri (0 ≤ xi, yi ≤ 50, 2 ≤ ri ≤ 50) — the coordinates of the center and the raduis of the i-th circle.

In the first line print a correct function f(t). In the second line print a correct function g(t). The set of the points (xt = f(t), yt = g(t)) (0 ≤ t ≤ 50) must satisfy the condition, that there is at least one point inside or on the border of each of the circles, Ruslan thinks of at the beginning.

NoteCorrect functions: 10 (1+2) ((t-3)+(t*4)) abs((t-10)) (abs((((23-t)*(t*t))+((45+12)*(t*t))))*((5*t)+((12*t)-13))) abs((t-(abs((t*31))+14))))Incorrect functions: 3+5+7 (not enough brackets, it should be ((3+5)+7) or (3+(5+7)))  abs(t-3) (not enough brackets, it should be abs((t-3)) 2+(2-3 (one bracket too many) 1(t+5) (no arithmetic operation between 1 and the bracket) 5000*5000 (the number exceeds the maximum)  The picture shows one of the possible solutions

open Printf
open Scanf

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

let () =
  let n = read_int () in

  let x = Array.make n 0 in
  let y = Array.make n 0 in

  for i=0 to n-1 do
    x.(i) <- read_int();
    y.(i) <- read_int();
    x.(i) <- x.(i) + (x.(i) land 1);
    y.(i) <- y.(i) + (y.(i) land 1);
    ignore (read_int())
  done;

  let abs f =
    sprintf "abs(%s)" f
  in

  let comb f op g =
    sprintf "(%s%s%s)" f op g
  in

  let rec const k =
    if k < 0 then comb (const 0) "-" (const (-k)) else sprintf "%d" k
  in

  let absdif k =
    abs (comb "t" "-" (const k))
  in

  let basis k =
    let p1 = comb (absdif (k+1)) "+" (absdif (k-1)) in
    let p2 = comb (absdif k) "+" (absdif k) in
    comb p1 "-" p2
  in

  let build_function n x =
    let rec loop i ac = if i=n then ac else
	let v = x.(i) in
	loop (i+1) (comb ac "+" (comb (const (v/2)) "*" (basis i)))
    in
    loop 0 "0"
  in

  printf "%s\n" (build_function n x);
  printf "%s\n" (build_function n y);

open Printf
open Scanf

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

let () =
  let n = read_int () in

  let x = Array.make n 0 in
  let y = Array.make n 0 in

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

  let abs f =
    sprintf "abs(%s)" f
  in

  let comb f op g =
    sprintf "(%s%s%s)" f op g
  in

  let rec const k =
    sprintf "%d" k
  in

  let absdif k =
    if k>0 then abs (comb "t" "-" (const k)) else abs (comb "t" "+" (const (-k)))
  in

  let basis k =
    let p1 = comb (absdif (k+1)) "-" (absdif (k-1)) in
    comb "2" "-" (abs p1)
  in

  let build_function n x =
    let rec loop i ac = if i=n then ac else
	let p1 = (comb (const ((x.(i)+1)/2)) "*" (basis i)) in
	let ac = if ac="" then p1 else comb p1 "+" ac in
	loop (i+1) ac
    in
    loop 0 ""
  in

  printf "%s\n" (build_function n x);
  printf "%s\n" (build_function n y);

open Printf
open Scanf

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

let () =
  let n = read_int () in

  let x = Array.make n 0 in
  let y = Array.make n 0 in

  for i=0 to n-1 do
    x.(i) <- read_int();
    y.(i) <- read_int();
    x.(i) <- x.(i) + (x.(i) land 1);
    y.(i) <- y.(i) + (y.(i) land 1);
    ignore (read_int())
  done;

  let abs f =
    sprintf "abs(%s)" f
  in

  let comb f op g =
    sprintf "(%s%s%s)" f op g
  in

  let const k =
    sprintf "%d" k
  in

  let absdif k =
    abs (comb "t" "-" (const k))
  in

  let basis k =
    let p1 = comb (absdif (k+1)) "+" (absdif (k-1)) in
    let p2 = comb "2" "*" (absdif k) in
    comb p1 "-" p2
  in

  let build_function n x =
    let rec loop i ac = if i=n then ac else
	let v = x.(i) in
	loop (i+1) (comb ac "+" (comb (const (v/2)) "*" (basis i)))
    in
    loop 0 "0"
  in

  printf "%s\n" (build_function n x);
  printf "%s\n" (build_function n y);

open Printf
open Scanf

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

let () =
  let n = read_int () in

  let x = Array.make n 0 in
  let y = Array.make n 0 in

  for i=0 to n-1 do
    x.(i) <- read_int();
    y.(i) <- read_int();
    x.(i) <- x.(i) + (x.(i) land 1);
    y.(i) <- y.(i) + (y.(i) land 1);
    ignore (read_int())
  done;

  let abs f =
    sprintf "abs(%s)" f
  in

  let comb f op g =
    sprintf "(%s%s%s)" f op g
  in

  let const k =
    sprintf "%d" k
  in

  let absdif k =
    abs (comb "t" "-" (const k))
  in

  let basis k =
    let p1 = comb (absdif (k+1)) "+" (absdif (k-1)) in
    let p2 = comb (absdif k) "+" (absdif k) in
    comb p1 "-" p2
  in

  let build_function n x =
    let rec loop i ac = if i=n then ac else
	let v = x.(i) in
	loop (i+1) (comb ac "+" (comb (const (v/2)) "*" (basis (i+1))))
    in
    loop 0 "0"
  in

  printf "%s\n" (build_function n x);
  printf "%s\n" (build_function n y);

open Printf
open Scanf

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

let () =
  let n = read_int () in

  let x = Array.make n 0 in
  let y = Array.make n 0 in

  for i=0 to n-1 do
    x.(i) <- read_int();
    y.(i) <- read_int();
    x.(i) <- x.(i) + (x.(i) land 1);
    y.(i) <- y.(i) + (y.(i) land 1);
    ignore (read_int())
  done;

  let abs f =
    sprintf "abs(%s)" f
  in

  let comb f op g =
    sprintf "(%s%s%s)" f op g
  in

  let const k =
    sprintf "%d" k
  in

  let absdif k =
    abs (comb "t" "-" (const k))
  in

  let basis k =
    let p1 = comb (absdif (k+1)) "-" (absdif (k-1)) in
    let p2 = comb "2" "*" (absdif k) in
    comb p1 "-" p2
  in

  let build_function n x =
    let rec loop i ac = if i=n then ac else
	let v = x.(i) in
	loop (i+1) (comb ac "+" (comb (const (v/2)) "*" (basis v)))
    in
    loop 0 "0"
  in

  printf "%s\n" (build_function n x);
  printf "%s\n" (build_function n y);

open Printf
open Scanf

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

let () =
  let n = read_int () in

  let x = Array.make n 0 in
  let y = Array.make n 0 in

  for i=0 to n-1 do
    x.(i) <- read_int();
    y.(i) <- read_int();
    x.(i) <- x.(i) + (x.(i) land 1);
    y.(i) <- y.(i) + (y.(i) land 1);
    ignore (read_int())
  done;

  let abs f =
    sprintf "abs(%s)" f
  in

  let comb f op g =
    sprintf "(%s%s%s)" f op g
  in

  let const k =
    sprintf "%d" k
  in

  let absdif k =
    abs (comb "t" "-" (const k))
  in

  let basis k =
    let p1 = comb (absdif (k+1)) "+" (absdif (k-1)) in
    let p2 = comb "2" "*" (absdif k) in
    comb p1 "-" p2
  in

  let build_function n x =
    let rec loop i ac = if i=n then ac else
	let v = x.(i) in
	loop (i+1) (comb ac "+" (comb (const (v/2)) "*" (basis v)))
    in
    loop 0 "0"
  in

  printf "%s\n" (build_function n x);
  printf "%s\n" (build_function n y);

open Printf
open Scanf

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

let () =
  let n = read_int () in

  let x = Array.make n 0 in
  let y = Array.make n 0 in

  for i=0 to n-1 do
    x.(i) <- read_int();
    y.(i) <- read_int();
    x.(i) <- x.(i) + (x.(i) land 1);
    y.(i) <- y.(i) + (y.(i) land 1);
    ignore (read_int())
  done;

  let abs f =
    sprintf "abs(%s)" f
  in

  let comb f op g =
    sprintf "(%s%s%s)" f op g
  in

  let const k =
    sprintf "%d" k
  in

  let absdif k =
    abs (comb "t" "-" (const k))
  in

  let basis k =
    let p1 = comb (absdif (k+1)) "+" (absdif (k-1)) in
    let p2 = comb (absdif k) "+" (absdif k) in
    comb p1 "-" p2
  in

  let build_function n x =
    let rec loop i ac = if i=n then ac else
	let v = x.(i) in
	loop (i+1) (comb ac "+" (comb (const (v/2)) "*" (basis i)))
    in
    loop 0 "0"
  in

  printf "%s\n" (build_function n x);
  printf "%s\n" (build_function n y);

open Printf
open Scanf

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

let () =
  let n = read_int () in

  let x = Array.make n 0 in
  let y = Array.make n 0 in

  for i=0 to n-1 do
    x.(i) <- read_int();
    y.(i) <- read_int();
    x.(i) <- x.(i) + (x.(i) land 1);
    y.(i) <- y.(i) + (y.(i) land 1);
    ignore (read_int())
  done;

  let abs f =
    sprintf "abs(%s)" f
  in

  let comb f op g =
    sprintf "(%s%s%s)" f op g
  in

  let const k =
    sprintf "%d" k
  in

  let absdif k =
    abs (comb "t" "-" (const k))
  in

  let basis k =
    let p1 = comb (absdif (k+1)) "+" (absdif (k-1)) in
    let p2 = comb "2" "*" (absdif k) in
    comb p1 "-" p2
  in

  let build_function n x =
    let rec loop i ac = if i=n then ac else
	let v = x.(i) in
	loop (i+1) (comb ac "+" (comb (const (v/2)) "*" (basis (i+1))))
    in
    loop 0 "0"
  in

  printf "%s\n" (build_function n x);
  printf "%s\n" (build_function n y);


Little Petya is now fond of data compression algorithms. He has already studied gz, bz, zip algorithms and many others. Inspired by the new knowledge, Petya is now developing the new compression algorithm which he wants to name dis.Petya decided to compress tables. He is given a table a consisting of n rows and m columns that is filled with positive integers. He wants to build the table a' consisting of positive integers such that the relative order of the elements in each row and each column remains the same. That is, if in some row i of the initial table ai, j < ai, k, then in the resulting table a'i, j < a'i, k, and if ai, j = ai, k then a'i, j = a'i, k. Similarly, if in some column j of the initial table ai, j < ap, j then in compressed table a'i, j < a'p, j and if ai, j = ap, j then a'i, j = a'p, j. Because large values require more space to store them, the maximum value in a' should be as small as possible.Petya is good in theory, however, he needs your help to implement the algorithm.

The first line of the input contains two integers n and m (, the number of rows and the number of columns of the table respectively. Each of the following n rows contain m integers ai, j (1 ≤ ai, j ≤ 109) that are the values in the table.

Output the compressed table in form of n lines each containing m integers. If there exist several answers such that the maximum number in the compressed table is minimum possible, you are allowed to output any of them.

NoteIn the first sample test, despite the fact a1, 2 ≠ a21, they are not located in the same row or column so they may become equal after the compression.

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_pair () = bscanf Scanning.stdib " %d %d " (fun x y -> (x,y))
let () =
  let (n,m) = read_pair () in
  let a = Array.make_matrix n m 0 in
  for i=0 to n-1 do
    for j=0 to m-1 do
      a.(i).(j) <- read_int()
    done
  done;

  let graph = Array.make_matrix n m [] in

  let add_edge x (i,j) h =
    try
      let (i',j') = Hashtbl.find h x in
      graph.(i').(j') <- (i,j)::graph.(i').(j');
      graph.(i).(j) <- (i',j')::graph.(i).(j);
    with Not_found ->
      Hashtbl.add h x (i,j)
  in

  for i=0 to n-1 do
    let row = Hashtbl.create 10 in
    for j=0 to m-1 do
      add_edge a.(i).(j) (i,j) row
    done
  done;

  for j=0 to m-1 do
    let col = Hashtbl.create 10 in
    for i=0 to n-1 do
      add_edge a.(i).(j) (i,j) col
    done
  done;

  let visited = Array.make_matrix n m false in
  let vis (i,j) = visited.(i).(j) in
  let mark (i,j) = visited.(i).(j) <- true in
  let gr (i,j) = graph.(i).(j) in
  let geta (i,j) = a.(i).(j) in

  let rec dfs ac v =
    if vis v then ac else (
      mark v;
      List.fold_left dfs (v::ac) (gr v)
    )
  in

  let next (i,j) = if j<m-1 then (i,j+1) else (i+1,0) in

  let rec find_comps v ac = if v = (n,0) then ac else (
    if vis v then find_comps (next v) ac
    else find_comps (next v) ((dfs [] v)::ac)
  )
  in

  let comps = find_comps (0,0) [] in

  let comps = List.sort (
    fun c1 c2 -> compare (geta (List.hd c1)) (geta (List.hd c2))
  ) comps
  in

  let row_max = Array.make n 0 in
  let col_max = Array.make m 0 in

  let answer = Array.make_matrix n m 0 in

  List.iter (fun li ->
    let mval = List.fold_left (fun ac (i,j) ->
      max ac (max row_max.(i) col_max.(j))
    ) 0 li in
    List.iter (fun (i,j) ->
      answer.(i).(j) <- mval+1;
      row_max.(i) <- mval+1;
      col_max.(j) <- mval+1;
    ) li
  ) comps;

  for i=0 to n-1 do
    for j=0 to m-1 do
      printf "%d " answer.(i).(j);
    done;
    print_newline()
  done;


A restaurant received n orders for the rental. Each rental order reserve the restaurant for a continuous period of time, the i-th order is characterized by two time values — the start time li and the finish time ri (li ≤ ri).Restaurant management can accept and reject orders. What is the maximal number of orders the restaurant can accept?No two accepted orders can intersect, i.e. they can't share even a moment of time. If one order ends in the moment other starts, they can't be accepted both.

The first line contains integer number n (1 ≤ n ≤ 5·105) — number of orders. The following n lines contain integer values li and ri each (1 ≤ li ≤ ri ≤ 109).

Print the maximal number of orders that can be accepted.

open Array;;
open Str;;
let n = read_int () and ans = ref 0;;
let par = make n [|0; 0|] and right = ref (-1);;
for i = 1 to n do set par (i - 1) (of_list (List.map (int_of_string) (split (regexp " ") (read_line ())))) done;;
let cmp [|a; b|] [|c; d|] = (if b < d then -1 else 1);;
sort (cmp) par;;
for i = 0 to n - 1 do if par.(i).(0) > !right then begin
	right := par.(i).(1);
	ans := !ans + 1;
end done;;
print_int !ans

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make (2 * n) (0, 0, 0) in
  let ll = Array.make n 0 in
    for i = 0 to n - 1 do
      let l = Scanf.bscanf sb "%d " (fun s -> s) in
      let r = Scanf.bscanf sb "%d " (fun s -> s) in
	a.(2 * i) <- (l, 0, i);
	a.(2 * i + 1) <- (r, 1, i);
	ll.(i) <- l;
    done;
    Array.sort compare a;
    let res = ref 0 in
    let s = ref [] in
    let tt = ref (-1) in
      for i = 0 to 2 * n - 1 do
	let (t, k, x) = a.(i) in
	  if k = 0
	  then ()
	  else (
	    if ll.(x) > !tt then (
	      incr res;
	      tt := t;
	    )
	  )
      done;
      Printf.printf "%d\n" !res

open Array;;
open Str;;
let n = read_int () and ans = ref 0;;
let par = make n [|0; 0|] and right = ref (-1);;
for i = 1 to n do set par (i - 1) (of_list (List.map (int_of_string) (split (regexp " ") (read_line ())))) done;;
let cmp [|a; b|] [|c; d|] = (if b < d then -1 else 1);;
sort (cmp) par;;
for i = 0 to n - 1 do Printf.printf "%d %d\n" par.(i).(0) par.(i).(1) done;;
for i = 0 to n - 1 do if par.(i).(0) > !right then begin
	right := par.(i).(1);
	ans := !ans + 1;
end done;;
print_int !ans


Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats. Your task is to help Kefa count the number of restaurants where he can go.

The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa. The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat). Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.  It is guaranteed that the given set of edges specifies a tree.

A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.

NoteLet us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.Note to the first sample test:  The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.Note to the second sample test:  The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7.

let main () =
	let (n,m) = Scanf.scanf "%d %d" (fun i j -> (i,j)) in
	let grph = Array.make n [] and cats = Array.make n false
	and visited = Array.make n false in
		for i=0 to n-1 do
			Scanf.scanf " %d" (fun j -> if j = 1
						then cats.(i) <- true);
		done;
		for k=1 to n-1 do
			Scanf.scanf " %d %d" (fun i j ->
			let (i',j') = (i-1,j-1) in
				grph.(i') <- j'::grph.(i');
				grph.(j') <- i'::grph.(j'));
		done;
	let rec construct cats_atm i =
		visited.(i) <- true;
		if cats_atm = m && cats.(i)
			then 0
			else let l = List.filter (fun i -> not (visited.(i))) (grph.(i)) in
				if List.length l = 0
					then 1
					else let l' = List.map (construct (if cats.(i) then cats_atm + 1 else 0)) l in
						List.fold_left (+) 0 l'
	in Printf.printf "%d" (construct 0 0);;

main ();;


Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries:  Query number i is given as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).  The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + ali + 1 + ... + ari = 0, otherwise the response to the query will be integer 0. Help Eugeny, answer all his queries.

The first line contains integers n and m (1 ≤ n, m ≤ 2·105). The second line contains n integers a1, a2, ..., an (ai = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n).

Print m integers — the responses to Eugene's queries in the order they occur in the input.

open List
open Printf
open Scanf
open String

let inf= 1070000000;;

let rec getlist n =
	if n=0 then []
	else scanf " %d" (fun x->x)::getlist (n-1);;

let rec getplist n =
	if n=0 then []
	else scanf " %d %d" (fun x y->(x,y))::getplist (n-1);;

let is1 x =
	if x=1 then 1
	else 0;;

let rec count1 a =
	if a=[] then 0
	else is1 (hd a) + count1 (tl a);;

let ans plus minus l r =
	let len = r-l+1 in
	if len mod 2 = 0 && min plus minus >= len/2
		then 1
	else 0;;

let rec solve plus minus lr =
	if lr <> [] then begin
		printf "%d\n" (ans plus minus (fst (hd lr)) (snd (hd lr)));
		solve plus minus (tl lr)
	end;;

let n = scanf " %d" (fun x->x)
in let m = scanf " %d" (fun x->x)
in let a = getlist n
in let plus = count1 a
in let minus = n-plus
in let lr = rev (getplist m)
in solve plus minus lr;;

open List
open Printf
open Scanf
open String

let inf= 1070000000;;

let rec getlist n =
	if n=0 then []
	else scanf " %d" (fun x->x)::getlist (n-1);;

let rec getplist n =
	if n=0 then []
	else scanf " %d %d" (fun x y->(x,y))::getplist (n-1);;

let is1 x =
	if x=1 then 1
	else 0;;

let rec count1 a =
	if a=[] then 0
	else is1 (hd a) + count1 (tl a);;

let ans plus minus l r =
	let len = r-l+1 in
	if len mod 2 = 0 && min plus minus >= len/2
		then "1\n"
		else "0\n";;

let rec solve plus minus lr =
	if lr = [] then ""
	else
		ans plus minus (fst (hd lr)) (snd (hd lr)) ^ solve plus minus (tl lr);;

let n = scanf " %d" (fun x->x)
in let m = scanf " %d" (fun x->x)
in let a = getlist n
in let plus = count1 a
in let minus = n-plus
in let lr = getplist m
in printf "%s" (solve plus minus lr);;


Last year Bob earned by selling memory sticks. During each of n days of his work one of the two following events took place:   A customer came to Bob and asked to sell him a 2x MB memory stick. If Bob had such a stick, he sold it and got 2x berllars.  Bob won some programming competition and got a 2x MB memory stick as a prize. Bob could choose whether to present this memory stick to one of his friends, or keep it. Bob never kept more than one memory stick, as he feared to mix up their capacities, and deceive a customer unintentionally. It is also known that for each memory stick capacity there was at most one customer, who wanted to buy that memory stick. Now, knowing all the customers' demands and all the prizes won at programming competitions during the last n days, Bob wants to know, how much money he could have earned, if he had acted optimally.

The first input line contains number n (1 ≤ n ≤ 5000) — amount of Bob's working days. The following n lines contain the description of the days. Line sell x stands for a day when a customer came to Bob to buy a 2x MB memory stick (0 ≤ x ≤ 2000). It's guaranteed that for each x there is not more than one line sell x. Line win x stands for a day when Bob won a 2x MB memory stick (0 ≤ x ≤ 2000).

Output the maximum possible earnings for Bob in berllars, that he would have had if he had known all the events beforehand. Don't forget, please, that Bob can't keep more than one memory stick at a time.

7
win 10
win 5
win 3
sell 5
sell 3
win 10
sell 10

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

let base = 100000000
let base_digits = 8

let () =
  let n = read_int 0 in
  let a = Array.make (max n 700) (-1) in
  let b = ref [] in
  for i = 0 to n-1 do
    let op = read_str 0 in
    let x = read_int 0 in
    if op.[0] = 'w' then
      a.(i) <- x
    else (
      b := (x,i)::!b;
    )
  done;

  let mask = Array.make 2001 false in
  List.sort compare !b |> List.rev |> List.iter (fun (lv,x) ->
    let rec go j =
      if j >= 0 && a.(j) <> (-2) then
        if a.(j) = lv then (
          Array.fill a j (x-j+1) (-2);
          mask.(lv) <- true
        ) else
          go (j-1)
    in
    go x
  );

  let m = ref 1 in
  a.(0) <- 0;
  for i = 2001-1 downto 0 do
    let rec go c j =
      if j < !m then (
        let t = a.(j)*2+c in
        a.(j) <- t mod base;
        go (t/base) (j+1)
      ) else if c > 0 then (
        a.(j) <- c;
        !m+1
      ) else
        !m
    in
    m := go (if mask.(i) then 1 else 0) 0;
  done;

  Printf.printf "%d" a.(!m-1);
  for i = !m-2 downto 0 do
    Printf.printf "%0*d" base_digits a.(i)
  done;
  print_char '\n'


ZS the Coder is coding on a crazy computer. If you don't type in a word for a c consecutive seconds, everything you typed disappear! More formally, if you typed a word at second a and then the next word at second b, then if b - a ≤ c, just the new word is appended to other words on the screen. If b - a > c, then everything on the screen disappears and after that the word you have typed appears on the screen.For example, if c = 5 and you typed words at seconds 1, 3, 8, 14, 19, 20 then at the second 8 there will be 3 words on the screen. After that, everything disappears at the second 13 because nothing was typed. At the seconds 14 and 19 another two words are typed, and finally, at the second 20, one more word is typed, and a total of 3 words remain on the screen.You're given the times when ZS the Coder typed the words. Determine how many words remain on the screen after he finished typing everything.

The first line contains two integers n and c (1 ≤ n ≤ 100 000, 1 ≤ c ≤ 109) — the number of words ZS the Coder typed and the crazy computer delay respectively. The next line contains n integers t1, t2, ..., tn (1 ≤ t1 < t2 < ... < tn ≤ 109), where ti denotes the second when ZS the Coder typed the i-th word.

Print a single positive integer, the number of words that remain on the screen after all n words was typed, in other words, at the second tn.

NoteThe first sample is already explained in the problem statement.For the second sample, after typing the first word at the second 1, it disappears because the next word is typed at the second 3 and 3 - 1 > 1. Similarly, only 1 word will remain at the second 9. Then, a word is typed at the second 10, so there will be two words on the screen, as the old word won't disappear because 10 - 9 ≤ 1.

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

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

let counter count max_delay diff =
    if diff <= max_delay
    then
        count + 1
    else
        1

let input () =
    let n = read () in
    let delay = read () in
    let seconds = make_list n in
    (delay, seconds)

let solve (delay, seconds) =
    let rec loop prev rest count =
        match rest with
        | (head :: tail) -> loop head tail (counter count delay (head - prev))
        | [] -> count
    in loop 0 seconds 0

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

let read_nums () =
    let s = read_line () in
    let nums = List.map int_of_string (Str.split (Str.regexp " ") s) in
    nums

;;

let rec get_ans c lst acc prev=
    match lst with
    | hd :: tl -> if (hd - prev <= c) then
                      get_ans c tl (acc + 1) hd
                  else
                      get_ans c tl 1 hd
    | [] -> let () = print_int acc in print_string "\n"

let main () =
    let l = read_nums () in
    match l with
    | [n; c] -> (get_ans c (read_nums ())) 0 0
    | _ -> ()
;;

main () ;;

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

let () =
  let n = read_int () in
  let c = read_int () in
  let time_arr = Array.init n (fun _ ->
      read_int ()
    )
  in
  let counter = ref 1 in
  for i = 0 to n - 2 do
    if time_arr.(i+1) - time_arr.(i) <= c then
      counter := !counter + 1
    else counter := 1
  done;
  Printf.printf "%d" !counter

open Scanf
open Printf

let rec calc a i cur n c = if (i = n) then cur
else if (a.(i) - a.(i - 1) > c) then calc a (i + 1) 1 n c
else calc a (i + 1) (cur + 1) n c;;

let readInt () = scanf " %d " (fun x -> x)

let a =
let answer =
let n = readInt () in
let c = readInt () in
let a  = Array.init n (fun y -> readInt ()) in
calc a 1 1 n c
in printf "%d\n" answer;;

open Scanf
open Printf

let rec calc a i cur n c = if (i = n) then cur
else if (a.(i) - a.(i - 1) > c) then calc a (i + 1) 1 n c
else calc a (i + 1) (cur + 1) n c;;

let a =
let answer =
let n = scanf " %d " (fun x-> x) in
let c = scanf " %d " (fun x-> x) in
let a  = Array.init n (fun y -> scanf " %d " (fun x -> x)) in
calc a 1 1 n c
in printf "%d\n" answer;;


You are given an array $$$a_1, a_2, \ldots, a_n$$$ consisting of $$$n$$$ positive integers and a positive integer $$$m$$$.You should divide elements of this array into some arrays. You can order the elements in the new arrays as you want.Let's call an array $$$m$$$-divisible if for each two adjacent numbers in the array (two numbers on the positions $$$i$$$ and $$$i+1$$$ are called adjacent for each $$$i$$$) their sum is divisible by $$$m$$$. An array of one element is $$$m$$$-divisible.Find the smallest number of $$$m$$$-divisible arrays that $$$a_1, a_2, \ldots, a_n$$$ is possible to divide into.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 1000)$$$  — the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$m$$$ $$$(1 \le n \le 10^5, 1 \le m \le 10^5)$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ $$$(1 \le a_i \le 10^9)$$$. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases do not exceed $$$10^5$$$.

For each test case print the answer to the problem.

NoteIn the first test case we can divide the elements as follows:  $$$[4, 8]$$$. It is a $$$4$$$-divisible array because $$$4+8$$$ is divisible by $$$4$$$.  $$$[2, 6, 2]$$$. It is a $$$4$$$-divisible array because $$$2+6$$$ and $$$6+2$$$ are divisible by $$$4$$$.  $$$[9]$$$. It is a $$$4$$$-divisible array because it consists of one element.

(* https://codeforces.com/contest/1497/problem/B *)

let make_hist modulo arr =
    let histo = Array.make modulo 0 in
    List.iter
        (fun e -> histo.(e) <- histo.(e) + 1)
        arr;
    histo

let marrays m l =
    let even = m mod 2 = 0 in
    let modulos =
        List.map (fun e -> Int64.rem e (Int64.of_int m) |> Int64.to_int)
        l in
    let histo = make_hist m modulos and
    last_i = (if even then m / 2 - 1 else m / 2) in
    let rec pair_modulos i nb_arrays =
        if i > last_i
        then nb_arrays
        else
            let min_amount = min histo.(i) histo.(m-i) and
            max_amount = max histo.(i) histo.(m-i) in
            if max_amount = min_amount && max_amount <> 0
            then pair_modulos (i+1) (nb_arrays+1)
            else pair_modulos (i+1) (nb_arrays+(max_amount-min_amount)) in
    let nb_arrays = ref 0 in
    nb_arrays := !nb_arrays + (if histo.(0) > 0 then 1 else 0);
    nb_arrays := !nb_arrays + (if even && histo.(m/2) > 0 then 1 else 0);
    nb_arrays := !nb_arrays + (pair_modulos 1 0);
    !nb_arrays

let read_case () =
    let [_; m] =
        read_line ()
        |> Str.split (Str.regexp " ")
        |> List.map int_of_string in
    let nums =
        read_line ()
        |> Str.split (Str.regexp " ")
        |> List.map Int64.of_string in
    m, nums

let rec solve_n n =
    if n <> 0
    then
        let m, nums = read_case () in
        let _ = marrays m nums
        |> Printf.printf "%d\n" in
        solve_n (n-1)

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

(* https://codeforces.com/contest/1497/problem/B *)

let make_hist modulo arr =
    let histo = Array.make modulo 0 in
    List.iter
        (fun e -> histo.(e) <- histo.(e) + 1)
        arr;
    histo

let marrays m l =
    let even = m mod 2 = 0 in
    let modulos =
        List.map (fun e -> Int64.rem e (Int64.of_int m) |> Int64.to_int)
        l in
    let histo = make_hist m modulos and
    last_i = (if even then m / 2 - 1 else m / 2) in
    let rec pair_modulos i nb_arrays =
        if i > last_i
        then nb_arrays
        else
            let min_amount = min histo.(i) histo.(m-i) in
            let _ = histo.(i) <- histo.(i) - (min_amount+1) and
            _ = histo.(m-i) <- histo.(m-i) - (min_amount+1) in
            pair_modulos (i+1) (nb_arrays+1) in
    let nb_arrays = ref 0 in
    nb_arrays := !nb_arrays + (if histo.(0) > 0 then 1 else 0);
    nb_arrays := !nb_arrays + (if even && histo.(m/2) > 0 then 1 else 0);
    nb_arrays := !nb_arrays + (pair_modulos 1 0);
    Array.iteri
        (fun i e ->
            if i = 0
            then ()
            else if even && i = m / 2
            then ()
            else if e > 0
            then nb_arrays := !nb_arrays + e)
        histo;
    !nb_arrays

let read_case () =
    let [_; m] =
        read_line ()
        |> Str.split (Str.regexp " ")
        |> List.map int_of_string in
    let nums =
        read_line ()
        |> Str.split (Str.regexp " ")
        |> List.map Int64.of_string in
    m, nums

let rec solve_n n =
    if n <> 0
    then
        let m, nums = read_case () in
        let _ = marrays m nums
        |> Printf.printf "%d\n" in
        solve_n (n-1)

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


You are given two arrays $$$a$$$ and $$$b$$$ both consisting of $$$n$$$ positive (greater than zero) integers. You are also given an integer $$$k$$$.In one move, you can choose two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) and swap $$$a_i$$$ and $$$b_j$$$ (i.e. $$$a_i$$$ becomes $$$b_j$$$ and vice versa). Note that $$$i$$$ and $$$j$$$ can be equal or different (in particular, swap $$$a_2$$$ with $$$b_2$$$ or swap $$$a_3$$$ and $$$b_9$$$ both are acceptable moves).Your task is to find the maximum possible sum you can obtain in the array $$$a$$$ if you can do no more than (i.e. at most) $$$k$$$ such moves (swaps).You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 30; 0 \le k \le n$$$) — the number of elements in $$$a$$$ and $$$b$$$ and the maximum number of moves you can do. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 30$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 30$$$), where $$$b_i$$$ is the $$$i$$$-th element of $$$b$$$.

For each test case, print the answer — the maximum possible sum you can obtain in the array $$$a$$$ if you can do no more than (i.e. at most) $$$k$$$ swaps.

NoteIn the first test case of the example, you can swap $$$a_1 = 1$$$ and $$$b_2 = 4$$$, so $$$a=[4, 2]$$$ and $$$b=[3, 1]$$$.In the second test case of the example, you don't need to swap anything.In the third test case of the example, you can swap $$$a_1 = 1$$$ and $$$b_1 = 10$$$, $$$a_3 = 3$$$ and $$$b_3 = 10$$$ and $$$a_2 = 2$$$ and $$$b_4 = 10$$$, so $$$a=[10, 10, 10, 4, 5]$$$ and $$$b=[1, 9, 3, 2, 9]$$$.In the fourth test case of the example, you cannot swap anything.In the fifth test case of the example, you can swap arrays $$$a$$$ and $$$b$$$, so $$$a=[4, 4, 5, 4]$$$ and $$$b=[1, 2, 2, 1]$$$.

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

let rec read_list = function
| 0 -> []
| n -> read() :: read_list (n - 1)
in

let rec print_list = function
| [] -> ()
| x :: r -> print_int x; print_newline (); print_list r
in

let rec biggest_sum a b nb = function
| 0 -> 0
| n -> if List.hd a < List.hd b && nb != 0 then
      (List.hd b) + (biggest_sum a (List.tl b) (nb - 1) (n - 1))
   else
      (List.hd a) + (biggest_sum (List.tl a) b nb (n - 1))
in

let nbTests = read () in
for iTest = 1 to nbTests do
   let nbElems = read () in
   let nbEchanges = read () in
   let a = List.rev (List.sort (-) (read_list nbElems)) in
   let b = List.rev (List.sort (-) (read_list nbElems)) in

   print_int (biggest_sum a b nbEchanges nbElems);
   print_newline ()
done;


You are given two very long integers a, b (leading zeroes are allowed). You should check what number a or b is greater or determine that they are equal.The input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java. Don't use the function input() in Python2 instead of it use the function raw_input().

The first line contains a non-negative integer a. The second line contains a non-negative integer b. The numbers a, b may contain leading zeroes. Each of them contains no more than 106 digits.

Print the symbol "<" if a < b and the symbol ">" if a > b. If the numbers are equal print the symbol "=".

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

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

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

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

let sprawdz n a = (* czy jest jakis niezerowy *)
  let koniec = ref false in
  for i=0 to n do
    if a.[i] <> '0' then koniec := true
  done;
  !koniec;;

let rec porownaj ax bx a b =
  if ax = String.length a then '='
  else if a.[ax] = b.[bx] then porownaj (ax+1) (bx+1) a b
  else if a.[ax] < b.[bx] then '<'
  else '>';;

let check a b =
  let n = String.length a
  and m = String.length b in
  if sprawdz (n-m-1) a then '>'
  else if sprawdz (m-n-1) b then '<'
  else
    let ax = max 0 (n-m)
    and bx = max 0 (m-n) in
    porownaj ax bx a b;;

let _ =
  let (a,b) = Scanf.scanf "%s\n%s\n" (fun x y -> x, y) in
  Printf.printf "%c\n" (check a b) ;;

let xstr() = Scanf.scanf "%s " (fun x -> x)

let () =
  let s = xstr() and t = xstr() in
  let n = String.length s and m = String.length t in
  let i = ref 0 and j = ref 0 and res = ref 0 in
  while s.[!i] == '0' && !i + 1 < n do
    i := !i + 1;
  done;
  while t.[!j] == '0' && !j + 1 < m do
    j := !j + 1;
  done;
  res := (if n - !i < m - !j then -1 else (
    if n - !i > m - !j then 1 else 0
  ));
  if n - !i = m - !j then (
    res := 0;
    while !i < n && !j < m && !res = 0 do
      res := if s.[!i] < t.[!j] then -1 else (
        if s.[!i] > t.[!j] then 1 else 0
      );
      i := !i + 1;
      j := !j + 1;
    done;
  );
  if !res = 0 then (
    Printf.printf "=\n";
  );
  if !res < 0 then (
    Printf.printf "<\n";
  );
  if !res > 0 then (
    Printf.printf ">\n";
  );

let xstr() = Scanf.scanf "%s " (fun x -> x)

let () =
  let s = xstr() and t = xstr() in
  let n = String.length s and m = String.length t in
  let i = ref 0 and j = ref 0 and res = ref 0 in
  while s.[!i] == '0' && !i + 1 < n do
    i := !i + 1;
  done;
  while t.[!j] == '0' && !j + 1 < m do
    j := !j + 1;
  done;
  res := (if n - !i < m - !j then -1 else (
    if n - !i < m - !j then 1 else 0
  ));
  if n - !i = m - !j then (
    res := 0;
    while !i < n && !j < m && !res = 0 do
      res := if s.[!i] < t.[!j] then -1 else (
        if s.[!i] > t.[!j] then 1 else 0
      );
      i := !i + 1;
      j := !j + 1;
    done;
  );
  if !res = 0 then (
    Printf.printf "=\n";
  );
  if !res < 0 then (
    Printf.printf "<\n";
  );
  if !res > 0 then (
    Printf.printf ">\n";
  );


This is the easier version of the problem. In this version, $$$1 \le n \le 10^5$$$ and $$$0 \le a_i \le 1$$$. You can hack this problem only if you solve and lock both problems.Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare $$$n$$$ boxes of chocolate, numbered from $$$1$$$ to $$$n$$$. Initially, the $$$i$$$-th box contains $$$a_i$$$ chocolate pieces.Since Bob is a typical nice guy, he will not send Alice $$$n$$$ empty boxes. In other words, at least one of $$$a_1, a_2, \ldots, a_n$$$ is positive. Since Alice dislikes coprime sets, she will be happy only if there exists some integer $$$k > 1$$$ such that the number of pieces in each box is divisible by $$$k$$$. Note that Alice won't mind if there exists some empty boxes. Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box $$$i$$$ and put it into either box $$$i-1$$$ or box $$$i+1$$$ (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of chocolate boxes. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 1$$$) — the number of chocolate pieces in the $$$i$$$-th box. It is guaranteed that at least one of $$$a_1, a_2, \ldots, a_n$$$ is positive.

If there is no way for Charlie to make Alice happy, print $$$-1$$$. Otherwise, print a single integer $$$x$$$ — the minimum number of seconds for Charlie to help Bob make Alice happy.

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

let cost arr k =
  let n = Array.length arr in
  let tar j = (j/k) * k + k/2 in
  Array.init n (fun i -> (Int64.abs (arr.(tar i) -- arr.(i))))
  |> Array.fold_left ( ++ ) 0L

let () =
  let n = read_int () in
  let a = Array.init n (fun _ -> Scanf.scanf " %d " (fun x -> x)) in
  let rec iter j =
    if j = n then []
    else if a.(j)=1 then (Int64.of_int j)::(iter (j+1)) else iter (j+1) in
  let arr = Array.of_list (iter 0) in
  let n = Array.length arr in
  let rec iter acc n d =
    if d * d > n then (if n = 1 then acc else n::acc)
    else if n mod d > 0 then iter acc n (d+1)
    else let rec iter' n d = if n mod d = 0 then iter' (n/d) d else n in
      iter (d::acc) (iter' n d) (d+1) in
  let primes = iter [] n 2 in
  (* List.iter (Printf.printf "%d\n") primes; *)
  if n = 1 then Printf.printf "-1\n" else
    List.map (cost arr) primes
    (* |> List.iter (Printf.printf " %Ld") *)
    |> List.fold_left min 123412341234L
    |> Printf.printf "%Ld\n"

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

let cost arr k =
  let n = Array.length arr in
  let tar j = (j/k) * k + k/2 in
  Array.init n (fun i -> (Int64.abs (arr.(tar i) -- arr.(i))))
  |> Array.fold_left ( ++ ) 0L

let () =
  let n = read_int () in
  let a = Array.init n (fun _ -> Scanf.scanf " %d " (fun x -> x)) in
  let rec iter j =
    if j = n then []
    else if a.(j)=1 then (Int64.of_int j)::(iter (j+1)) else iter (j+1) in
  let arr = Array.of_list (iter 0) in
  let n = Array.length arr in
  let rec iter acc n d =
    if d * d > n then (if n = 1 then acc else n::acc)
    else if n mod d > 0 then iter acc n (d+1)
    else let rec iter' n d = if n mod d = 0 then iter' (n/d) d else n in
      iter (d::acc) (iter' n d) (d+1) in
  let primes = iter [] n 2 in
  (* List.iter (Printf.printf "%d\n") primes; *)
  if n = 1 then Printf.printf "-1\n" else
    List.map (cost arr) primes
    (* |> List.iter (Printf.printf " %Ld") *)
    |> List.fold_left min 0L
    |> Printf.printf "%Ld\n"