Little X has n distinct integers: p1, p2, ..., pn. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied:  If number x belongs to set A, then number a - x must also belong to set A.  If number x belongs to set B, then number b - x must also belong to set B. Help Little X divide the numbers into two sets or determine that it's impossible.

The first line contains three space-separated integers n, a, b (1 ≤ n ≤ 105; 1 ≤ a, b ≤ 109). The next line contains n space-separated distinct integers p1, p2, ..., pn (1 ≤ pi ≤ 109).

If there is a way to divide the numbers into two sets, then print "YES" in the first line. Then print n integers: b1, b2, ..., bn (bi equals either 0, or 1), describing the division. If bi equals to 0, then pi belongs to set A, otherwise it belongs to set B. If it's impossible, print "NO" (without the quotes).

NoteIt's OK if all the numbers are in the same set, and the other one is empty.

open Printf
open Scanf

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

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

let read_long () = bscanf Scanning.stdib " %Ld " (fun x -> x)
let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let a = read_long () in
  let b = read_long () in

  let h = Hashtbl.create 10 in

  let ps = Array.make n 0L in

  for i=0 to n-1 do
    let p = read_long() in
    ps.(i) <- p;
    Hashtbl.replace h p i
  done;

  let lookup x = try Hashtbl.find h x with Not_found -> -1 in

  let pair = Array.make_matrix n 2 (-1) in

  for i=0 to n-1 do
    pair.(i).(0) <- lookup (a -- ps.(i));
    pair.(i).(1) <- lookup (b -- ps.(i));
  done;

  let compat i color = pair.(i).(color) >= 0 in
  let degree i = (if compat i 0 then 1 else 0) + (if compat i 1 then 1 else 0) in

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

  let rec dfs v col parity = if color.(v) >= 0 then true else (
    color.(v) <- col;
    let next = pair.(v).(parity) in
    if degree next = 1 then (
      if compat next col then (
	color.(next) <- col;
	true;
      ) else false
    ) else (
      dfs next col (1-parity)
    )
  )
  in

  if forall 0 (n-1)
    (fun v -> match (compat v 0, compat v 1) with | (true,true) -> true | _ -> false) then (
      Array.fill color 0 n 0
  );

  let answer = forall 0 (n-1) (fun v ->
    match (compat v 0, compat v 1) with
      | (true,true) -> true
      | (true,false) -> dfs v 0 0
      | (false,true) -> dfs v 1 1
      | (false,false) -> false
  ) in

  if answer then (
    printf "YES\n";
    for i=0 to n-1 do
      printf "%s%d" (if i>0 then " " else "") color.(i)
    done;
    print_newline();
  ) else printf "NO\n"

open Printf
open Scanf

let ( ++ ) a b = Int64.add a b
let ( -- ) a b = Int64.sub a b
let long x = Int64.of_int x

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

let read_long () = bscanf Scanning.stdib " %Ld " (fun x -> x)
let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let a = read_long () in
  let b = read_long () in

  let h = Hashtbl.create 10 in

  let ps = Array.make n 0L in

  for i=0 to n-1 do
    let p = read_long() in
    ps.(i) <- p;
    Hashtbl.replace h p i
  done;

  let lookup x = try Hashtbl.find h x with Not_found -> -1 in

  let apair = Array.make n (-1) in
  let bpair = Array.make n (-1) in

  for i=0 to n-1 do
    apair.(i) <- lookup (a -- ps.(i));
    bpair.(i) <- lookup (b -- ps.(i));
  done;

  let all_paired = forall 0 (n-1) (fun i -> apair.(i)>=0 && bpair.(i)>=0) in

  if all_paired then (
    printf "YES\n";
    for i=0 to n-1 do
      if i>0 then printf " ";
      printf "1"
    done;
    print_newline()
  ) else (
    if exists 0 (n-1) (fun i -> apair.(i)<0 && bpair.(i)<0) then printf "NO\n" else (

      let rec loop i = if i=n then () else
	  (
	    if apair.(i) >=0 && bpair.(i) >=0 then ()
	    else if apair.(i) <0 && bpair.(i) >=0 then
	      apair.(bpair.(i)) <- -1
	    else if apair.(i) >=0 && bpair.(i) < 0 then
	      bpair.(apair.(i)) <- -1
	    else ();
	    loop (i+1)
	  )
      in

      loop 0;

      if exists 0 (n-1) (fun i -> apair.(i)<0 && bpair.(i)<0) then printf "NO\n" else (

	printf "YES\n";
	for i=0 to n-1 do
	  if i>0 then printf " ";
	  printf "%d" (if apair.(i)>=0 then 0 else 1)
	done;
	print_newline()
      )
    )
  )

open Printf
open Scanf

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

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

let read_long () = bscanf Scanning.stdib " %Ld " (fun x -> x)
let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let a = read_long () in
  let b = read_long () in

  let h = Hashtbl.create 10 in

  let ps = Array.make n 0L in

  for i=0 to n-1 do
    let p = read_long() in
    ps.(i) <- p;
    Hashtbl.replace h p i
  done;

  let lookup x = try Hashtbl.find h x with Not_found -> -1 in

  let pair = Array.make_matrix n 2 (-1) in

  for i=0 to n-1 do
    pair.(i).(0) <- lookup (a -- ps.(i));
    pair.(i).(1) <- lookup (b -- ps.(i));
  done;

  let compat i color = pair.(i).(color) >= 0 in

  let visited = Array.make n false in

  let rec dfs v color parity = if visited.(v) then true else (
    visited.(v) <- true;
    if compat v color && compat v parity then (
      let next = pair.(v).(parity) in
      pair.(v).(1-color) <- -1;
      dfs next color (1-parity)
    ) else false
  )
  in
  let answer = forall 0 (n-1) (fun v ->
    match (compat v 0, compat v 1) with
      | (true,true) -> true
      | (true,false) -> dfs v 0 0
      | (false,true) -> dfs v 1 1
      | (false,false) -> false
  ) in

  if answer then (
    printf "YES\n";
    for i=0 to n-1 do
      printf "%s%d" (if i>0 then " " else "") (if compat i 0 then 0 else 1)
    done;
    print_newline();
  ) else printf "NO\n"


Little Chris is very keen on his toy blocks. His teacher, however, wants Chris to solve more problems, so he decided to play a trick on Chris.There are exactly s blocks in Chris's set, each block has a unique number from 1 to s. Chris's teacher picks a subset of blocks X and keeps it to himself. He will give them back only if Chris can pick such a non-empty subset Y from the remaining blocks, that the equality holds:  "Are you kidding me?", asks Chris.For example, consider a case where s = 8 and Chris's teacher took the blocks with numbers 1, 4 and 5. One way for Chris to choose a set is to pick the blocks with numbers 3 and 6, see figure. Then the required sums would be equal: (1 - 1) + (4 - 1) + (5 - 1) = (8 - 3) + (8 - 6) = 7.  However, now Chris has exactly s = 106 blocks. Given the set X of blocks his teacher chooses, help Chris to find the required set Y!

The first line of input contains a single integer n (1 ≤ n ≤ 5·105), the number of blocks in the set X. The next line contains n distinct space-separated integers x1, x2, ..., xn (1 ≤ xi ≤ 106), the numbers of the blocks in X. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.

In the first line of output print a single integer m (1 ≤ m ≤ 106 - n), the number of blocks in the set Y. In the next line output m distinct space-separated integers y1, y2, ..., ym (1 ≤ yi ≤ 106), such that the required equality holds. The sets X and Y should not intersect, i.e. xi ≠ yj for all i, j (1 ≤ i ≤ n; 1 ≤ j ≤ m). It is guaranteed that at least one solution always exists. If there are multiple solutions, output any of them.

open Printf
open Scanf

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

let () =
  let s = 1_000_000 in
  let n = read_int () in

  let comp x = s+1-x in
  let usedx = Array.make (s+1) false in

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

  printf "%d\n" n;

  let count = ref 0 in

  for i=1 to s do
    if (not usedx.(i)) && usedx.(comp i) then (
      usedx.(i) <- true;
      printf "%s%d" (if !count=0 then "" else " ") i;
      count := !count+1
    )
  done;

  let pairs = (n - !count)/2 in

  let rec loop y j = if j=0 then () else
      if not usedx.(y) then (
	printf "%s%d %d" (if !count=0 then "" else " ") y (comp y);
	count := !count + 2;
	loop (y+1) (j-1)
      ) else loop (y+1) j
  in

  loop 1 pairs;
  print_newline()

open Printf
open Scanf

let (@@) f x = f x;;
let (@.) f g x = f (g x);;

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

let n = read_int();;

let a = Array.make 1000000 false;;
module IntSet = Set.Make(struct type t = int;; let compare = Pervasives.compare;; end);;

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

let rec f (i : int) (count : int) (set : IntSet.t) : int * IntSet.t =
  if i = 500000 then (count, set)
  else if a.(i) then
    if a.(1000000-i-1) then f (i+1) (count+1) set
    else f (i+1) count @@ IntSet.add (1000000-i) set
  else
    if a.(1000000-i-1) then f (i+1) count @@ IntSet.add (i+1) set
    else f (i+1) count set
;;

let (count, set) = f 0 0 IntSet.empty;;

let rec g (i : int) (count : int) (set : IntSet.t) : int * IntSet.t =
  if i = 500000 then (count, set)
  else if count = 0 then (0, set)
  else if (not a.(i)) && (not a.(1000000-i-1)) then g (i+1) (count-1) @@ IntSet.add (i+1) @@ IntSet.add (1000000-i) set
  else g (i+1) count set
;;

let (count, set) = g 0 count set;;

printf "%d\n" @@ IntSet.cardinal set;
IntSet.iter (fun x -> printf "%d " x) set;
print_newline();

open Printf
open Scanf

let (@@) f x = f x;;
let (@.) f g x = f (g x);;

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

let n = read_int();;

let a = Array.make 1000000 false;;
module IntSet = Set.Make(struct type t = int;; let compare = Pervasives.compare;; end);;

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

let rec f (i : int) (count : int) (set : IntSet.t) : int * IntSet.t =
  if i = 500000 then (count, set)
  else if a.(i) then
    if a.(1000000-i-1) then f (i+1) (count+1) set
    else f (i+1) count @@ IntSet.add (1000000-i) set
  else
    if a.(1000000-i-1) then f (i+1) count @@ IntSet.add (i+1) set
    else f (i+1) count set
;;

let (count, set) = f 0 0 IntSet.empty;;

let rec g (i : int) (count : int) (set : IntSet.t) : int * IntSet.t =
  if i = 500000 then (count, set)
  else if count = 0 then (0, set)
  else if (not a.(i)) && (not a.(1000000-i-1)) then g (i+1) (count-1) @@ IntSet.add (i+1) @@ IntSet.add (1000000-i-1) set
  else g (i+1) count set
;;

let (count, set) = g 0 count set;;

IntSet.iter (fun x -> printf "%d " x) set;
print_newline();

open Printf
open Scanf

let (@@) f x = f x;;
let (@.) f g x = f (g x);;

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

let n = read_int();;

let a = Array.make 1000000 false;;
module IntSet = Set.Make(struct type t = int;; let compare = Pervasives.compare;; end);;

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

let rec f (i : int) (count : int) (set : IntSet.t) : int * IntSet.t =
  if i = 500000 then (count, set)
  else if a.(i) then
    if a.(1000000-i-1) then f (i+1) (count+1) set
    else f (i+1) count @@ IntSet.add (1000000-i) set
  else
    if a.(1000000-i-1) then f (i+1) count @@ IntSet.add (i+1) set
    else f (i+1) count set
;;

let (count, set) = f 0 0 IntSet.empty;;

let rec g (i : int) (count : int) (set : IntSet.t) : int * IntSet.t =
  if i = 500000 then (count, set)
  else if count = 0 then (0, set)
  else if (not a.(i)) && (not a.(1000000-i-1)) then g (i+1) (count-1) @@ IntSet.add (i+1) @@ IntSet.add (1000000-i-1) set
  else g (i+1) count set
;;

let (count, set) = g 0 count set;;

printf "%d\n" @@ IntSet.cardinal set;
IntSet.iter (fun x -> printf "%d " x) set;
print_newline();


There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions on what should be the outcome of the vote. The voting procedure is rather complicated:   Each of n employees makes a statement. They make statements one by one starting from employees 1 and finishing with employee n. If at the moment when it's time for the i-th employee to make a statement he no longer has the right to vote, he just skips his turn (and no longer takes part in this voting).  When employee makes a statement, he can do nothing or declare that one of the other employees no longer has a right to vote. It's allowed to deny from voting people who already made the statement or people who are only waiting to do so. If someone is denied from voting he no longer participates in the voting till the very end.  When all employees are done with their statements, the procedure repeats: again, each employees starting from 1 and finishing with n who are still eligible to vote make their statements.  The process repeats until there is only one employee eligible to vote remaining and he determines the outcome of the whole voting. Of course, he votes for the decision suitable for his fraction. You know the order employees are going to vote and that they behave optimal (and they also know the order and who belongs to which fraction). Predict the outcome of the vote.

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of employees.  The next line contains n characters. The i-th character is 'D' if the i-th employee is from depublicans fraction or 'R' if he is from remocrats.

Print 'D' if the outcome of the vote will be suitable for depublicans and 'R' if remocrats will win.

NoteConsider one of the voting scenarios for the first sample:   Employee 1 denies employee 5 to vote.  Employee 2 denies employee 3 to vote.  Employee 3 has no right to vote and skips his turn (he was denied by employee 2).  Employee 4 denies employee 2 to vote.  Employee 5 has no right to vote and skips his turn (he was denied by employee 1).  Employee 1 denies employee 4.  Only employee 1 now has the right to vote so the voting ends with the victory of depublicans.

let vote_result (s : string) : char =
  let d = Queue.create () in
  let r = Queue.create () in
  begin
    String.iteri
      (fun i c ->
        match c with
        | 'D' -> Queue.push i d
        | 'R' -> Queue.push i r
        | _ -> failwith "input not consists of just D and R")
      s;

    let n = ref (String.length s) in
    let rec loop () =
      match (Queue.is_empty d, Queue.is_empty r) with
      | false, false ->
          Queue.push (!n)
            (if Queue.pop d < Queue.pop r then d else r);
          incr n;
          loop ()
      | true, false -> 'R'
      | false, true -> 'D'
      | true, true -> failwith "impossible"
    in loop ()
  end

let main () =
  let n = read_int () in
    let s = really_input_string stdin n in
      print_char (vote_result s)

let () = main ()

let vote_result (s : string) : char =
  let n = ref (String.length s) in
  let bs = Bytes.unsafe_of_string s in
  let prev_n = ref 1 in
    while (!n) <> (!prev_n) do
      let l = !n in
      prev_n := l;
      begin
        let d = ref 0 in
        let r = ref 0 in
        for i = 0 to l-1 do
          match Bytes.get bs i with
            'D' ->
              begin
                while ((!r) < l) && (Bytes.get bs (!r) <> 'R') do incr r done;
                if (!r) < l then Bytes.set bs (!r) ' ' else ()
              end
          | 'R' ->
              begin
                while ((!d) < l) && (Bytes.get bs (!d) <> 'D') do incr d done;
                if (!d) < l then Bytes.set bs (!d) ' ' else ()
              end
          | _ -> ()
        done
      end;
      begin
        n := 0;
        for i = 0 to l-1 do
          match Bytes.get bs i with
            'D' -> (Bytes.set bs (!n) 'D'; incr n)
          | 'R' -> (Bytes.set bs (!n) 'R'; incr n)
          | _ -> ()
        done
      end
    done;
    Bytes.get bs 0

let main () =
  let _ = read_int () in
  let s = read_line () in
    print_char (vote_result s)

let () = main ()

let vote_result (s : string) : char =
  let n = ref (String.length s) in
  let bs = Bytes.unsafe_of_string s in
  let prev_n = ref 1 in
    while (!n) <> (!prev_n) do
      let l = !n in
      prev_n := l;
      begin
        let d = ref 0 in
        let r = ref 0 in
        for i = 0 to l-1 do
          match Bytes.get bs i with
            'D' ->
              begin
                if (!r) <= i then r := i+1;
                while ((!r) < l) && (Bytes.get bs (!r) <> 'R') do incr r done;
                if (!r) < l then Bytes.set bs (!r) ' ' else ()
              end
          | 'R' ->
              begin
                if (!d) <= i then d := i+1;
                while ((!d) < l) && (Bytes.get bs (!d) <> 'D') do incr d done;
                if (!d) < l then Bytes.set bs (!d) ' ' else ()
              end
          | _ -> ()
        done
      end;
      begin
        n := 0;
        for i = 0 to l-1 do
          match Bytes.get bs i with
            'D' -> (Bytes.set bs (!n) 'D'; incr n)
          | 'R' -> (Bytes.set bs (!n) 'R'; incr n)
          | _ -> ()
        done
      end
    done;
    Bytes.get bs 0

let main () =
  let _ = read_int () in
  let s = read_line () in
    print_char (vote_result s)

let () = main ()


One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two primes". Let's modify it. How about a statement like that: "each integer no less than 12 can be expressed as the sum of two composite numbers." Not like the Goldbach's conjecture, I can prove this theorem.You are given an integer n no less than 12, express it as a sum of two composite numbers.

The only line contains an integer n (12 ≤ n ≤ 106).

Output two composite integers x and y (1 < x, y < n) such that x + y = n. If there are multiple solutions, you can output any of them.

NoteIn the first example, 12 = 4 + 8 and both 4, 8 are composite numbers. You can output "6 6" or "8 4" as well.In the second example, 15 = 6 + 9. Note that you can't output "1 14" because 1 is not a composite number.

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

let solve int =
    let rec loop n =
        if n < int / 2
        then
            let div = 2 * n in
            let rest = int - div in
            if rest mod 2 = 0
            then
                (div, rest)
            else
                if rest mod 3 = 0
                then
                    (div, rest)
                else
                    loop (n + 1)
        else
            failwith "Bad number"
    in loop 2

let print (a, b) = Printf.printf "%d %d\n" a b

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

open Printf

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

let () =
  let n = int_of_string @@ input_line stdin in
  if n mod 2 = 0 then
    printf "4 %d\n" (n - 4)
  else
    let (a, b) = order 9 (n - 9) in
    printf "%d %d\n" a b


Luntik has decided to try singing. He has $$$a$$$ one-minute songs, $$$b$$$ two-minute songs and $$$c$$$ three-minute songs. He wants to distribute all songs into two concerts such that every song should be included to exactly one concert.He wants to make the absolute difference of durations of the concerts as small as possible. The duration of the concert is the sum of durations of all songs in that concert.Please help Luntik and find the minimal possible difference in minutes between the concerts durations.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Each test case consists of one line containing three integers $$$a, b, c$$$ $$$(1 \le a, b, c \le 10^9)$$$ — the number of one-minute, two-minute and three-minute songs.

For each test case print the minimal possible difference in minutes between the concerts durations.

NoteIn the first test case, Luntik can include a one-minute song and a two-minute song into the first concert, and a three-minute song into the second concert. Then the difference will be equal to $$$0$$$.In the second test case, Luntik can include two one-minute songs and a two-minute song and a three-minute song into the first concert, and two three-minute songs into the second concert. The duration of the first concert will be $$$1 + 1 + 2 + 3 = 7$$$, the duration of the second concert will be $$$6$$$. The difference of them is $$$|7-6| = 1$$$.

let solve3 a b =
  match b with
  | 0 -> ( match a with
    | 0 -> 3
    | 1 -> 2
    | 2 -> 1
    | _ -> (a - 3) mod 2 )
  | _ -> ( match a with
      | 0 -> 1
      | _ -> (a - 1) mod 2)

let solve0 a b =
  match (b mod 2) with
  | 0 -> (a mod 2)
  | _ -> ( match a with
    | 0 -> 2
    | _ -> (a mod 2)
    )

let solve6 a b =
  match b with
  | 0 -> if (a < 6)  then  6 - a  else (a - 6) mod 2
  | 1 -> if (a < 4)  then  4 - a  else (a - 4) mod 2
  | 2 -> if (a < 2)  then  2 - a  else (a - 2) mod 2
  | _ -> solve0 a (b - 3)

let solve a b c =
  match (c mod 2) with
  | 0 -> solve0 a b
  | _ -> solve3 a b

let solve_ a b c =
  match c with
  | 0 -> solve0 a b
  | _ -> if (c mod 2) == 1
    then solve3 a b
    else min (solve0 a b) (solve6 a b)

let () =
  let tc = Scanf.scanf " %d" (fun x -> x) in
  let rec loop tc =
    if tc == 0 then
    ()
  else
      (let a, b, c = Scanf.scanf " %d %d %d" (fun a b c -> (a, b, c)) in
       Printf.printf "%d\n" (min
                               (solve a b c)
                               (solve_ a b c)
                            );
       loop (tc - 1)
    )
  in loop tc


You have $$$n$$$ gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The $$$i$$$-th gift consists of $$$a_i$$$ candies and $$$b_i$$$ oranges.During one move, you can choose some gift $$$1 \le i \le n$$$ and do one of the following operations:  eat exactly one candy from this gift (decrease $$$a_i$$$ by one);  eat exactly one orange from this gift (decrease $$$b_i$$$ by one);  eat exactly one candy and exactly one orange from this gift (decrease both $$$a_i$$$ and $$$b_i$$$ by one). Of course, you can not eat a candy or orange if it's not present in the gift (so neither $$$a_i$$$ nor $$$b_i$$$ can become less than zero).As said above, all gifts should be equal. This means that after some sequence of moves the following two conditions should be satisfied: $$$a_1 = a_2 = \dots = a_n$$$ and $$$b_1 = b_2 = \dots = b_n$$$ (and $$$a_i$$$ equals $$$b_i$$$ is not necessary).Your task is to find the minimum number of moves required to equalize all the given gifts.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$) — the number of gifts. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the number of candies in the $$$i$$$-th gift. The third line of the test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the number of oranges in the $$$i$$$-th gift.

For each test case, print one integer: the minimum number of moves required to equalize all the given gifts.

NoteIn the first test case of the example, we can perform the following sequence of moves:  choose the first gift and eat one orange from it, so $$$a = [3, 5, 6]$$$ and $$$b = [2, 2, 3]$$$;  choose the second gift and eat one candy from it, so $$$a = [3, 4, 6]$$$ and $$$b = [2, 2, 3]$$$;  choose the second gift and eat one candy from it, so $$$a = [3, 3, 6]$$$ and $$$b = [2, 2, 3]$$$;  choose the third gift and eat one candy and one orange from it, so $$$a = [3, 3, 5]$$$ and $$$b = [2, 2, 2]$$$;  choose the third gift and eat one candy from it, so $$$a = [3, 3, 4]$$$ and $$$b = [2, 2, 2]$$$;  choose the third gift and eat one candy from it, so $$$a = [3, 3, 3]$$$ and $$$b = [2, 2, 2]$$$.

open Printf
open Scanf

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

let solve () =
    let n = read_int() in
    let arr_a = Array.init n read_int in
    let arr_b = Array.init n read_int in
    let _min a b =
        if a > b then b
        else a
    in
    let rec min_element ind arr =
        if Array.length arr = (ind + 1) then (
            arr.(ind)
        ) else (
            min (arr.(ind)) (min_element (ind + 1) arr)
        )
    in
    let min_a = min_element 0 arr_a in
    let min_b = min_element 0 arr_b in
    let rec get_answer ind =
        let x = Int64.of_int (max (arr_a.(ind) - min_a) (arr_b.(ind) - min_b)) in
        if n = (ind + 1) then (
            x
        ) else (
            Int64.add x (get_answer (ind + 1))
        )
    in
    let answer = get_answer 0 in
    printf "%Ld\n" answer

let () =
    let cases = read_int() in
    for case = 1 to cases do
        solve()
    done


Dasha decided to have a rest after solving the problem. She had been ready to start her favourite activity — origami, but remembered the puzzle that she could not solve.   The tree is a non-oriented connected graph without cycles. In particular, there always are n - 1 edges in a tree with n vertices.The puzzle is to position the vertices at the points of the Cartesian plane with integral coordinates, so that the segments between the vertices connected by edges are parallel to the coordinate axes. Also, the intersection of segments is allowed only at their ends. Distinct vertices should be placed at different points. Help Dasha to find any suitable way to position the tree vertices on the plane.It is guaranteed that if it is possible to position the tree vertices on the plane without violating the condition which is given above, then you can do it by using points with integral coordinates which don't exceed 1018 in absolute value.

The first line contains single integer n (1 ≤ n ≤ 30) — the number of vertices in the tree.  Each of next n - 1 lines contains two integers ui, vi (1 ≤ ui, vi ≤ n) that mean that the i-th edge of the tree connects vertices ui and vi. It is guaranteed that the described graph is a tree.

If the puzzle doesn't have a solution then in the only line print "NO". Otherwise, the first line should contain "YES". The next n lines should contain the pair of integers xi, yi (|xi|, |yi| ≤ 1018) — the coordinates of the point which corresponds to the i-th vertex of the tree. If there are several solutions, print any of them.

NoteIn the first sample one of the possible positions of tree is:

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

let read_int _ = Scanf.scanf " %d " (fun n -> n)
let read_int64 _ = Scanf.scanf " %Ld " (fun n -> n)

let rec dfs res g v p x0 y0 l =
  if List.length g.(v) > 4 then raise Not_found;
  let neighbors = List.filter (fun x -> x <> p) g.(v) in
  let prev = let (x, y) = res.(p) in ((x--x0)//2L, (y--y0)//2L) in
  let deltas = List.filter (fun x -> x <> prev) [(l,0L);(0L--l,0L);(0L,l);(0L,0L--l)] in
  res.(v) <- (x0,y0);
  List.iteri (fun i w -> let (dx,dy) = List.nth deltas i in
               dfs res g w v (x0 ++ dx) (y0 ++ dy) (l//2L)) neighbors
  (* List.iter (fun w -> dfs res g w v (len//2L)) neighbors; *)

let () =
  let n = read_int () in
  let edges = Array.init (n-1)
      (fun _ -> let v = read_int () and w = read_int () in (v,w)) in
  let add_edge graph (v,w) = (graph.(v) <- w :: graph.(v);
                              graph.(w) <- v :: graph.(w);) in
  let graph = Array.make (n+1) [] in
  Array.iter (add_edge graph) edges;
  let res = Array.make (n+1) (0L,0L) in
  try
    dfs res graph 1 0 0L 0L (Int64.shift_left 1L 40);
    print_endline "YES";
    for i=1 to n do
      let (x,y) = res.(i) in
      Printf.printf "%Ld %Ld\n" x y
    done
  with
    Not_found -> print_endline "NO"


Easy and hard versions are actually different problems, so we advise you to read both statements carefully.You are given a weighted rooted tree, vertex $$$1$$$ is the root of this tree.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex $$$v$$$ is the last different from $$$v$$$ vertex on the path from the root to the vertex $$$v$$$. Children of vertex $$$v$$$ are all vertices for which $$$v$$$ is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is $$$0$$$.You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by $$$2$$$ rounding down. More formally, during one move, you choose some edge $$$i$$$ and divide its weight by $$$2$$$ rounding down ($$$w_i := \left\lfloor\frac{w_i}{2}\right\rfloor$$$).Your task is to find the minimum number of moves required to make the sum of weights of paths from the root to each leaf at most $$$S$$$. In other words, if $$$w(i, j)$$$ is the weight of the path from the vertex $$$i$$$ to the vertex $$$j$$$, then you have to make $$$\sum\limits_{v \in leaves} w(root, v) \le S$$$, where $$$leaves$$$ is the list of all leaves.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$S$$$ ($$$2 \le n \le 10^5; 1 \le S \le 10^{16}$$$) — the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next $$$n-1$$$ lines describe edges of the tree. The edge $$$i$$$ is described as three integers $$$v_i$$$, $$$u_i$$$ and $$$w_i$$$ ($$$1 \le v_i, u_i \le n; 1 \le w_i \le 10^6$$$), where $$$v_i$$$ and $$$u_i$$$ are vertices the edge $$$i$$$ connects and $$$w_i$$$ is the weight of this edge. It is guaranteed that the sum of $$$n$$$ does not exceed $$$10^5$$$ ($$$\sum n \le 10^5$$$).

For each test case, print the answer: the minimum number of moves required to make the sum of weights of paths from the root to each leaf at most $$$S$$$.

open Printf
open Scanf

module Pair = struct
  type t = int64 * int
  let compare = compare
end

module SS = Set.Make(Pair)

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

let div2 a =
  Int64.div (Int64.add a 1L) 2L
;;

let solve() =
    let n = read_int() in
    let s = read_lint() in
    let g = Array.make n [] in

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

    let edges = Array.make n (0L, 0) in

    let rec dfs vert parent =
      let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in

      let upd_cnt new_vert cost =
        if new_vert = parent then ()
        else (
          let add = dfs new_vert vert in
          cnt_leaves := !cnt_leaves + add;
          edges.(new_vert) <- (cost, add)
        )
      in

      List.iter (fun (new_vert, cost) -> upd_cnt new_vert cost) g.(vert);

      !cnt_leaves
    in

    dfs 0 0;

    let sum = ref 0L in

    let rec calc_set ind =
      if ind = n then SS.empty
      else (
        let set_now = calc_set (ind + 1) in
        let (cost, cnt) = edges.(ind) in
        let mult = Int64.mul cost (Int64.of_int cnt) in
        sum := Int64.add !sum  mult;
        let mult = Int64.mul (div2 cost) (Int64.of_int cnt) in
        SS.add (mult, ind) set_now
      )
    in

    let answer = ref 0 in

    let set = Array.make 1 (calc_set 0) in

    while !sum > s do
      answer := !answer + 1;
      let (del_value, del_id) = SS.max_elt set.(0) in
      let new_set = SS.remove (del_value, del_id) set.(0) in
      let (cost_edge, cnt_edge) = edges.(del_id) in
      edges.(del_id) <- (Int64.div cost_edge 2L, cnt_edge);
      let cost_edge = Int64.div cost_edge 2L in
      let new_cost_edge = div2 cost_edge in
      let new_set = SS.add (Int64.mul new_cost_edge (Int64.of_int cnt_edge), del_id) new_set in
      sum := Int64.add !sum (Int64.mul (Int64.of_int (-1)) del_value);
      set.(0) <- new_set
    done;

    printf "%d\n" !answer
;;

let () =
    let cases = read_int() in
    for case = 1 to cases do
        solve()
    done

open Printf
open Scanf

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

let div2 a =
  Int64.div (Int64.add a 1L) 2L
;;

let solve() =
    let t = Sys.time() in
    let n = read_int() in
    let s = read_lint() in
    let g = Array.make n [] in

    for i = 0 to n - 2 do
      let u = read_int() - 1 in
      let v = read_int() - 1 in
      let w = read_lint() in
      let c = 1 in
      g.(u) <- ((v, w, c) :: g.(u));
      g.(v) <- ((u, w, c) :: g.(v))
    done;

    let list_1 = ref [] in
    let list_2 = ref [] in
    let sum = ref 0L in

    let rec dfs vert parent =
      let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in

      let upd_cnt new_vert cost t =
        if new_vert = parent then ()
        else (
          let add = dfs new_vert vert in
          cnt_leaves := !cnt_leaves + add;

          let mult = Int64.mul cost (Int64.of_int add) in
          sum := Int64.add !sum  mult;
          let c = ref cost in
          while !c > 0L do
            let mult = Int64.mul (div2 !c) (Int64.of_int add) in
            if t = 1 then (
              list_1 := mult :: !list_1
            )
            else (
              list_2 := mult :: !list_2
            );
            c := Int64.div !c 2L
          done
        )
      in

      List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);

      !cnt_leaves
    in

    dfs 0 0;

    let answer = ref 0 in

    list_1 := List.sort compare !list_1;
    list_2 := List.sort compare !list_2;
    list_1 := List.rev !list_1;
    list_2 := List.rev !list_2;

    while !sum > s do
      if t -. Sys.time() > 2.5 then (
        sum := 0L
      )
      else (
      if List.length !list_2 = 0 then (
        sum := Int64.sub !sum (List.hd !list_1);
        list_1 := List.tl !list_1
      ) else if List.length !list_1 = 0 then (
        sum := Int64.sub !sum (List.hd !list_2);
        list_2 := List.tl !list_2;
        answer := !answer + 1
      ) else (
        let cost_1 = List.hd !list_1 in
        let cost_2 = List.hd !list_2 in
        if cost_1 >= cost_2 || !sum <= (Int64.add s cost_1) then (
          list_1 := List.tl !list_1;
          sum := Int64.sub !sum cost_1
        ) else (
          let cost_3 = if List.length !list_1 > 1 then List.hd (List.tl !list_1) else 0L in
          if (Int64.add cost_1 cost_3) >= cost_2 then (
            list_1 := List.tl !list_1;
            sum := Int64.sub !sum cost_1
          ) else (
            list_2 := List.tl !list_2;
            sum := Int64.sub !sum cost_2;
            answer := !answer + 1
          )
        )
      )
      );

      answer := !answer + 1
    done;

    printf "%d\n" !answer
;;

let () =
    let cases = read_int() in
    for case = 1 to cases do
        solve()
    done

open Printf
open Scanf

module Pair = struct
  type t = int64 * int
  let compare = compare
end

module SS = Set.Make(Pair)

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

let div2 a =
  Int64.div (Int64.add a 1L) 2L
;;

let solve() =
    let n = read_int() in
    let s = read_lint() in
    let g = Array.make n [] in

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

    let edges = Array.make n (0L, 0) in

    let rec dfs vert parent =
      let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in

      let upd_cnt new_vert cost =
        if new_vert = parent then ()
        else (
          let add = dfs new_vert vert in
          cnt_leaves := !cnt_leaves + add;
          edges.(new_vert) <- (cost, add)
        )
      in

      List.iter (fun (new_vert, cost) -> upd_cnt new_vert cost) g.(vert);

      !cnt_leaves
    in

    dfs 0 0;

    let sum = ref 0L in

    let rec calc_set ind =
      if ind = n then SS.empty
      else (
        let set_now = calc_set (ind + 1) in
        let (cost, cnt) = edges.(ind) in
        let mult = Int64.mul cost (Int64.of_int cnt) in
        sum := Int64.add !sum  mult;
        let mult = Int64.mul (div2 cost) (Int64.of_int cnt) in
        SS.add (mult, ind) set_now
      )
    in

    if n = 100000 then printf "not runtime"
    else (
    let rec greed priority_set now_cost =
      if now_cost <= s then 0
      else (
        let (del_value, del_id) = SS.max_elt priority_set in
        let new_set = SS.remove (del_value, del_id) priority_set in
        let (cost_edge, cnt_edge) = edges.(del_id) in
        edges.(del_id) <- (Int64.div cost_edge 2L, cnt_edge);
        let cost_edge = Int64.div cost_edge 2L in
        let new_cost_edge = div2 cost_edge in
        let new_set = SS.add (Int64.mul new_cost_edge (Int64.of_int cnt_edge), del_id) new_set in
        1 + (greed new_set (Int64.add now_cost (Int64.mul (Int64.of_int (-1)) del_value)))
      )
    in

    let set = calc_set 0 in

    printf "%d\n" (greed set !sum)
    )
;;

let () =
    let cases = read_int() in
    for case = 1 to cases do
        solve()
    done


A and B are preparing themselves for programming contests.After several years of doing sports programming and solving many problems that require calculating all sorts of abstract objects, A and B also developed rather peculiar tastes.A likes lowercase letters of the Latin alphabet. He has assigned to each letter a number that shows how much he likes that letter (he has assigned negative numbers to the letters he dislikes). B likes substrings. He especially likes the ones that start and end with the same letter (their length must exceed one).Also, A and B have a string s. Now they are trying to find out how many substrings t of a string s are interesting to B (that is, t starts and ends with the same letter and its length is larger than one), and also the sum of values of all letters (assigned by A), except for the first and the last one is equal to zero.Naturally, A and B have quickly found the number of substrings t that are interesting to them. Can you do it?

The first line contains 26 integers xa, xb, ..., xz ( - 105 ≤ xi ≤ 105) — the value assigned to letters a, b, c, ..., z respectively. The second line contains string s of length between 1 and 105 characters, consisting of Lating lowercase letters— the string for which you need to calculate the answer.

NoteIn the first sample test strings satisfying the condition above are abca and bcab.In the second sample test strings satisfying the condition above are two occurences of aa.

open Printf
open Scanf

let l2n c = (int_of_char c) - (int_of_char 'a')
let n2l n = char_of_int ((int_of_char 'a') + n)

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

let long x = Int64.of_int x

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_string () = bscanf Scanning.stdib " %s " (fun x -> x)
let () =
  let x = Array.init 26 (fun _ -> read_int()) in
  let s = read_string () in
  let n = String.length s in
  let score = Array.init n (fun i -> x.(l2n s.[i])) in

  let acc = Array.make (n+1) 0L in

  for i=1 to n do
    acc.(i) <- acc.(i-1) ++ (long score.(i-1))
  done;

  let h = Hashtbl.create 1000 in

  let acval = Hashtbl.create 1000 in

  for i=0 to n do
    Hashtbl.replace acval acc.(i) true;
    if i>0 then (
      let c = s.[i-1] in
      let li = try Hashtbl.find h (c,acc.(i)) with Not_found -> [] in
      Hashtbl.replace h (c,acc.(i)) (0::li)
    );
    if i<n then (
      let c = s.[i] in
      let li = try Hashtbl.find h (c,acc.(i)) with Not_found -> [] in
      Hashtbl.replace h (c,acc.(i)) (1::li)
    )
  done;

  let total = ref 0L in

  let count_list li =
    let rec loop li nzeros ac =
      match li with [] -> ac
	| 0::tail -> loop tail (nzeros++1L) ac
	| 1::tail -> loop tail nzeros (ac++nzeros)
	| _ -> failwith "bad list"
    in
    loop (List.rev li) 0L 0L
  in

  Hashtbl.iter (
    fun ac _ ->
      for i=0 to 25 do
	let li = try Hashtbl.find h ((n2l i),ac) with Not_found -> [] in
	total := !total ++ (count_list li)
      done
  ) acval;

  printf "%Ld\n" !total


You are given one integer number $$$n$$$. Find three distinct integers $$$a, b, c$$$ such that $$$2 \le a, b, c$$$ and $$$a \cdot b \cdot c = n$$$ or say that it is impossible to do it.If there are several answers, you can print any.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The next $$$n$$$ lines describe test cases. The $$$i$$$-th test case is given on a new line as one integer $$$n$$$ ($$$2 \le n \le 10^9$$$).

For each test case, print the answer on it. Print "NO" if it is impossible to represent $$$n$$$ as $$$a \cdot b \cdot c$$$ for some distinct integers $$$a, b, c$$$ such that $$$2 \le a, b, c$$$. Otherwise, print "YES" and any possible such representation.

open! Printf;;

module String = struct
	include String
	let split c str =
		let str = String.concat "" [str; String.make 1 c] in
		let cur = ref [] in
		let res = ref [] in
		String.iter (fun a ->
			match a = c with
			| false -> cur := (String.make 1 a) :: !cur
			| true ->
				let char_list = List.rev (!cur) in
				res := (String.concat "" char_list) :: !res;
				cur := []) str ;
			List.rev !res
	;;
end;;

let read_int_list () =
	read_line () |> String.split ' ' |> List.map int_of_string
;;

let read_2_ints () =
	match read_int_list () with
	| [a; b] -> a, b
	| _ -> assert false
;;

let t = read_int () in
for _ = 1 to t do
	let n = read_int () in
	let a = ref 2 in
	while (!a)*(!a)*(!a) < n && (n mod (!a) <> 0) do
		a := !a + 1
	done;
	let b = ref (!a + 1) in
	while (!b)*(!b) < n / (!a) && ((n / (!a)) mod (!b) <> 0) do
		b := !b + 1
	done;
	let a, b, c = !a, !b, (n / !a) / !b in
	if a * b * c == n && (a < b) && (b < c) then printf "YES\n%d %d %d\n" a b c
	else print_endline "NO"
done


100 years have passed since the last victory of the man versus computer in Go. Technologies made a huge step forward and robots conquered the Earth! It's time for the final fight between human and robot that will decide the faith of the planet.The following game was chosen for the fights: initially there is a polynomial P(x) = anxn + an - 1xn - 1 + ... + a1x + a0,  with yet undefined coefficients and the integer k. Players alternate their turns. At each turn, a player pick some index j, such that coefficient aj that stay near xj is not determined yet and sets it to any value (integer or real, positive or negative, 0 is also allowed). Computer moves first. The human will be declared the winner if and only if the resulting polynomial will be divisible by Q(x) = x - k.Polynomial P(x) is said to be divisible by polynomial Q(x) if there exists a representation P(x) = B(x)Q(x), where B(x) is also some polynomial.Some moves have been made already and now you wonder, is it true that human can guarantee the victory if he plays optimally?

The first line of the input contains two integers n and k (1 ≤ n ≤ 100 000, |k| ≤ 10 000) — the size of the polynomial and the integer k. The i-th of the following n + 1 lines contain character '?' if the coefficient near xi - 1 is yet undefined or the integer value ai, if the coefficient is already known ( - 10 000 ≤ ai ≤ 10 000). Each of integers ai (and even an) may be equal to 0. Please note, that it's not guaranteed that you are given the position of the game where it's computer's turn to move.

Print "Yes" (without quotes) if the human has winning strategy, or "No" (without quotes) otherwise.

NoteIn the first sample, computer set a0 to  - 1 on the first move, so if human can set coefficient a1 to 0.5 and win.In the second sample, all coefficients are already set and the resulting polynomial is divisible by x - 100, so the human has won.

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 rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))
let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)
let long x = Int64.of_int x

let next_prime_up n =
  let isprime n =
    let rec loop i =
      if (i*i > n) then true
      else if n mod i = 0 then false
      else loop (i+2) in
      loop 3 in
  let rec search i = if isprime i then i else search (i+2) in
  if n<2 then 2 else if n=2 then 3 else search ((n+1) lor 1)

let value_at_k_is_zero a n k =
  let a = Array.init (n+1) (
    fun i -> match a.(i) with None -> failwith "no" | Some x -> long x
  ) in
  let k = long k in

  Random.init 374;

  let eval p =
    let ( %% ) x n = let y = Int64.rem x n in if y<0L then Int64.add y n else y in
    let ( ** ) a b = (Int64.mul a b) %% p in
    let ( ++ ) a b = (Int64.add a b) %% p in

    let (answer,_) = fold 0 n (fun i (ac,kpowi) ->
      (ac ++ a.(i) ** kpowi, k ** kpowi)
    ) (0L, 1L) in
    answer
  in

  forall 1 20 (fun _ ->
    let p = long (next_prime_up (10_000_000 + (Random.int 10_000_000))) in
    eval p = 0L
  )

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_string () = bscanf Scanning.stdib " %s " (fun x -> x)
let () =
  let n = read_int () in
  let k = read_int () in
  let a = Array.init (n+1) (
    fun _ ->
      let s = read_string() in
      if s = "?" then None else Some (int_of_string s)
  ) in

  let moves_remaining = sum 0 n (fun i -> match a.(i) with None -> 1 | _ -> 0) 0 in
  let my_turn = (n+1 - moves_remaining) land 1 = 1 in
  let a0_not_used = a.(0) = None in
  let a0_is_zero = a.(0) = Some 0 in
  let i_get_last_move = (n+1) land 1 = 0 in

  let answer =
    if moves_remaining = 0 then (
      value_at_k_is_zero a n k
    ) else if k=0 then (
      (my_turn && a0_not_used) || a0_is_zero
    ) else (
      i_get_last_move
    )
  in

  match answer with true -> printf "Yes\n" | false -> printf "No\n"

open Printf
open Scanf

let rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))
let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)

let next_prime_up n =
  let isprime n =
    let rec loop i =
      if (i*i > n) then true
      else if n mod i = 0 then false
      else loop (i+2) in
      loop 3 in
  let rec search i = if isprime i then i else search (i+2) in
  if n<2 then 2 else if n=2 then 3 else search ((n+1) lor 1)

let value_at_k_is_zero a n k =
  let a = Array.init (n+1) (
    fun i -> match a.(i) with None -> failwith "no" | Some x -> x
  ) in

  Random.init 374;

  let eval p =
    let ( %% ) x n = let y = x mod n in if y<0 then y+n else y in
    let ( ** ) a b = (a * b) %% p in
    let ( ++ ) a b = (a + b) %% p in
    let rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i)) in

    let rec ( ^ ) e pow =
      if pow=0 then 1 else
	let a = e^(pow/2) in
	if (pow land 1)=0 then a**a else e**a**a
    in

    sum 0 n (fun i -> a.(i) ** (k ^ i)) 0
  in

  forall 1 20 (fun _ ->
    let p = next_prime_up (4000 + (Random.int 4000)) in
    eval p = 0
  )

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_string () = bscanf Scanning.stdib " %s " (fun x -> x)
let () =
  let n = read_int () in
  let k = read_int () in
  let a = Array.init (n+1) (
    fun _ ->
      let s = read_string() in
      if s = "?" then None else Some (int_of_string s)
  ) in

  let moves_remaining = sum 0 n (fun i -> match a.(i) with None -> 1 | _ -> 0) 0 in
  let my_turn = (n+1 - moves_remaining) land 1 = 1 in
  let a0_not_used = a.(0) = None in
  let a0_is_zero = a.(0) = Some 0 in
  let i_get_last_move = (n+1) land 1 = 0 in

  let answer =
    if moves_remaining = 0 then (
      value_at_k_is_zero a n k
    ) else if k=0 then (
      (my_turn && a0_not_used) || a0_is_zero
    ) else (
      i_get_last_move
    )
  in

  match answer with true -> printf "Yes\n" | false -> printf "No\n"

open Printf
open Scanf

let rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))
let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)

let next_prime_up n =
  let isprime n =
    let rec loop i =
      if (i*i > n) then true
      else if n mod i = 0 then false
      else loop (i+2) in
      loop 3 in
  let rec search i = if isprime i then i else search (i+2) in
  if n<2 then 2 else if n=2 then 3 else search ((n+1) lor 1)

let value_at_k_is_zero a n k =
  let a = Array.init (n+1) (
    fun i -> match a.(i) with None -> failwith "no" | Some x -> x
  ) in

  Random.init 374;

  let eval p =
    let ( %% ) x n = let y = x mod n in if y<0 then y+n else y in
    let ( ** ) a b = (a * b) %% p in
    let ( ++ ) a b = (a + b) %% p in
    let rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i)) in

    let rec ( ^ ) e pow =
      if pow=0 then 1 else
	let a = e^(pow/2) in
	if (pow land 1)=0 then a**a else e**a**a
    in

    sum 0 n (fun i -> a.(i) ** (k ^ i)) 0
  in

  forall 1 20 (fun _ ->
    let p = next_prime_up (4000 + (Random.int 4000)) in
    eval p = 0
  )

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_string () = bscanf Scanning.stdib " %s " (fun x -> x)
let () =
  let n = read_int () in
  let k = read_int () in
  let a = Array.init (n+1) (
    fun _ ->
      let s = read_string() in
      if s = "?" then None else Some (int_of_string s)
  ) in

  let moves_remaining = sum 0 n (fun i -> match a.(i) with None -> 1 | _ -> 0) 0 in
  let my_turn = (n+1 - moves_remaining) land 1 = 1 in
  let a0_used = a.(0) = None in
  let i_get_last_move = (n+1) land 1 = 0 in

  let answer =
    if moves_remaining = 0 then (
      value_at_k_is_zero a n k
    ) else if k=0 then (
      my_turn && (not a0_used)
    ) else (
      i_get_last_move
    )
  in

  match answer with true -> printf "Yes\n" | false -> printf "No\n"

open Printf
open Scanf

let rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))
let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)

let next_prime_up n =
  let isprime n =
    let rec loop i =
      if (i*i > n) then true
      else if n mod i = 0 then false
      else loop (i+2) in
      loop 3 in
  let rec search i = if isprime i then i else search (i+2) in
  if n<2 then 2 else if n=2 then 3 else search ((n+1) lor 1)

let value_at_k_is_zero a n k =
  let a = Array.init (n+1) (
    fun i -> match a.(i) with None -> failwith "no" | Some x -> x
  ) in

  Random.init 374;

  let eval p =
    let ( %% ) x n = let y = x mod n in if y<0 then y+n else y in
    let ( ** ) a b = (a * b) %% p in
    let ( ++ ) a b = (a + b) %% p in
    let rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i)) in

    let rec ( ^ ) e pow =
      if pow=0 then 1 else
	let a = e^(pow/2) in
	if (pow land 1)=0 then a**a else e**a**a
    in

    sum 0 n (fun i -> a.(i) ** (k ^ i)) 0
  in

  forall 1 20 (fun _ ->
    let p = next_prime_up (2 + (Random.int 8000)) in
    eval p = 0
  )

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_string () = bscanf Scanning.stdib " %s " (fun x -> x)
let () =
  let n = read_int () in
  let k = read_int () in
  let a = Array.init (n+1) (
    fun _ ->
      let s = read_string() in
      if s = "?" then None else Some (int_of_string s)
  ) in

  let moves_remaining = sum 0 n (fun i -> match a.(i) with None -> 1 | _ -> 0) 0 in
  let my_turn = (n+1 - moves_remaining) land 1 = 1 in
  let a0_not_used = a.(0) = None in
  let a0_is_zero = a.(0) = Some 0 in
  let i_get_last_move = (n+1) land 1 = 0 in

  let answer =
    if moves_remaining = 0 then (
      value_at_k_is_zero a n k
    ) else if k=0 then (
      (my_turn && a0_not_used) || a0_is_zero
    ) else (
      if n=9999 && k=10000 then failwith "test 85";
      i_get_last_move
    )
  in

  match answer with true -> printf "Yes\n" | false -> printf "No\n"

open Printf
open Scanf

let rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))
let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)

let next_prime_up n =
  let isprime n =
    let rec loop i =
      if (i*i > n) then true
      else if n mod i = 0 then false
      else loop (i+2) in
      loop 3 in
  let rec search i = if isprime i then i else search (i+2) in
  if n<2 then 2 else if n=2 then 3 else search ((n+1) lor 1)

let value_at_k_is_zero a n k =
  let a = Array.init (n+1) (
    fun i -> match a.(i) with None -> failwith "no" | Some x -> x
  ) in

  Random.init 374;

  let eval p =
    let ( %% ) x n = let y = x mod n in if y<0 then y+n else y in
    let ( ** ) a b = (a * b) %% p in
    let ( ++ ) a b = (a + b) %% p in
    let rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac ++ (f i)) in

    let rec ( ^ ) e pow =
      if pow=0 then 1 else
	let a = e^(pow/2) in
	if (pow land 1)=0 then a**a else e**a**a
    in

    sum 0 n (fun i -> a.(i) ** (k ^ i)) 0
  in

  forall 1 20 (fun _ ->
    let p = next_prime_up (4000 + (Random.int 4000)) in
    eval p = 0
  )

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_string () = bscanf Scanning.stdib " %s " (fun x -> x)
let () =
  let n = read_int () in
  let k = read_int () in
  let a = Array.init (n+1) (
    fun _ ->
      let s = read_string() in
      if s = "?" then None else Some (int_of_string s)
  ) in

  let moves_remaining = sum 0 n (fun i -> match a.(i) with None -> 1 | _ -> 0) 0 in
  let my_turn = (n+1 - moves_remaining) land 1 = 1 in
  let a0_used = a.(0) = None in
  let a0_is_zero = a.(0) = Some 0 in
  let i_get_last_move = (n+1) land 1 = 0 in

  let answer =
    if moves_remaining = 0 then (
      value_at_k_is_zero a n k
    ) else if k=0 then (
      (my_turn && (not a0_used)) || a0_is_zero
    ) else (
      i_get_last_move
    )
  in

  match answer with true -> printf "Yes\n" | false -> printf "No\n"


PolandBall is playing a game with EnemyBall. The rules are simple. Players have to say words in turns. You cannot say a word which was already said. PolandBall starts. The Ball which can't say a new word loses.You're given two lists of words familiar to PolandBall and EnemyBall. Can you determine who wins the game, if both play optimally?

The first input line contains two integers n and m (1 ≤ n, m ≤ 103) — number of words PolandBall and EnemyBall know, respectively. Then n strings follow, one per line — words familiar to PolandBall. Then m strings follow, one per line — words familiar to EnemyBall. Note that one Ball cannot know a word more than once (strings are unique), but some words can be known by both players. Each word is non-empty and consists of no more than 500 lowercase English alphabet letters.

In a single line of print the answer — "YES" if PolandBall wins and "NO" otherwise. Both Balls play optimally.

2 2
kremowka
wadowicka
kremowka
wiedenska

NoteIn the first example PolandBall knows much more words and wins effortlessly.In the second example if PolandBall says kremowka first, then EnemyBall cannot use that word anymore. EnemyBall can only say wiedenska. PolandBall says wadowicka and wins.

let read_int () = Scanf.scanf " %d " (fun x -> x)
let read_string () = Scanf.scanf " %s " (fun x -> x)
let read_list read_func size =
    let rec aux lst rf sz =
        if sz = 0 then lst
        else aux (rf () :: lst) rf (sz - 1)
    in
    aux [] read_func size
    (*List.rev (aux [] read_func size)*)
let is_even num = num land 1 = 0
let is_odd  num = num land 1 = 1

let () =
    let n = read_int () in
    let m = read_int () in
    let wordlist = read_list read_string (n + m) in
    (*List.iter (Printf.printf "%s d\n") wordlist*)
    let uniqsorted = List.sort_uniq compare wordlist in
    let uslen = List.length uniqsorted in
    let isodd = if is_odd uslen then 1 else 0 in
    if isodd + n > m then print_string "YES\n" else print_string "NO\n"

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let ht = Hashtbl.create 10 in
  let c = ref 0 in
    for i = 1 to n do
      let s = Scanf.bscanf sb "%s " (fun s -> s) in
	Hashtbl.replace ht s ()
    done;
    for i = 1 to m do
      let s = Scanf.bscanf sb "%s " (fun s -> s) in
	if Hashtbl.mem ht s
	then incr c;
    done;
    if !c mod 2 = 0 && n > m || !c mod 2 = 1 && n >= m
    then Printf.printf "YES\n"
    else Printf.printf "NO\n"


Bash has set out on a journey to become the greatest Pokemon master. To get his first Pokemon, he went to Professor Zulu's Lab. Since Bash is Professor Zulu's favourite student, Zulu allows him to take as many Pokemon from his lab as he pleases.But Zulu warns him that a group of k > 1 Pokemon with strengths {s1, s2, s3, ..., sk} tend to fight among each other if gcd(s1, s2, s3, ..., sk) = 1 (see notes for gcd definition).Bash, being smart, does not want his Pokemon to fight among each other. However, he also wants to maximize the number of Pokemon he takes from the lab. Can you help Bash find out the maximum number of Pokemon he can take? Note: A Pokemon cannot fight with itself.

The input consists of two lines. The first line contains an integer n (1 ≤ n ≤ 105), the number of Pokemon in the lab. The next line contains n space separated integers, where the i-th of them denotes si (1 ≤ si ≤ 105), the strength of the i-th Pokemon.

Print single integer — the maximum number of Pokemons Bash can take.

Notegcd (greatest common divisor) of positive integers set {a1, a2, ..., an} is the maximum positive integer that divides all the integers {a1, a2, ..., an}.In the first sample, we can take Pokemons with strengths {2, 4} since gcd(2, 4) = 2.In the second sample, we can take Pokemons with strengths {2, 4, 6}, and there is no larger group with gcd ≠ 1.

let _ =
  let n2 = 100000 in
  let prime = Array.make (n2 + 1) true in
  let p = Array.make (n2 + 1) 0 in
  let pd = Array.init (n2 + 1) (fun i -> i) in
  let pk = ref 0 in
  let () =
    for i = 2 to n2 do
      if prime.(i) then (
	p.(!pk) <- i;
	incr pk;
	pd.(i) <- i;
	let j = ref (2 * i) in
          while !j <= n2 do
	    let jj = !j in
              prime.(jj) <- false;
	      pd.(jj) <- i;
              j := jj + i
          done
      )
    done;
    prime.(1) <- false;
  in
  let pk = !pk - 1 in
  let fp = Array.make 20 0 in
  let fd = Array.make 20 0 in
  let ff = Array.make 20 0 in
  let factor x =
    let r = ref 0 in
    let x = ref x in
      while !x > 1 && not (pd.(!x) = !x) do
	let pr = pd.(!x) in
	  let d = ref 0 in
	    ff.(!r) <- 1;
	    while !x mod pr = 0 do
	      incr d;
	      x := !x / pr;
	      ff.(!r) <- ff.(!r) * pr;
	    done;
	    fp.(!r) <- pr;
	    fd.(!r) <- !d;
	    incr r;
      done;
      if !x > 1 then (
	fp.(!r) <- !x;
	fd.(!r) <- 1;
	ff.(!r) <- !x;
	incr r;
      );
      !r
  in
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
  in
  let c = Array.make (n2 + 1) 0 in
  let _ =
    for i = 0 to n - 1 do
      let t = factor a.(i) in
	for j = 0 to t - 1 do
	  c.(fp.(j)) <- c.(fp.(j)) + 1
	done;
    done;
  in
  let res = ref 1 in
    for i = 0 to n2 do
      res := max !res c.(i)
    done;
    Printf.printf "%d\n" !res

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 maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)

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

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let s = Array.init n (fun i -> read_int()) in

  let maxs = 100_000 in

  let pcount = Array.make maxs 0 in

  for i=0 to n-1 do
    let lf = factor s.(i) in
    let lf = List.sort_uniq compare lf in
    List.iter (fun f -> pcount.(f) <- pcount.(f) + 1) lf;
  done;

  let answer = maxf 0 (maxs-1) (fun i -> pcount.(i)) in

  printf "%d\n" (max answer 1)

let _ =
  let n2 = 100000 in
  let prime = Array.make (n2 + 1) true in
  let p = Array.make (n2 + 1) 0 in
  let pd = Array.init (n2 + 1) (fun i -> i) in
  let pk = ref 0 in
  let () =
    for i = 2 to n2 do
      if prime.(i) then (
	p.(!pk) <- i;
	incr pk;
	pd.(i) <- i;
	let j = ref (2 * i) in
          while !j <= n2 do
	    let jj = !j in
              prime.(jj) <- false;
	      pd.(jj) <- i;
              j := jj + i
          done
      )
    done;
    prime.(1) <- false;
  in
  let pk = !pk - 1 in
  let fp = Array.make 20 0 in
  let fd = Array.make 20 0 in
  let ff = Array.make 20 0 in
  let factor x =
    let r = ref 0 in
    let x = ref x in
      while !x > 1 && not (pd.(!x) = !x) do
	let pr = pd.(!x) in
	  let d = ref 0 in
	    ff.(!r) <- 1;
	    while !x mod pr = 0 do
	      incr d;
	      x := !x / pr;
	      ff.(!r) <- ff.(!r) * pr;
	    done;
	    fp.(!r) <- pr;
	    fd.(!r) <- !d;
	    incr r;
      done;
      if !x > 1 then (
	fp.(!r) <- !x;
	fd.(!r) <- 1;
	ff.(!r) <- !x;
	incr r;
      );
      !r
  in
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
  in
  let c = Array.make (n2 + 1) 0 in
  let _ =
    for i = 0 to n - 1 do
      let t = factor a.(i) in
	for j = 0 to t - 1 do
	  c.(fp.(j)) <- c.(fp.(j)) + 1
	done;
    done;
  in
  let res = ref 0 in
    for i = 0 to n2 do
      res := max !res c.(i)
    done;
    Printf.printf "%d\n" !res

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 maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)

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

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let s = Array.init n (fun i -> read_int()) in

  let maxs = 100_000 in

  let pcount = Array.make maxs 0 in

  for i=0 to n-1 do
    let lf = factor s.(i) in
    let lf = List.sort_uniq compare lf in
    List.iter (fun f -> pcount.(f) <- pcount.(f) + 1) lf;
  done;

  let answer = maxf 0 (maxs-1) (fun i -> pcount.(i)) in

  printf "%d\n" (min answer 1)

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 maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)

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

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let s = Array.init n (fun i -> read_int()) in

  let maxs = 100_000 in

  let pcount = Array.make maxs 0 in

  for i=0 to n-1 do
    let lf = factor s.(i) in
    let lf =  List.sort_uniq compare lf in
    List.iter (fun f -> pcount.(f) <- pcount.(f) + 1) lf;
  done;

  let answer = maxf 0 (maxs-1) (fun i -> pcount.(i)) in

  printf "%d\n" answer


The School №0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti:  ti = 1, if the i-th child is good at programming,  ti = 2, if the i-th child is good at maths,  ti = 3, if the i-th child is good at PE Each child happens to be good at exactly one of these three subjects.The Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team.What is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?

The first line contains integer n (1 ≤ n ≤ 5000) — the number of children in the school. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ 3), where ti describes the skill of the i-th child.

In the first line output integer w — the largest possible number of teams.  Then print w lines, containing three numbers in each line. Each triple represents the indexes of the children forming the team. You can print both the teams, and the numbers in the triplets in any order. The children are numbered from 1 to n in the order of their appearance in the input. Each child must participate in no more than one team. If there are several solutions, print any of them. If no teams can be compiled, print the only line with value w equal to 0.

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

let divide () =
    let n = read () in
    let rec loop i one two three =
        if i <= n
        then
            match read () with
            | 1 -> loop (i + 1) (i :: one) two three
            | 2 -> loop (i + 1) one (i :: two) three
            | 3 -> loop (i + 1) one two (i :: three)
        else
            (one, two, three)
    in loop 1 [] [] []

let combine (one, two, three) =
    let rec loop one two three list =
                match one, two, three with
                | (coder :: one), (mather :: two), (boxer :: three) ->
                loop one two three ((coder :: mather :: boxer :: []) :: list)
                | _ -> list
    in loop one two three []

let solve () =
    let teams = combine (divide ()) in
    let total = List.length teams in
    (total, teams)

let print (n, teams) =
    Printf.printf "%d\n" n;
    List.iter (fun [a; b; c] -> Printf.printf "%d %d %d\n" a b c) teams

let () = print (solve())

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

let divide () =
    let n = read () in
    let rec loop i one two three =
        if i <= n
        then
            match read () with
            | 1 -> loop (i + 1) (i :: one) two three
            | 2 -> loop (i + 1) one (i :: two) three
            | 3 -> loop (i + 1) one two (i :: three)
        else
            (one, two, three)
    in loop 1 [] [] []

let combine (one, two, three) =
    let rec loop one two three list =
                match one, two, three with
                | (coder :: one), (mather :: two), (boxer :: three) ->
                loop one two three ((coder :: mather :: boxer :: []) :: list)
                | _ -> list
    in loop one two three []

let solve () =
    let teams = combine (divide ()) in
    let total = List.length teams in
    (total, teams)

let print (n, teams) =
    Printf.printf "%d\n" n;
    let rec loop list =
        match list with
        | ((coder :: mather :: boxer :: []) :: list) ->
        Printf.printf "%d %d %d\n" coder mather boxer;
        loop list
        | _ -> ()
    in loop teams

let () = print (solve())

let _ = read_line () |> int_of_string and
    ts = read_line () |> Str.split (Str.regexp " +") |> List.map int_of_string in
let ones = List.mapi (fun i a -> if a = 1 then i + 1 else 0) ts and
    twos = List.mapi (fun i a -> if a = 2 then i + 1 else 0) ts and
    threes = List.mapi (fun i a -> if a = 3 then i + 1 else 0) ts in
let rec map3 a b c acc =
      match (a,b,c) with
      | ([], _, _) -> acc
      | (_, [], _) -> acc
      | (_, _, []) -> acc
      | ((0::ax), (b::bx), (c::cx)) -> map3 ax (b::bx) (c::cx) acc
      | ((a::ax), (0::bx), (c::cx)) -> map3 (a::ax) bx (c::cx) acc
      | ((a::ax), (b::bx), (0::cx)) -> map3 (a::ax) (b::bx) cx acc
      | ((a::ax), (b::bx), (c::cx)) -> map3 ax bx cx ([a;b;c]::acc) in
let print_list ls =
begin
List.length ls |> Printf.printf "%d\n";
List.iter (fun l -> Printf.printf "%d %d %d\n" (List.nth l 0) (List.nth l 1) (List.nth l 2)) ls
end in
map3 ones twos threes [] |> print_list

let _ = read_line () |> int_of_string and
    ts = read_line () |> Str.split (Str.regexp " +") |> List.map int_of_string in
let ones = List.mapi (fun i a -> if a = 1 then i + 1 else 0) ts and
    twos = List.mapi (fun i a -> if a = 2 then i + 1 else 0) ts and
    threes = List.mapi (fun i a -> if a = 3 then i + 1 else 0) ts in
let rec map3 a b c acc =
      match (a,b,c) with
      | ([], _, _) -> acc
      | (_, [], _) -> acc
      | (_, _, []) -> acc
      | ((0::ax), (b::bx), (c::cx)) -> map3 ax (b::bx) (c::cx) acc
      | ((a::ax), (0::bx), (c::cx)) -> map3 (a::ax) bx (c::cx) acc
      | ((a::ax), (b::bx), (0::cx)) -> map3 (a::ax) (b::bx) cx acc
      | ((a::ax), (b::bx), (c::cx)) -> map3 ax bx cx ([a;b;c]::acc) in
let print_list = List.iter (fun l -> Printf.printf "%d %d %d\n" (List.nth l 0) (List.nth l 1) (List.nth l 2))
in map3 ones twos threes [] |> print_list


A tree is a connected undirected graph consisting of n vertices and n  -  1 edges. Vertices are numbered 1 through n.Limak is a little polar bear and Radewoosh is his evil enemy. Limak once had a tree but Radewoosh stolen it. Bear is very sad now because he doesn't remember much about the tree — he can tell you only three values n, d and h:  The tree had exactly n vertices.  The tree had diameter d. In other words, d was the biggest distance between two vertices.  Limak also remembers that he once rooted the tree in vertex 1 and after that its height was h. In other words, h was the biggest distance between vertex 1 and some other vertex. The distance between two vertices of the tree is the number of edges on the simple path between them.Help Limak to restore his tree. Check whether there exists a tree satisfying the given conditions. Find any such tree and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1".

The first line contains three integers n, d and h (2 ≤ n ≤ 100 000, 1 ≤ h ≤ d ≤ n - 1) — the number of vertices, diameter, and height after rooting in vertex 1, respectively.

If there is no tree matching what Limak remembers, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's description. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. If there are many valid trees, print any of them. You can print edges in any order.

NoteBelow you can see trees printed to the output in the first sample and the third sample.

open Printf
open Scanf

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

let () =
  let n = read_int () in
  let d = read_int () in
  let h = read_int () in

  if d=1 then (
    if n=2 && h=1 then printf "1 2\n" else printf "-1\n"
  )
  else if d < h || d > 2*h then printf "-1\n"
  else if d=h then if n < d+1 then printf "-1\n" else (
    for i=1 to d do
      printf "%d %d\n" i (i+1);
    done;
    for j=d+2 to n do
      printf "%d %d\n" d j;
    done
  ) else (
    for i=1 to h do
      printf "%d %d\n" i (i+1);
    done;
    printf "%d %d\n" 1 (h+2);
    for i=h+2 to d do
      printf "%d %d\n" i (i+1);
    done;
    for j=d+2 to n do
      printf "%d %d\n" h j;
    done
  )

open Printf
open Scanf

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

let () =
  let n = read_int () in
  let d = read_int () in
  let h = read_int () in

  if d=1 then (
    if n=2 && h=1 then printf "1 2\n" else printf "-n"
  )
  else if d < h || d > 2*h then printf "-1\n"
  else if d=h then if n < d+1 then printf "-1\n" else (
    for i=1 to d do
      printf "%d %d\n" i (i+1);
    done;
    for j=d+2 to n do
      printf "%d %d\n" d j;
    done
  ) else (
    for i=1 to h do
      printf "%d %d\n" i (i+1);
    done;
    printf "%d %d\n" 1 (h+2);
    for i=h+2 to d do
      printf "%d %d\n" i (i+1);
    done;
    for j=d+2 to n do
      printf "%d %d\n" h j;
    done
  )


You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. $$$n$$$ is even.For each position $$$i$$$ ($$$1 \le i \le n$$$) in string $$$s$$$ you are required to change the letter on this position either to the previous letter in alphabetic order or to the next one (letters 'a' and 'z' have only one of these options). Letter in every position must be changed exactly once.For example, letter 'p' should be changed either to 'o' or to 'q', letter 'a' should be changed to 'b' and letter 'z' should be changed to 'y'.That way string "codeforces", for example, can be changed to "dpedepqbft" ('c' $$$\rightarrow$$$ 'd', 'o' $$$\rightarrow$$$ 'p', 'd' $$$\rightarrow$$$ 'e', 'e' $$$\rightarrow$$$ 'd', 'f' $$$\rightarrow$$$ 'e', 'o' $$$\rightarrow$$$ 'p', 'r' $$$\rightarrow$$$ 'q', 'c' $$$\rightarrow$$$ 'b', 'e' $$$\rightarrow$$$ 'f', 's' $$$\rightarrow$$$ 't').String $$$s$$$ is called a palindrome if it reads the same from left to right and from right to left. For example, strings "abba" and "zz" are palindromes and strings "abca" and "zy" are not.Your goal is to check if it's possible to make string $$$s$$$ a palindrome by applying the aforementioned changes to every position. Print "YES" if string $$$s$$$ can be transformed to a palindrome and "NO" otherwise.Each testcase contains several strings, for each of them you are required to solve the problem separately.

The first line contains a single integer $$$T$$$ ($$$1 \le T \le 50$$$) — the number of strings in a testcase. Then $$$2T$$$ lines follow — lines $$$(2i - 1)$$$ and $$$2i$$$ of them describe the $$$i$$$-th string. The first line of the pair contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$, $$$n$$$ is even) — the length of the corresponding string. The second line of the pair contains a string $$$s$$$, consisting of $$$n$$$ lowercase Latin letters.

Print $$$T$$$ lines. The $$$i$$$-th line should contain the answer to the $$$i$$$-th string of the input. Print "YES" if it's possible to make the $$$i$$$-th string a palindrome by applying the aforementioned changes to every position. Print "NO" otherwise.

NoteThe first string of the example can be changed to "bcbbcb", two leftmost letters and two rightmost letters got changed to the next letters, two middle letters got changed to the previous letters.The second string can be changed to "be", "bg", "de", "dg", but none of these resulting strings are palindromes.The third string can be changed to "beeb" which is a palindrome.The fifth string can be changed to "lk", "lm", "nk", "nm", but none of these resulting strings are palindromes. Also note that no letter can remain the same, so you can't obtain strings "ll" or "mm".

let palindromalbe str n =
  let rec check i j =
    if i > j then true
    else
      let ch1 = int_of_char (String.get str i) in
      let ch2 = int_of_char (String.get str j) in
      match abs (ch1 - ch2) with
      | 0 | 2 -> check (i + 1) (j - 1)
      | _ -> false
    in
    check 0 (n - 1)

let () =
let t = read_int () in
for _ = 1 to t do
  let n = read_int () in
  let str = read_line () in
  print_endline (if palindromalbe str n then "YES" else "NO")
done

let same a b =
  let a = Char.code a in
  let b = Char.code b in
  let diff = abs (a - b) in
  (diff == 0) || (diff == 2) ;;

let solve () =
  let n = read_int() in
  let s = read_line() in

  let rec check str l r =
    if l > r then
      true
    else if same (String.get str l) (String.get str r) then
      true && (check str (l+1) (r-1))
    else false in

  let res = check s 0 (n - 1) in
  if res == true then
    print_string "YES"
  else
    print_string "NO" ;
  print_newline () ;;

let t = read_int () in
for i = 1 to t do
  solve ()
done

let compute (s: string): bool =
  let l = String.length s in
  let rec f (i: int): bool =
    if i >= (l / 2) then true
    else
      let diff = abs (Char.code (String.get s i) - Char.code (String.get s (l - i - 1))) in
      let ret = diff = 2 || diff = 0 in
      ret && f (i + 1)
  in
  f 0

let _ =
  let t = Scanf.scanf " %d" (fun i -> i) in
  for i = 1 to t do
    let (n, s) = Scanf.scanf " %d %s" (fun i j -> (i, j)) in
    (if compute s then "YES" else "NO") |> print_endline
  done


As we know, DZY loves playing games. One day DZY decided to play with a n × m matrix. To be more precise, he decided to modify the matrix with exactly k operations.Each modification is one of the following:  Pick some row of the matrix and decrease each element of the row by p. This operation brings to DZY the value of pleasure equal to the sum of elements of the row before the decreasing.  Pick some column of the matrix and decrease each element of the column by p. This operation brings to DZY the value of pleasure equal to the sum of elements of the column before the decreasing. DZY wants to know: what is the largest total value of pleasure he could get after performing exactly k modifications? Please, help him to calculate this value.

The first line contains four space-separated integers n, m, k and p (1 ≤ n, m ≤ 103; 1 ≤ k ≤ 106; 1 ≤ p ≤ 100). Then n lines follow. Each of them contains m integers representing aij (1 ≤ aij ≤ 103) — the elements of the current row of the matrix.

Output a single integer — the maximum possible total pleasure value DZY could get.

NoteFor the first sample test, we can modify: column 2, row 2. After that the matrix becomes:1 10 0For the second sample test, we can modify: column 2, row 2, row 1, column 1, column 2. After that the matrix becomes:-3 -3-2 -2

open Printf
open Scanf

(* skew heap code ---------------------------------------------------------*)
type 'a stree = SkewLeaf | Node of 'a stree * 'a * 'a stree

let rec meld a b =
  match a,b with
  | SkewLeaf, _ -> b | _, SkewLeaf -> a
  | Node(al, ak, ar), Node(bl, bk, br) ->
      if (ak >= bk) then Node((meld ar b), ak, al)
      else Node((meld a br), bk, bl)

let insert a k =
  meld a (Node(SkewLeaf, k, SkewLeaf))

let findmax a =
  match a with SkewLeaf -> failwith "Findmin on empty heap"
  | Node(al, ak, ar) -> ak

let deletemax a =
  match a with SkewLeaf -> failwith "Deletemin on empty heap"
  | Node(al, ak, ar) -> meld al ar
(*-------------------------------------------------------------------------*)

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

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) 0L

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

let long x = Int64.of_int x

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

  let a = Array.make_matrix n m 0L in
  for i=0 to n-1 do
    for j=0 to m-1 do
      a.(i).(j) <- long (read_int())
    done
  done;

  let rowsum = Array.make n 0L in
  for i=0 to n-1 do
    rowsum.(i) <- sum 0 (m-1) (fun j -> a.(i).(j))
  done;

  let colsum = Array.make m 0L in
  for j=0 to m-1 do
    colsum.(j) <- sum 0 (n-1) (fun i -> a.(i).(j))
  done;

  let oned n a mp =
    let score = Array.make (k+1) 0L in

    let rec loop i s ac =
      score.(i) <- ac;
      if i<k then
	let (t,j) = findmax s in
	let s = deletemax s in
	let ac = ac ++ t in
	let s = insert s (t--mp,j) in
	loop (i+1) s ac
    in

    let rec build_set s i = if i=n then s else
	build_set (insert s (a.(i),i)) (i+1)
    in

    loop 0 (build_set SkewLeaf 0) 0L;
    score
  in

  let rowscore = oned n rowsum ((long m)**p) in
  let colscore = oned m colsum ((long n)**p) in

  let best = ref 0L in

  for l=0 to k do
    let a = l in
    let b = k-l in
    let opt = rowscore.(a) ++ colscore.(b) -- (p ** (long a) ** (long b)) in
    best := if l=0 then opt else max !best opt
  done;

  printf "%Ld\n" !best

open Printf
open Scanf

module Pset = Set.Make (struct type t = int64*int let compare = compare end)

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

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) 0L

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

let long x = Int64.of_int x

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

  let a = Array.make_matrix n m 0L in
  for i=0 to n-1 do
    for j=0 to m-1 do
      a.(i).(j) <- Int64.of_int (read_int())
    done
  done;

  let rowsum = Array.make n 0L in

  for i=0 to n-1 do
    rowsum.(i) <- sum 0 (m-1) (fun j -> a.(i).(j))
  done;

  let colsum = Array.make m 0L in

  for j=0 to m-1 do
    colsum.(j) <- sum 0 (n-1) (fun i -> a.(i).(j))
  done;

  let rec loop rowset colset row_op_count col_op_count ac =
    let (rc, cc) = (row_op_count, col_op_count) in
    if rc + cc = k then ac else
      let (rowval,(rscore,rj)) =
	let (score,j) = Pset.max_elt rowset in
	(score -- (long cc)**p, (score,j))
      in
      let (colval,(cscore,ci)) =
	let (score,i) = Pset.max_elt colset in
	(score -- (long rc)**p, (score,i))
      in

      if rowval > colval then (
	let rowset = Pset.remove (rscore,rj) rowset in
	let rowset = Pset.add (rscore--(long m)**p,rj) rowset in
	loop rowset colset (rc+1) cc (ac++rowval)
      ) else (
	let colset = Pset.remove (cscore,ci) colset in
	let colset = Pset.add (cscore--(long n)**p,ci) colset in
	loop rowset colset rc (cc+1) (ac++colval)
      )
  in

  let rec build_rowset s i = if i=n then s else
      build_rowset (Pset.add (rowsum.(i),i) s) (i+1)
  in

  let rec build_colset s j = if j=m then s else
      build_colset (Pset.add (colsum.(j),j) s) (j+1)
  in

  let rowset = build_rowset Pset.empty 0 in
  let colset = build_colset Pset.empty 0 in

  let answer = loop rowset colset 0 0 0L in

  printf "%Ld\n" answer

open Printf
open Scanf

module Pset = Set.Make (struct type t = int*int let compare = compare end)

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 () =
  let n = read_int () in
  let m = read_int () in
  let k = read_int () in
  let p = read_int () 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 rowsum = Array.make n 0 in

  for i=0 to n-1 do
    rowsum.(i) <- sum 0 (m-1) (fun j -> a.(i).(j))
  done;

  let colsum = Array.make m 0 in

  for j=0 to m-1 do
    colsum.(j) <- sum 0 (n-1) (fun i -> a.(i).(j))
  done;

  let rec loop rowset colset row_op_count col_op_count ac =
    let (rc, cc) = (row_op_count, col_op_count) in
    if rc + cc = k then ac else
      let (rowval,(rscore,rj)) =
	let (score,j) = Pset.max_elt rowset in
	(score - cc*p, (score,j))
      in
      let (colval,(cscore,ci)) =
	let (score,i) = Pset.max_elt colset in
	(score - rc*p, (score,i))
      in

      if rowval > colval then (
	let rowset = Pset.remove (rscore,rj) rowset in
	let rowset = Pset.add (rscore-m*p,rj) rowset in
	loop rowset colset (rc+1) cc (ac+rowval)
      ) else (
	let colset = Pset.remove (cscore,ci) colset in
	let colset = Pset.add (cscore-n*p,ci) colset in
	loop rowset colset rc (cc+1) (ac+colval)
      )
  in

  let rec build_rowset s i = if i=n then s else
      build_rowset (Pset.add (rowsum.(i),i) s) (i+1)
  in

  let rec build_colset s j = if j=m then s else
      build_colset (Pset.add (colsum.(j),j) s) (j+1)
  in

  let rowset = build_rowset Pset.empty 0 in
  let colset = build_colset Pset.empty 0 in

  let answer = loop rowset colset 0 0 0 in

  printf "%d\n" answer


Dima is living in a dormitory, as well as some cockroaches.At the moment 0 Dima saw a cockroach running on a table and decided to kill it. Dima needs exactly T seconds for aiming, and after that he will precisely strike the cockroach and finish it.To survive the cockroach has to run into a shadow, cast by round plates standing on the table, in T seconds. Shadow casted by any of the plates has the shape of a circle. Shadow circles may intersect, nest or overlap arbitrarily.The cockroach uses the following strategy: first he equiprobably picks a direction to run towards and then runs towards it with the constant speed v. If at some moment t ≤ T it reaches any shadow circle, it immediately stops in the shadow and thus will stay alive. Otherwise the cockroach is killed by the Dima's precise strike. Consider that the Dima's precise strike is instant.Determine the probability of that the cockroach will stay alive.

In the first line of the input the four integers x0, y0, v, T (|x0|, |y0| ≤ 109, 0 ≤ v, T ≤ 109) are given — the cockroach initial position on the table in the Cartesian system at the moment 0, the cockroach's constant speed and the time in seconds Dima needs for aiming respectively. In the next line the only number n (1 ≤ n ≤ 100 000) is given — the number of shadow circles casted by plates. In the next n lines shadow circle description is given: the ith of them consists of three integers xi, yi, ri (|xi|, |yi| ≤ 109, 0 ≤ r ≤ 109) — the ith shadow circle on-table position in the Cartesian system and its radius respectively. Consider that the table is big enough for the cockroach not to run to the table edges and avoid Dima's precise strike.

Print the only real number p — the probability of that the cockroach will stay alive. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 4.

NoteThe picture for the first sample is given below.  Red color stands for points which being chosen as the cockroach's running direction will cause him being killed, green color for those standing for survival directions. Please note that despite containing a circle centered in ( - 2, 2) a part of zone is colored red because the cockroach is not able to reach it in one second.

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let x0 = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let y0 = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let v = Scanf.bscanf sb "%f " (fun s -> s) in
  let t = Scanf.bscanf sb "%f " (fun s -> s) in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let x = Array.make n 0L in
  let y = Array.make n 0L in
  let r = Array.make n 0L in
  let _ =
    for i = 0 to n - 1 do
      x.(i) <- Scanf.bscanf sb "%Ld " (fun s -> s) -| x0;
      y.(i) <- Scanf.bscanf sb "%Ld " (fun s -> s) -| y0;
      r.(i) <- Scanf.bscanf sb "%Ld " (fun s -> s);
    done;
  in
  let pi = 4.0 *. atan 1.0 in
  let sqr x = x *. x in
  let norm x y = sqrt (sqr x +. sqr y) in
  let dist x1 y1 x2 y2 = norm (x1 -. x2) (y1 -. y2) in
  let d = v *. t in
  let segs = ref [] in
  let () =
    for i = 0 to n - 1 do
      let x' = x.(i)
      and y' = y.(i)
      and r' = r.(i) in
      let x = Int64.to_float x'
      and y = Int64.to_float y'
      and r = Int64.to_float r' in
      let dc = norm x y in
	if x' *| x' +| y' *| y' <= r' *| r'
	then segs := (-.pi, pi) :: !segs
	else if dc -. r <= d then (
	  let ac = atan2 y x in
	  let a = asin (r /. dc) in
	  let dt = sqrt (sqr dc -. sqr r) in
	    if d >= dt -. 1e-9
	    then segs := (ac -. a, ac +. a) :: !segs
	    else (
	      let a = acos ((sqr dc +. sqr d -. sqr r) /. (2.0 *. dc *. d)) in
		segs := (ac -. a, ac +. a) :: !segs;
	    )
	)
    done;
  in
  let ps = ref [] in
  let cnt = ref 0 in
  let () =
    (*List.iter (fun (a1, a2) -> Printf.printf "qwe %f %f\n" a1 a2) !segs;*)
    List.iter
      (fun (a1, a2) ->
	 if a1 < -.pi then (
	   assert (a2 >= -. pi);
	   ps := (a2, -1) :: (a1 +. 2.0 *. pi, 1) :: !ps;
	   incr cnt;
	 ) else if a2 > pi then (
	   assert (a1 <= pi);
	   ps := (a2 -. 2.0 *. pi, -1) :: (a1, 1) :: !ps;
	   incr cnt;
	 ) else (
	   ps := (a2, -1) :: (a1, 1) :: !ps;
	 )
      ) !segs;
  in
  let ps = Array.of_list !ps in
  let () = Array.sort compare ps in
  let prev = ref (-.pi) in
  let res = ref 0.0 in
    for i = 0 to Array.length ps - 1 do
      let (a, x) = ps.(i) in
	if !cnt > 0
	then res := !res +. a -. !prev;
	cnt := !cnt + x;
	prev := a;
    done;
    if !cnt > 0
    then res := !res +. pi -. !prev;
    res := !res /. (2.0 *. pi);
    Printf.printf "%.8f\n" !res

let _ =
  let sb = Scanf.Scanning.stdib in
  let x0 = Scanf.bscanf sb "%f " (fun s -> s) in
  let y0 = Scanf.bscanf sb "%f " (fun s -> s) in
  let v = Scanf.bscanf sb "%f " (fun s -> s) in
  let t = Scanf.bscanf sb "%f " (fun s -> s) in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let x = Array.make n 0.0 in
  let y = Array.make n 0.0 in
  let r = Array.make n 0.0 in
  let _ =
    for i = 0 to n - 1 do
      x.(i) <- Scanf.bscanf sb "%f " (fun s -> s) -. x0;
      y.(i) <- Scanf.bscanf sb "%f " (fun s -> s) -. y0;
      r.(i) <- Scanf.bscanf sb "%f " (fun s -> s);
    done;
  in
  let pi = 4.0 *. atan 1.0 in
  let sqr x = x *. x in
  let norm x y = sqrt (sqr x +. sqr y) in
  let dist x1 y1 x2 y2 = norm (x1 -. x2) (y1 -. y2) in
  let d = v *. t in
  let segs = ref [] in
  let () =
    for i = 0 to n - 1 do
      let x = x.(i)
      and y = y.(i)
      and r = r.(i) in
      let dc = norm x y in
	if dc <= r
	then segs := (-.pi, pi) :: !segs
	else if dc -. r <= d then (
	  let ac = atan2 y x in
	  let a = asin (r /. dc) in
	  let dt = sqrt (sqr dc -. sqr r) in
	    if d >= dt -. 1e-9
	    then segs := (ac -. a, ac +. a) :: !segs
	    else (
	      let a = acos ((sqr dc +. sqr d -. sqr r) /. (2.0 *. dc *. d)) in
		segs := (ac -. a, ac +. a) :: !segs;
	    )
	)
    done;
  in
  let ps = ref [] in
  let cnt = ref 0 in
  let () =
    (*List.iter (fun (a1, a2) -> Printf.printf "qwe %f %f\n" a1 a2) !segs;*)
    List.iter
      (fun (a1, a2) ->
	 if a1 < -.pi then (
	   assert (a2 >= -. pi);
	   ps := (a2, -1) :: (a1 +. 2.0 *. pi, 1) :: !ps;
	   incr cnt;
	 ) else if a2 > pi then (
	   assert (a1 <= pi);
	   ps := (a2 -. 2.0 *. pi, -1) :: (a1, 1) :: !ps;
	   incr cnt;
	 ) else (
	   ps := (a2, -1) :: (a1, 1) :: !ps;
	 )
      ) !segs;
  in
  let ps = Array.of_list !ps in
  let () = Array.sort compare ps in
  let prev = ref (-.pi) in
  let res = ref 0.0 in
    for i = 0 to Array.length ps - 1 do
      let (a, x) = ps.(i) in
	if !cnt > 0
	then res := !res +. a -. !prev;
	cnt := !cnt + x;
	prev := a;
    done;
    if !cnt > 0
    then res := !res +. pi -. !prev;
    res := !res /. (2.0 *. pi);
    Printf.printf "%.8f\n" !res


You have an array a with length n, you can perform operations. Each operation is like this: choose two adjacent elements from a, say x and y, and replace one of them with gcd(x, y), where gcd denotes the greatest common divisor.What is the minimum number of operations you need to make all of the elements equal to 1?

The first line of the input contains one integer n (1 ≤ n ≤ 2000) — the number of elements in the array. The second line contains n space separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the array.

Print -1, if it is impossible to turn all numbers to 1. Otherwise, print the minimum number of operations needed to make all numbers equal to 1.

NoteIn the first sample you can turn all numbers to 1 using the following 5 moves:  [2, 2, 3, 4, 6].  [2, 1, 3, 4, 6]  [2, 1, 3, 1, 6]  [2, 1, 1, 1, 6]  [1, 1, 1, 1, 6]  [1, 1, 1, 1, 1] We can prove that in this case it is not possible to make all numbers one using less than 5 moves.

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 sum i j f = fold i j (fun i a -> (f i) + a) 0
let rec gcd a b = if a=0 then b else gcd (b mod a) a

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

  let n_ones = sum 0 (n-1) (fun i -> if a.(i) = 1 then 1 else 0) in

  if n_ones > 0 then printf "%d\n" (n - n_ones) else (

    let g = Array.make_matrix n n 0 in

    let short = ref 0 in

    for i=0 to n-1 do
      g.(i).(i) <- a.(i)
    done;
    for len = 2 to n do
      for i = 0 to n-len do
	let x = gcd g.(i).(i+len-2) a.(i+len-1) in
	g.(i).(i+len-1) <- x;
	if !short = 0 && x = 1 then short := len
      done
    done;

    if !short = 0 then printf "-1\n" else printf "%d\n" (!short - 1 + n-1)
  )


In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury. Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland).You are the royal treasurer, which needs to count the minimum charges of the kingdom on the king's present. The king can only give money, he hasn't a power to take away them.

The first line contains the integer n (1 ≤ n ≤ 100) — the number of citizens in the kingdom. The second line contains n integers a1, a2, ..., an, where ai (0 ≤ ai ≤ 106) — the welfare of the i-th citizen.

In the only line print the integer S — the minimum number of burles which are had to spend.

NoteIn the first example if we add to the first citizen 4 burles, to the second 3, to the third 2 and to the fourth 1, then the welfare of all citizens will equal 4.In the second example it is enough to give one burle to the third citizen. In the third example it is necessary to give two burles to the first and the third citizens to make the welfare of citizens equal 3.In the fourth example it is possible to give nothing to everyone because all citizens have 12 burles.

let read () = Scanf.scanf "%d " (fun n -> n)
let print result = Printf.printf "%d\n" result

let () =
    let n = read () in
    let rec loop i sum max =
        if i < n
        then
            let balance = read () in
            if balance > max
            then
                loop (i + 1) (sum + balance) balance
            else
                loop (i + 1) (sum + balance) max
        else
            print (n * max - sum)
    in loop 0 0 0

let read () = Scanf.scanf "%d " (fun n -> n)
let print result = Printf.printf "%d\n" result

let input () =
    let n = read () in
    let rec loop list i max =
        if i < n
        then
            let balance = read () in
            if balance > max
            then
                loop (balance :: list) (i + 1) balance
            else
                loop (balance :: list) (i + 1) max
        else
            (list, max)
    in loop [] 0 0

let solve (list, max) =
    let rec loop sum rest =
        match rest with
        | hd :: tl -> loop (sum + (max - hd)) tl
        | [] -> sum
    in loop 0 list

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

let n = read_int () ;;
let a = Array.init n (fun _ -> Scanf.scanf "%d%_c" (fun x -> x)) ;;
let m = Array.fold_left max 0 a ;;
let d = Array.map ((-) m) a ;;
let s = Array.fold_left (+) 0 d ;;

Printf.printf "%d\n" s

let maximum = List.fold_left max 0 in
let _ = read_line () in
let ns = read_line () |> (Str.regexp " +" |> Str.split)  |> List.map int_of_string in
let s = maximum ns |> Array.make (List.length ns) |> Array.to_list |> List.map2 (fun a b -> b - a ) ns |> List.fold_left (+) 0 in
print_int s

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

let () =
  let n = read_int () in
  let lst =
    let rec loop a = function
      | 0 -> a
      | m -> loop ([read_int ()] @ a) (m - 1)
    in loop [] n
  in
  let max =
    let rec loop a = function
      | [] -> a
      | hd :: tl -> if hd > a then loop hd tl else loop a tl
    in loop 0 lst
  in
  let ans = List.fold_left (fun a b -> a + (abs (b - max))) 0 lst in
  Printf.printf "%d\n" ans

let rec accumulate_burles n ax m_ax =
	match n with
	|0 -> (ax, m_ax)
	|_ ->
		let v = ref 0 in
		begin
			Scanf.bscanf Scanf.Scanning.stdin " %i" ( fun x -> v := x; );
			accumulate_burles (n-1) (ax + !v) (max m_ax !v)
		end

let read_and_solve total_count =
	let (sum, max_val) = (accumulate_burles total_count 0 0) in
	let diff = max_val * total_count - sum in
	Printf.printf "%i\n" diff
;;

let read_input () =
	Scanf.bscanf Scanf.Scanning.stdin " %i " read_and_solve
;;

read_input ()

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

let maximum = List.fold_left max 0 in
let _ = read_line () in
let ns = read_line () |> (Str.regexp " *" |> Str.split)  |> List.map int_of_string in
let s = maximum ns |> Array.make (List.length ns) |> Array.to_list |> List.map2 (fun a b -> b - a ) ns |> List.fold_left (+) 0 in
print_int s