Alice and Bob are playing a game with strings. There will be $$$t$$$ rounds in the game. In each round, there will be a string $$$s$$$ consisting of lowercase English letters. Alice moves first and both the players take alternate turns. Alice is allowed to remove any substring of even length (possibly empty) and Bob is allowed to remove any substring of odd length from $$$s$$$.More formally, if there was a string $$$s = s_1s_2 \ldots s_k$$$ the player can choose a substring $$$s_ls_{l+1} \ldots s_{r-1}s_r$$$ with length of corresponding parity and remove it. After that the string will become $$$s = s_1 \ldots s_{l-1}s_{r+1} \ldots s_k$$$.After the string becomes empty, the round ends and each player calculates his/her score for this round. The score of a player is the sum of values of all characters removed by him/her. The value of $$$\texttt{a}$$$ is $$$1$$$, the value of $$$\texttt{b}$$$ is $$$2$$$, the value of $$$\texttt{c}$$$ is $$$3$$$, $$$\ldots$$$, and the value of $$$\texttt{z}$$$ is $$$26$$$. The player with higher score wins the round. For each round, determine the winner and the difference between winner's and loser's scores. Assume that both players play optimally to maximize their score. It can be proved that a draw is impossible.

The first line of input contains a single integer $$$t$$$ ($$$1\leq t\leq 5\cdot 10^4$$$) denoting the number of rounds. Each of the next $$$t$$$ lines contain a single string $$$s$$$ ($$$1\leq |s|\leq 2\cdot 10^5$$$) consisting of lowercase English letters, denoting the string used for the round. Here $$$|s|$$$ denotes the length of the string $$$s$$$. It is guaranteed that the sum of $$$|s|$$$ over all rounds does not exceed $$$2\cdot 10^5$$$.

For each round, print a single line containing a string and an integer. If Alice wins the round, the string must be "Alice". If Bob wins the round, the string must be "Bob". The integer must be the difference between their scores assuming both players play optimally.

NoteFor the first round, $$$\texttt{"aba"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{ab}}}\texttt{a"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$1+2=3$$$. Bob's total score is $$$1$$$.For the second round, $$$\texttt{"abc"}\xrightarrow{\texttt{Alice}}\texttt{"a}{\color{red}{\texttt{bc}}}\texttt{"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$2+3=5$$$. Bob's total score is $$$1$$$.For the third round, $$$\texttt{"cba"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{cb}}}\texttt{a"}\xrightarrow{} \texttt{"a"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{a}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$3+2=5$$$. Bob's total score is $$$1$$$.For the fourth round, $$$\texttt{"n"}\xrightarrow{\texttt{Alice}}\texttt{"n"}\xrightarrow{} \texttt{"n"}\xrightarrow{\texttt{Bob}}\texttt{"}{\color{red}{\texttt{n}}}\texttt{"}\xrightarrow{}\texttt{""}$$$. Alice's total score is $$$0$$$. Bob's total score is $$$14$$$.For the fifth round, $$$\texttt{"codeforces"}\xrightarrow{\texttt{Alice}}\texttt{"}{\color{red}{\texttt{codeforces}}}\texttt{"}\xrightarrow{} \texttt{""}$$$. Alice's total score is $$$3+15+4+5+6+15+18+3+5+19=93$$$. Bob's total score is $$$0$$$.

let n = int_of_string (input_line stdin) in
for i = 0 to n-1 do
  let a = input_line stdin in
  if String.length a = 1 then (let b = Char.code (a.[0]) -96 in print_endline ("Bob "^(string_of_int b)))
  else ( if String.length a mod 2 = 0 then (let count = ref 0 in
                                            for i = 0 to String.length a - 1 do
                                              count := !count + Char.code (a.[i]) - 96 ;
                                            done;
                                            print_endline ("Alice "^ (string_of_int (!count ))))
         else begin
           let count = ref 0 in
           for i = 1 to String.length a - 2 do
             count := !count + Char.code (a.[i]) - 96 ;
           done;
           let b = Char.code (a.[0]) -96 in
           let c = Char.code (a.[ String.length a - 1]) -96 in
           let d = (max b c) - (min b c) in
           print_endline ("Alice "^ (string_of_int (!count +d )));
         end)
done;;


Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules.In this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba.Programmers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given n patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle?

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of patterns. Next n lines contain the patterns. It is guaranteed that the patterns can only consist of small English letters and symbols '?'. All patterns are non-empty and have the same length. The total length of all the patterns does not exceed 105 characters.

In a single line print the answer to the problem — the pattern with the minimal number of signs '?', which intersects with each of the given ones. If there are several answers, print any of them.

NoteConsider the first example. Pattern xab intersects with each of the given patterns. Pattern ??? also intersects with each of the given patterns, but it contains more question signs, hence it is not an optimal answer. Clearly, xab is the optimal answer, because it doesn't contain any question sign. There are a lot of other optimal answers, for example: aab, bab, cab, dab and so on.

let n=read_int();;
let tab=Array.make (n+1) "";;
for i=1 to n do
   tab.(i)<-read_line()
done;;
let m=String.length(tab.(1));;
let vec=Array.make m ' ';;
for j=0 to m-1 do
   vec.(j)<-tab.(1).[j]
done;;
for i=2 to n do
   for j=0 to m-1 do
      if vec.(j)='?' then vec.(j)<-tab.(i).[j]
      else if tab.(i).[j]='?' then ()
      else if tab.(i).[j]<>vec.(j) then vec.(j)<-'!'
   done
done;;

let sol=tab.(1);;
for j=0 to m-1 do
   if vec.(j)='?' then sol.[j]<-'a'
   else if vec.(j)='!' then sol.[j]<-'?'
   else sol.[j]<-vec.(j)
done;;
print_string sol;;

open Scanf
open Printf

let read_int () = scanf " %d " (fun x -> x) in
let read_string () = scanf " %s " (fun x -> x) in

let n = read_int () in
let a = Array.init n (fun x -> (read_string ())) in
let m = String.length a.(0) in

let res = String.make m 'A' in

let upd i c =
    if c <> '?' then
        if res.[i] = 'A' || res.[i] = c then
            res.[i] <- c
        else
            res.[i] <- '?' in

Array.iter (String.iteri upd) a;
printf "%s\n" (String.lowercase res);;

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n "" in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%s " (fun s -> s)
    done;
  in
  let k = String.length a.(0) in
  let res = String.make k 'x' in
    for i = 0 to k - 1 do
      let c = ref '?' in
	for j = 0 to n - 1 do
	  if !c = '?' && a.(j).[i] <> '?' then (
	    c := a.(j).[i];
	    res.[i] <- !c;
	  ) else if !c <> '?' && a.(j).[i] <> '?' && a.(j).[i] <> !c then (
	    res.[i] <- '?'
	  )
	done
    done;
    Printf.printf "%s\n" res;


Nick had received an awesome array of integers $$$a=[a_1, a_2, \dots, a_n]$$$ as a gift for his $$$5$$$ birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product $$$a_1 \cdot a_2 \cdot \dots a_n$$$ of its elements seemed to him not large enough.He was ready to throw out the array, but his mother reassured him. She told him, that array would not be spoiled after the following operation: choose any index $$$i$$$ ($$$1 \le i \le n$$$) and do $$$a_i := -a_i - 1$$$.For example, he can change array $$$[3, -1, -4, 1]$$$ to an array $$$[-4, -1, 3, 1]$$$ after applying this operation to elements with indices $$$i=1$$$ and $$$i=3$$$. Kolya had immediately understood that sometimes it's possible to increase the product of integers of the array a lot. Now he has decided that he wants to get an array with the maximal possible product of integers using only this operation with its elements (possibly zero, one or more times, as many as he wants), it is not forbidden to do this operation several times for the same index. Help Kolya and print the array with the maximal possible product of elements $$$a_1 \cdot a_2 \cdot \dots a_n$$$ which can be received using only this operation in some order.If there are multiple answers, print any of them.

The first line contains integer $$$n$$$ ($$$1 \leq n \leq 10^{5}$$$) — number of integers in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^{6} \leq a_i \leq 10^{6}$$$) — elements of the array

Print $$$n$$$ numbers — elements of the array with the maximal possible product of elements which can be received using only this operation in some order from the given array. If there are multiple answers, print any of them.

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

let () =
  let n = Scanf.scanf "%d\n" (fun x -> x) in
  let a =
    Array.init n (fun _ -> Scanf.scanf "%Ld " (fun x -> x))
    |> Array.mapi (fun i x -> (if 0L <= x then 0L -- x -- 1L else x), i)
  in
  if n mod 2 = 0 then
    Array.iter (fun (x, _) -> Printf.printf "%Ld " x) a
  else
    let min, min_idx =
      Array.fold_left
        (fun (min, min_idx) (x, i) ->
           if x < min then x, i else min, min_idx
        ) a.(0) a
    in
    a.(min_idx) <- 0L -- fst a.(min_idx) -- 1L, min_idx;
    Array.iter (fun (x, _) -> Printf.printf "%Ld " x) a
;;

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

let () =
  let n = Scanf.scanf "%d\n" (fun x -> x) in
  let a =
    Array.init n (fun _ -> Scanf.scanf "%Ld " (fun x -> x))
    |> Array.mapi (fun i x -> (if 0L <= x then 0L -- x -- 1L else x), i)
  in
  if n mod 2 = 0 then
    Array.iter (fun (x, _) -> Printf.printf "%Ld " x) a
  else
    let max, max_idx =
      Array.fold_left
        (fun (max, max_idx) (x, i) ->
           if max < x then x, i else max, max_idx
        ) a.(0) a
    in
    a.(max_idx) <- 0L -- fst a.(max_idx) -- 1L, max_idx;
    Array.iter (fun (x, _) -> Printf.printf "%Ld " x) a
;;

let () =
  let n = Scanf.scanf "%d\n" (fun x -> x) in
  let a =
    Array.init n (fun _ -> Scanf.scanf "%d " (fun x -> x))
    |> Array.mapi (fun i x -> (if 0 <= x then - x - 1 else x), i)
  in
  if n mod 2 = 0 then
    Array.iter (fun (x, _) -> Printf.printf "%d " x) a
  else
    let max, max_idx =
      Array.fold_left
        (fun (max, max_idx) (x, i) ->
           if max < x then x, i else max, max_idx
        ) a.(0) a
    in
    a.(max_idx) <- - fst a.(max_idx) - 1, max_idx;
    Array.iter (fun (x, _) -> Printf.printf "%d " x) a
;;


Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.There are n boys and m girls among his friends. Let's number them from 0 to n - 1 and 0 to m - 1 separately. In i-th day, Drazil invites -th boy and -th girl to have dinner together (as Drazil is programmer, i starts from 0). If one of those two people is happy, the other one will also become happy. Otherwise, those two people remain in their states. Once a person becomes happy (or if he/she was happy originally), he stays happy forever.Drazil wants to know whether he can use this plan to make all his friends become happy at some moment.

The first line contains two integer n and m (1 ≤ n, m ≤ 100). The second line contains integer b (0 ≤ b ≤ n), denoting the number of happy boys among friends of Drazil, and then follow b distinct integers x1, x2, ..., xb (0 ≤ xi < n), denoting the list of indices of happy boys. The third line conatins integer g (0 ≤ g ≤ m), denoting the number of happy girls among friends of Drazil, and then follow g distinct integers y1, y2, ... , yg (0 ≤ yj < m), denoting the list of indices of happy girls. It is guaranteed that there is at least one person that is unhappy among his friends.

If Drazil can make all his friends become happy by this plan, print "Yes". Otherwise, print "No".

NoteBy  we define the remainder of integer division of i by k.In first sample case:   On the 0-th day, Drazil invites 0-th boy and 0-th girl. Because 0-th girl is happy at the beginning, 0-th boy become happy at this day.  On the 1-st day, Drazil invites 1-st boy and 1-st girl. They are both unhappy, so nothing changes at this day.  On the 2-nd day, Drazil invites 0-th boy and 2-nd girl. Because 0-th boy is already happy he makes 2-nd girl become happy at this day.  On the 3-rd day, Drazil invites 1-st boy and 0-th girl. 0-th girl is happy, so she makes 1-st boy happy.  On the 4-th day, Drazil invites 0-th boy and 1-st girl. 0-th boy is happy, so he makes the 1-st girl happy. So, all friends become happy at this moment.

(*  start 6:35  done 6:42 *)
let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_pair () = let u = read_int() in (u,read_int())
let () =
  let (n,m) = read_pair () in
  let boy = Array.make n false in
  let girl = Array.make m false in
  let b = read_int () in
  for i=0 to b-1 do
    boy.(read_int()) <- true;
  done;
  let g = read_int() in
  for i=0 to g-1 do
    girl.(read_int()) <- true;
  done;

  for i=0 to n*m*(1 + min m n) do
    let x = boy.(i mod n) || girl.(i mod m) in
    boy.(i mod n) <- x;
    girl.(i mod m) <- x;
  done;

  if (forall 0 (n-1) (fun i -> boy.(i))) && (forall 0 (m-1) (fun i -> girl.(i)))
  then printf "Yes\n" else printf "No\n";

(*  start 6:35 *)
let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_pair () = let u = read_int() in (u,read_int())
let () =
  let (n,m) = read_pair () in
  let boy = Array.make n false in
  let girl = Array.make m false in
  let b = read_int () in
  for i=0 to b-1 do
    boy.(read_int()) <- true;
  done;
  let g = read_int() in
  for i=0 to g-1 do
    girl.(read_int()) <- true;
  done;

  for i=0 to n*m do
    let x = boy.(i mod n) || girl.(i mod m) in
    boy.(i mod n) <- x;
    girl.(i mod m) <- x;
  done;

  if (forall 0 (n-1) (fun i -> boy.(i))) && (forall 0 (m-1) (fun i -> girl.(i)))
  then printf "Yes\n" else printf "No\n";


Polycarpus likes studying at school a lot and he is always diligent about his homework. Polycarpus has never had any problems with natural sciences as his great-great-grandfather was the great physicist Seinstein. On the other hand though, Polycarpus has never had an easy time with history.Everybody knows that the World history encompasses exactly n events: the i-th event had continued from the year ai to the year bi inclusive (ai < bi). Polycarpus easily learned the dates when each of n events started and ended (Polycarpus inherited excellent memory from his great-great-granddad). But the teacher gave him a more complicated task: Polycaprus should know when all events began and ended and he should also find out for each event whether it includes another event. Polycarpus' teacher thinks that an event j includes an event i if aj < ai and bi < bj. Your task is simpler: find the number of events that are included in some other event.

The first input line contains integer n (1 ≤ n ≤ 105) which represents the number of events. Next n lines contain descriptions of the historical events, one event per line. The i + 1 line contains two integers ai and bi (1 ≤ ai < bi ≤ 109) — the beginning and the end of the i-th event. No two events start or finish in the same year, that is, ai ≠ aj, ai ≠ bj, bi ≠ aj, bi ≠ bj for all i, j (where i ≠ j). Events are given in arbitrary order.

Print the only integer — the answer to the problem.

NoteIn the first example the fifth event is contained in the fourth. Similarly, the fourth event is contained in the third, the third — in the second and the second — in the first.In the second example all events except the first one are contained in the first.In the third example only one event, so the answer is 0.

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

let read_pair () = let a = read_int () in (a , read_int ());;

module Pair_set = struct
        type t = int*int
        let compare = compare
end;;

module Mytest = Set.Make (Pair_set);;

let n = read_int ();;

let data = Array.init n (fun i -> read_pair ());;
Array.sort compare data;;

let ans = ref 0 and _end = ref (-1) in
   for i = 0 to (n-1) do
           let first , second = data.(i) in
               if second < !_end then ans := !ans + 1
               else _end := second
   done;
   Printf.printf "%d\n" !ans;;

(*************** Ocaml stdio functions **********************)
let stdin_stream = Stream.of_channel stdin;;
let stdout_buffer = Buffer.create 65536;;
let rec gi() =
  match Stream.next stdin_stream with
    '-' ->  - (ri 0)
  | '+' ->  ri 0
  | '0'..'9' as c -> ri ((int_of_char c) - 48)
  | _ -> gi ()
and ri x =
  match Stream.next stdin_stream with
    '0'..'9' as c -> ri (((int_of_char c) - 48) + (x * 10))
  | _ -> x
;;
let flushout () = Buffer.output_buffer stdout stdout_buffer; Buffer.reset stdout_buffer;;
let putchar c =
  if (Buffer.length stdout_buffer) >= 65536 then flushout() else ();
  Buffer.add_char stdout_buffer c;;
let rec ppi i = if i < 10 then putchar (char_of_int (48 + i)) else (ppi (i / 10); putchar (char_of_int (48 + (i mod 10)))) ;;
let pi i = if i >= 0 then ppi i else (putchar ('-'); ppi (-i));;
let pa a = let n = Array.length a in Array.iteri (fun i j -> pi j; putchar (if i == (n-1) then '\n' else ' ')) a;;
(*************** Ocaml solution ******************************)
open Array
let main() =
  let n = gi() in
  let a = init n (fun i -> let ai = gi () in let bi = gi () in (ai, bi)) in
  let cmp a b = compare (fst a) (fst b) in
  stable_sort cmp a;
  let mx = ref 0 in
  let s = ref 0 in
  for i = 0 to (n-1) do
    let b = snd a.(i) in
    s := (!s) + (if b > (!mx) then 0 else 1);
    mx := max (!mx) b
    done;
  Printf.printf "%d\n" (!s)
  ;;
main();;
flushout ()

let getnum =
  let l = 512000 in
  let buf = String.make l ' ' in
  let s = ref 0 in
  let pos = ref 0 in
  let getc () =
    if !pos >= !s then (
      let new_s = input stdin buf 0 l in
	(*if new_s = 0 then raise End_of_file;*)
	s := new_s;
	if new_s = 0 then (
	  buf.[0] <- '\000';
	  s := 1;
	);
	pos := 0;
    );
    let c = buf.[!pos] in
      incr pos;
      c
  in
  let aux () =
    let n = ref 0 in
    let k = ref 1 in
      if !s - !pos < 50 then (
	let c = ref (getc ()) in
	  while !c <= ' ' do
	    c := getc ()
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := getc ();
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := getc ()
	  done;
	  !n * !k
      ) else (
	let c = ref (buf.[!pos]) in
	  incr pos;
	  while !c <= ' ' do
	    c := buf.[!pos];
	    incr pos;
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := buf.[!pos];
	    incr pos;
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := buf.[!pos];
	    incr pos;
	  done;
	  !n * !k
      )
  in
    aux

let _ =
  let n = getnum () in
  let c = Array.make n (0, 0) in
    for i = 0 to n - 1 do
      let a = getnum () in
      let b = getnum () in
	c.(i) <- (a, b)
    done;
    Array.sort compare c;
    let latest = ref 0 in
    let res = ref 0 in
      for i = 0 to n - 1 do
	let (_a, b) = c.(i) in
	  if b < !latest
	  then incr res;
	  latest := max !latest b
      done;
      output_string stdout (string_of_int !res);
      output_char stdout '\n';

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

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

let n = read_int()

let p = Array.make n (0,0)

let contained (a,b) s =
  let (l,_,_) = Pset.split (a,b) s in
    if Pset.is_empty l then false else
      let (ai,bi) = Pset.max_elt l in b < bi

let () =
  for i=0 to n-1 do
    let a = read_int() in
    let b = read_int() in
      p.(i) <- (a,b)
  done;
  Array.sort (fun (a,b) (c,d) -> compare (d-c) (b-a)) p;

  let s = ref Pset.empty in
  let count = ref 0 in
    for i=0 to n-1 do
      if not (contained p.(i) !s) then s := Pset.add p.(i) !s
      else count := !count + 1;
    done;

    Printf.printf "%d\n" !count

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

let read_pair () = let a = read_int () in (a , read_int ());;

let n = read_int ();;

let events = Array.init (2*n) (fun i -> (read_int (),if i land 1 = 0 then 0 else 1));;

let compare x y = let a , b = x in let c , d = y in if a = c then 0 else if a > c then 1 else -1;;

Array.sort compare events;;

let ans = ref 0;;

let () =
   let cnt = ref 0 in
       for i = 0 to (2*n-1) do
           let first , second =  events.(i) in
               if second = 1 then begin
                       cnt := !cnt - 1;
                       if !cnt > 0 then ans := !ans + 1
                       else () end
               else cnt := !cnt + 1
       done;;

Printf.printf "%d\n" !ans;;


Shakespeare is a widely known esoteric programming language in which programs look like plays by Shakespeare, and numbers are given by combinations of ornate epithets. In this problem we will have a closer look at the way the numbers are described in Shakespeare.Each constant in Shakespeare is created from non-negative powers of 2 using arithmetic operations. For simplicity we'll allow only addition and subtraction and will look for a representation of the given number which requires a minimal number of operations.You are given an integer n. You have to represent it as n = a1 + a2 + ... + am, where each of ai is a non-negative power of 2, possibly multiplied by -1. Find a representation which minimizes the value of m.

The only line of input contains a positive integer n, written as its binary notation. The length of the notation is at most 106. The first digit of the notation is guaranteed to be 1.

Output the required minimal m. After it output m lines. Each line has to be formatted as "+2^x" or "-2^x", where x is the power coefficient of the corresponding term. The order of the lines doesn't matter.

let s = read_line()
let n = String.length s

let neg = Array.make (n+1) 0
let pos = Array.make (n+1) 0

let bit i = if i>=n then 0 else (int_of_char s.[n-i-1]) - (int_of_char '0')

let nl = ref []
let pl = ref []

let _ =
  if bit 0 = 1 then (
    pos.(0) <- 1;
    neg.(0) <- 1;
    nl := [-2*n];  (* bit zero is turned on *)
    pl := [ 2*n];
  ) else neg.(0) <- n+1

let _ =
  for i=1 to n do
    match bit i with
      | 0 ->
	  if neg.(i-1)+1 < pos.(i-1) then (
	    pos.(i) <- neg.(i-1)+1;
	    pl := i::!nl;
	  ) else
	    pos.(i) <- pos.(i-1);
	  neg.(i) <- neg.(i-1)+1;
	  nl := (-i)::!nl;
      | 1 ->
	  if pos.(i-1)+1 < neg.(i-1) then (
	    neg.(i) <- pos.(i-1) + 1;
	    nl := (-i)::!pl
	  ) else
	    neg.(i) <- neg.(i-1);
	  pos.(i) <- pos.(i-1)+1;
	  pl := i::!pl;
      | _ -> failwith "bad bit"
  done

let rec print_soln = function [] -> ()
  | h::t -> if h<0 then (
      print_string "-2^";
      print_int ((-h) mod (2*n));
      print_char '\n'
    ) else (
      print_string "+2^";
      print_int (h mod (2*n));
      print_char '\n'
    );
      print_soln t
;;

Printf.printf "%d\n" (List.length !pl);
print_soln !pl

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

let s = read_string()
let n = String.length s

let neg = Array.make (n+1) 0
let pos = Array.make (n+1) 0

let bit i = if i>=n then 0 else (int_of_char s.[n-i-1]) - (int_of_char '0')

let nl = ref []
let pl = ref []

let _ =
  if bit 0 = 1 then (
    pos.(0) <- 1;
    neg.(0) <- 1;
    nl := [-2*n];  (* bit zero is turned on *)
    pl := [ 2*n];
  ) else neg.(0) <- n+1

let _ =
  for i=1 to n do
    match bit i with
      | 0 ->
	  if neg.(i-1)+1 < pos.(i-1) then (
	    pos.(i) <- neg.(i-1)+1;
	    pl := i::!nl;
	  ) else
	    pos.(i) <- pos.(i-1);
	  neg.(i) <- neg.(i-1)+1;
	  nl := (-i)::!nl;
      | 1 ->
	  if pos.(i-1)+1 < neg.(i-1) then (
	    neg.(i) <- pos.(i-1) + 1;
	    nl := (-i)::!pl
	  ) else
	    neg.(i) <- neg.(i-1);
	  pos.(i) <- pos.(i-1)+1;
	  pl := i::!pl;
      | _ -> failwith "bad bit"
  done

let rec print_soln = function [] -> ()
  | h::t -> if h<0 then
      Printf.printf "-2^%d\n" ((-h) mod (2*n))
    else
      Printf.printf "+2^%d\n" (h mod (2*n));
      print_soln t
;;

print_soln !pl


Vladik had started reading a complicated book about algorithms containing n pages. To improve understanding of what is written, his friends advised him to read pages in some order given by permutation P = [p1, p2, ..., pn], where pi denotes the number of page that should be read i-th in turn.Sometimes Vladik’s mom sorted some subsegment of permutation P from position l to position r inclusive, because she loves the order. For every of such sorting Vladik knows number x — what index of page in permutation he should read. He is wondered if the page, which he will read after sorting, has changed. In other words, has px changed? After every sorting Vladik return permutation to initial state, so you can assume that each sorting is independent from each other.

First line contains two space-separated integers n, m (1 ≤ n, m ≤ 104) — length of permutation and number of times Vladik's mom sorted some subsegment of the book. Second line contains n space-separated integers p1, p2, ..., pn (1 ≤ pi ≤ n) — permutation P. Note that elements in permutation are distinct. Each of the next m lines contains three space-separated integers li, ri, xi (1 ≤ li ≤ xi ≤ ri ≤ n) — left and right borders of sorted subsegment in i-th sorting and position that is interesting to Vladik.

For each mom’s sorting on it’s own line print "Yes", if page which is interesting to Vladik hasn't changed, or "No" otherwise.

NoteExplanation of first test case:   [1, 2, 3, 4, 5] — permutation after sorting, 3-rd element hasn’t changed, so answer is "Yes".  [3, 4, 5, 2, 1] — permutation after sorting, 1-st element has changed, so answer is "No".  [5, 2, 3, 4, 1] — permutation after sorting, 3-rd element hasn’t changed, so answer is "Yes".  [5, 4, 3, 2, 1] — permutation after sorting, 4-th element hasn’t changed, so answer is "Yes".  [5, 1, 2, 3, 4] — permutation after sorting, 3-rd element has changed, so answer is "No".

open Printf
open Scanf

let read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)
let read3 _ = bscanf Scanning.stdib " %d %d %d " (fun x y z -> (x,y,z))
let () =
  let n = read_int () in
  let m = read_int () in
  let p = Array.init (n+1) (fun i -> if i=0 then 0 else read_int()) in
  let query = Array.init m read3 in

  let count_smaller l r x =
    let count_range i j v =
      let c = ref 0 in
      for k=i to j do
	if p.(k) < v then c := !c + 1
      done;
      !c
    in

    let r1 = r-l+1 in
    let r2 = l-1 + (n-r) in
    if r1 <= r2 then count_range l r p.(x)
    else p.(x) - 1 - ((count_range 1 (l-1) p.(x)) + (count_range (r+1) n p.(x)))
  in

  for i=0 to m-1 do
    let (l,r,x) = query.(i) in
    if count_smaller l r x = x-l then printf "Yes\n" else printf "No\n"
  done


Little Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai, then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions:   Set the power of the hole a to value b.  Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.

The first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types:    0 a b  1 a  0 a b 1 a a b N

For each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.

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

type node = {mutable p: int; mutable d: int; ch: int array; mutable size: int}

class link_cut_tree n_ = object (self)
  val n = n_
  val a = Array.init (n_+1) (fun i ->
      {p=0; d=2; ch=Array.make 2 0; size=if i = 0 then 0 else 1}
    )

  method private pull x =
    a.(x).size <- a.(a.(x).ch.(0)).size + a.(a.(x).ch.(1)).size + 1

  method private join x d y =
    if d < 2 then
      a.(x).ch.(d) <- y;
    a.(y).p <- x;
    a.(y).d <- d

  method private zag x =
    let y = a.(x).p
    and d = a.(x).d in
    self#join y d a.(x).ch.(1-d);
    self#join a.(y).p a.(y).d x;
    self#join x (1-d) y;
    self#pull y

  method private splay x =
    let rec go _ =
      let y = a.(x).p in
      if y <> 0 && a.(x).d < 2 then (
        if a.(y).p <> 0 && a.(y).d < 2 then
          self#zag (if a.(x).d = a.(y).d then y else x);
        self#zag x;
        go ()
      )
    in
    go ();
    self#pull x

  method private access x =
    let rec go x y =
      if x <> 0 then (
        self#splay x;
        a.(a.(x).ch.(1)).d <- 2;
        self#join x 1 y;
        go a.(x).p x
      )
    in
    go x 0

  method get_root x =
    self#access x;
    self#splay x;
    let rec go x =
      if a.(x).ch.(0) = 0 then
        x
      else
        go a.(x).ch.(0)
    in
    let r = go x in
    self#splay r;
    r

  method get_dep x =
    self#access x;
    self#splay x;
    a.(a.(x).ch.(0)).size

  method link x y =
    (* self#access y; not necessary if no reverse *)
    self#splay y;
    a.(y).p <- x;
    a.(y).d <- 2;
    self#splay y

  method cut x =
    self#access x;
    self#splay x;
    a.(a.(x).ch.(0)).p <- 0;
    a.(a.(x).ch.(0)).d <- 2;
    a.(x).ch.(0) <- 0

  method dump =
    for i = 0 to n do
      Printf.printf "%d: p=%d d=%d l=%d r=%d size=%d\n" i a.(i).p a.(i).d
      a.(i).ch.(0) a.(i).ch.(1) a.(i).size
    done
end

let () =
  let n = read_int 0 in
  let m = read_int 0 in
  let t = new link_cut_tree n in
  for i = 1 to n do
    let x = read_int 0 in
    if i+x <= n then
      t#link (i+x) i
  done;
  for i = 1 to m do
    if read_int 0 = 0 then (
      let x = read_int 0 in
      let y = read_int 0 in
      t#cut x;
      t#link (if x+y > n then 0 else x+y) x
    ) else
      let x = read_int 0 in
      Printf.printf "%d %d\n" (t#get_root x) (t#get_dep x + 1)
  done


Today Pari and Arya are playing a game called Remainders.Pari chooses two positive integer x and k, and tells Arya k but not x. Arya have to find the value . There are n ancient numbers c1, c2, ..., cn and Pari has to tell Arya  if Arya wants. Given k and the ancient values, tell us if Arya has a winning strategy independent of value of x or not. Formally, is it true that Arya can understand the value  for any positive integer x?Note, that  means the remainder of x after dividing it by y.

The first line of the input contains two integers n and k (1 ≤ n,  k ≤ 1 000 000) — the number of ancient integers and value k that is chosen by Pari. The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 1 000 000).

Print "Yes" (without quotes) if Arya has a winning strategy independent of value of x, or "No" (without quotes) otherwise.

NoteIn the first sample, Arya can understand  because 5 is one of the ancient numbers.In the second sample, Arya can't be sure what  is. For example 1 and 7 have the same remainders after dividing by 2 and 3, but they differ in remainders after dividing by 7.

let rec gcd x y =
  if y == 0 then
    x
  else
    gcd y (x mod y)

let () =
  match read_line () |> Str.(split (regexp " ")) |> List.map int_of_string with
  | [n; k] ->
     let c = read_line () |> Str.(split (regexp " ")) |> List.map int_of_string in
     print_endline (
       if List.(fold_left gcd k (map (fun ci -> k / gcd k ci) c)) == 1 then
         "Yes"
       else
         "No"
       )
  | _ -> assert false

open Printf
open Scanf

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

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

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

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

  let factors = factor k in

  let answer = List.exists (fun p ->
    forall 0 (n-1) (fun i -> c.(i) mod p <> 0)
  ) factors in

  if answer then printf "No\n" else printf "Yes\n"

open Printf
open Scanf

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 rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)

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

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

  let factors = List.sort_uniq compare (factor k) in

  let answer = List.exists (fun p ->
    forall 0 (n-1) (fun i -> c.(i) mod p <> 0)
  ) factors in

  if answer then printf "No\n" else printf "Yes\n"


Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0). Next day Misha couldn't remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.

The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph. The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space.

In the first line print number m, the number of edges of the graph. Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b). Edges can be printed in any order; vertices of the edge can also be printed in any order.

NoteThe XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".

let () = Scanf.scanf "%d\n" (fun n ->
  let s = Stack.create () in
  let e = ref [] in
  let a = Array.init n (fun i ->
    let d, x = Scanf.scanf "%d %d\n" (fun d s -> (d, s)) in
    if d = 1 then Stack.push i s;
    (d, x)
  ) in
  while not (Stack.is_empty s) do
    let i = Stack.pop s in
    let d', j = a.(i) in
    if d' = 1 then begin
      e := (i, j) :: !e;
      let d, x = a.(j) in
      a.(j) <- (d - 1, x lxor i);
      if d = 2 then Stack.push j s
    end
  done;
  Printf.printf "%d\n" (List.length !e);
  List.iter (fun (a, b) -> Printf.printf "%d %d\n" a b) !e
)

type el = {
  i : int; (* node index *)
  mutable d : int; (* node degree *)
  mutable s : int; (* xor sum of neighbours *)
}

module H : sig
  type t
  val make : int -> t
  val add : t -> el -> unit
  val dec : t -> int -> unit
  val is_empty : t -> bool
  val pop : t -> el
  val get : t -> int -> el * int
end = struct
  type t = {
    mutable len : int;
    arr : el array;
    rev : int array;
  }

  let is_empty h = h.len = 0

  let make n = {
    len = 0;
    arr = Array.make n { i = -1; d = 0; s = 0 };
    rev = Array.make n 0;
  }

  let get h i =
    let j = h.rev.(i) in
    (h.arr.(j), j)

  let swap h i j =
    let e = h.arr.(i)
    and f = h.arr.(j) in
    h.arr.(i) <- f;
    h.arr.(j) <- e;
    h.rev.(e.i) <- j;
    h.rev.(f.i) <- i

  let rec dec h i =
    if i = 0 then ()
    else begin
      (* get parent *)
      let p = (i - 1) / 2 in
      (* if the child has smaller degree than parent *)
      if h.arr.(p).d > h.arr.(i).d then begin
        swap h i p;
        dec h p
      end
    end

  let rec inc h i =
    let l = 2 * i + 1
    and r = 2 * i + 2 in

    (* no children *)
    if l >= h.len then ()

    (* only left child *)
    else if r >= h.len then begin
      if h.arr.(i).d > h.arr.(l).d then begin
        swap h i l;
        inc h l
      end
    end

    (* both children *)
    else begin
      if h.arr.(i).d > h.arr.(l).d then
        (* right child is smallest *)
        if h.arr.(l).d > h.arr.(r).d then begin
          swap h i r;
          inc h r
        (* left child is smallest *)
        end else begin
          swap h i l;
          inc h l
        end
      (* right child is smaller *)
      else if h.arr.(i).d > h.arr.(r).d then begin
        swap h i r;
        inc h r
      end
    end

  let add h e =
    (* insert the element at the end of the heap *)
    h.arr.(h.len) <- e;
    h.rev.(e.i) <- h.len;

    (* bubble up to enforce the heap constraint *)
    dec h h.len;
    h.len <- h.len + 1

  let pop h =
    let e = h.arr.(0) in
    h.len <- h.len - 1;

    (* move the last element to the top *)
    swap h 0 h.len;

    (* bubble down *)
    inc h 0;

    (* return the element *)
    e
end

let () = Scanf.scanf "%d\n" (fun n ->
  let nodes = H.make n in
  let edges = ref [] in

  (* read nodes and populate the heap *)
  for i = 0 to n - 1 do
    let d, s = Scanf.scanf "%d %d\n" (fun d s -> (d, s)) in
    let el = { i; d; s } in
    H.add nodes el
  done;

  while not (H.is_empty nodes) do
    let e = H.pop nodes in
    match e.d with
    | 0 -> () (* isolated node; no edges *)

    | 1 -> (* leaf node, add edge to list *)
        edges := (e.i, e.s) :: !edges;
        let f, j = H.get nodes e.s in
        f.s <- f.s lxor e.i;
        f.d <- f.d - 1;
        H.dec nodes j;

    | _ -> failwith "Cycle detected"
  done;

  Printf.printf "%d\n" (List.length !edges);
  List.iter (fun (a, b) -> Printf.printf "%d %d\n" a b) !edges
)


Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.

The first line contains two space-separated integers n and m (1 ≤ m ≤ n ≤ 100) — amount of TV sets at the sale, and amount of TV sets that Bob can carry. The following line contains n space-separated integers ai ( - 1000 ≤ ai ≤ 1000) — prices of the TV sets.

Output the only number — the maximum sum of money that Bob can earn, given that he can carry at most m TV sets.

let rec input_tv = function
  | 0 -> []
  | i -> (Scanf.scanf " %d" (fun x -> x)) :: input_tv (i-1)

let solve n m =
  let tv = List.sort compare (input_tv n) in
  let rec loop i tv =
    match i with
    | 0 -> 0
    | i ->
      let current = List.hd tv in
      if current > 0 then 0
      else current + (loop (i-1) (List.tl tv))
  in
  -(loop m tv)

let _ =
  Printf.printf "%d\n" (Scanf.scanf " %d %d" solve)

let rec input_tv = function
  | 0 -> []
  | i -> (Scanf.scanf " %d" (fun x -> x)) :: input_tv (i-1)

let solve n m =
  let tv = List.sort compare (input_tv n) in
  let rec loop i tv =
    match i with
    | 0 -> 0
    | i ->
      (List.hd tv) + (loop (i-1) (List.tl tv))
  in
  -(loop m tv)

let _ =
  Printf.printf "%d\n" (Scanf.scanf " %d %d" solve)


You are given an integer $$$n$$$. You have to change the minimum number of digits in it in such a way that the resulting number does not have any leading zeroes and is divisible by $$$7$$$.If there are multiple ways to do it, print any of them. If the given number is already divisible by $$$7$$$, leave it unchanged.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 990$$$) — the number of test cases. Then the test cases follow, each test case consists of one line containing one integer $$$n$$$ ($$$10 \le n \le 999$$$).

For each test case, print one integer without any leading zeroes — the result of your changes (i. e. the integer that is divisible by $$$7$$$ and can be obtained by changing the minimum possible number of digits in $$$n$$$). If there are multiple ways to apply changes, print any resulting number. If the given number is already divisible by $$$7$$$, just print it.

NoteIn the first test case of the example, $$$42$$$ is already divisible by $$$7$$$, so there's no need to change it.In the second test case of the example, there are multiple answers — $$$28$$$, $$$21$$$ or $$$63$$$.In the third test case of the example, other possible answers are $$$357$$$, $$$371$$$ and $$$378$$$. Note that you cannot print $$$077$$$ or $$$77$$$.

open Printf
open Scanf

let solve_one = (
)

let remove_last s = (String.sub s 0 ((String.length s) - 1))

let find_div7 s =
  let rec find_div7_try k =
    if k == 10 then 0
    else if ((s * 10 + k) mod 7) == 0 then (s * 10 + k)
    else find_div7_try (k + 1) in
  find_div7_try 0

let rec solve t =
  if t > 0 then (
    let s = read_line() in
    let v = int_of_string s in
    (
      if v mod 7 == 0 then v
      else find_div7 (int_of_string (remove_last s))
    )
    |> string_of_int
    |> print_endline;
    solve (t - 1)
  )
  else ()

let () =
  let t = int_of_string (read_line()) in
  solve t

Scanf.scanf "%d" (fun t ->
    for i = 1 to t do
        Printf.printf "%d\n" (
            Scanf.scanf " %d" (fun n ->
                if n mod 7 = 0 then n else
                    let n2 = n / 10 * 10 in
                    let rec loop i =
                        if (n2 + i) mod 7 = 0 then n2 + i else loop (i + 1)
                    in
                    loop 0
            )
        )
    done
)

open Printf
open Scanf

let solve_one = (
)

let remove_last s = (String.sub s 0 ((String.length s) - 1))

let find_div7 s =
  let rec find_div7_try k =
    if k == 10 then 0
    else if ((s * 10 + k) mod 7) == 0 then (s * 10 + k)
    else find_div7_try (k + 1) in
  find_div7_try 0

let rec solve t =
  if t > 0 then (
    let s = read_line() in
    print_endline (string_of_int (find_div7 (int_of_string (remove_last s))));
    solve (t - 1)
  )
  else ()

let () =
  let t = int_of_string (read_line()) in
  solve t


You are given an array $$$a$$$ of $$$n$$$ integers. Find the number of pairs $$$(i, j)$$$ ($$$1 \le i < j \le n$$$) where the sum of $$$a_i + a_j$$$ is greater than or equal to $$$l$$$ and less than or equal to $$$r$$$ (that is, $$$l \le a_i + a_j \le r$$$).For example, if $$$n = 3$$$, $$$a = [5, 1, 2]$$$, $$$l = 4$$$ and $$$r = 7$$$, then two pairs are suitable:   $$$i=1$$$ and $$$j=2$$$ ($$$4 \le 5 + 1 \le 7$$$);  $$$i=1$$$ and $$$j=3$$$ ($$$4 \le 5 + 2 \le 7$$$).

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. The first line of each test case contains three integers $$$n, l, r$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le l \le r \le 10^9$$$) — the length of the array and the limits on the sum in the pair. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ overall test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, output a single integer — the number of index pairs $$$(i, j)$$$ ($$$i < j$$$), such that $$$l \le a_i + a_j \le r$$$.

open Printf
open Scanf

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

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

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

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_long _ = bscanf Scanning.stdin " %Ld " (fun x -> x)
let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))
let () =
  let cases = read_int() in
  for case = 1 to cases do
    let n = read_int () in
    let l = read_long () in
    let r = read_long () in
    let a = Array.init n read_long in
    Array.sort compare a;

    let rec scan i v w count = if i=n then count else (
      let rec loopv v = if v <= 0 then v else (
	if a.(i) ++ a.(v-1) >= l then loopv (v-1) else v
      ) in
      let v = loopv v in

      let rec loopw w = if w < 0 then w else (
	if a.(i) ++ a.(w) > r then loopw (w-1) else w
      ) in
      let w = loopw w in
      if a.(i) ++ a.(v) < l then scan (i+1) v w count
      else if w < 0 then count else (
	let count = count ++ (long (max (w-v+1) 0)) in
	scan (i+1) v w count
      )
    ) in

    let count = scan 0 (n-1) (n-1) 0L in
    let diag = sum 0 (n-1) (fun i -> if a.(i) ++ a.(i) <= r && a.(i) ++ a.(i) >= l then 1 else 0) in
    let answer = (count -- (long diag))//2L in
    printf "%Ld\n" answer
  done

open Printf
open Scanf

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

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

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

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_long _ = bscanf Scanning.stdin " %Ld " (fun x -> x)
let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))
let () =
  let cases = read_int() in
  for case = 1 to cases do
    let n = read_int () in
    let l = read_long () in
    let r = read_long () in
    let a = Array.init n read_long in
    Array.sort compare a;

    let findv i =
      (* return Some v if a.(i) + a.(v) >= l and v is the smallest such index.
	 None if there is no such index *)
      let rec bsearch lo hi =
      (* know that a.(i) + a.(hi) >= l and a.(i) + a.(lo) < l *)
	if hi = lo+1 then hi else
	  let m = (lo+hi)/2 in
	  if a.(i) ++ a.(m) < l then bsearch m hi else bsearch lo m
      in
      if a.(i) ++ a.(n-1) < l then None
      else if a.(i) ++ a.(0) >= l then Some 0
      else Some (bsearch 0 (n-1))
    in

    let findw i =
      (* return Some v if a.(i) + a.(v) <= r and v is the largest such index.
	 None if there is no such index *)
      let rec bsearch lo hi =
      (* know that a.(i) + a.(hi) > r and a.(i) + a.(lo) <= r *)
	if hi = lo+1 then lo else
	  let m = (lo+hi)/2 in
	  if a.(i) ++ a.(m) <= r then bsearch m hi else bsearch lo m
      in
      if a.(i) ++ a.(0) > r then None
      else if a.(i) ++ a.(n-1) <= r then Some (n-1)
      else Some (bsearch 0 (n-1))
    in

    let count = sum 0 (n-1) (fun i ->
      match (findv i, findw i) with
	| (None, _) | (_, None) -> 0
	| (Some v, Some w) -> max (w-v+1) 0
    ) in

    if n <= 1 then printf "0\n" else (
      let diag = sum 0 (n-1) (fun i -> if a.(i) ++ a.(i) <= r && a.(i) ++ a.(i) >= l then 1 else 0) in
      let answer = (count - diag)/2 in
      printf "%d\n" answer
    )
  done

open Printf
open Scanf

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

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

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

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_long _ = bscanf Scanning.stdin " %Ld " (fun x -> x)
let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))
let () =
  let cases = read_int() in
  for case = 1 to cases do
    let n = read_int () in
    let l = read_long () in
    let r = read_long () in
    let a = Array.init n read_long in
    Array.sort compare a;

    let findv i =
      (* return Some v if a.(i) + a.(v) >= l and v is the smallest such index.
	 None if there is no such index *)
      let rec bsearch lo hi =
      (* know that a.(i) + a.(hi) >= l and a.(i) + a.(lo) < l *)
	if hi = lo+1 then hi else
	  let m = (lo+hi)/2 in
	  if a.(i) ++ a.(m) < l then bsearch m hi else bsearch lo m
      in
      if a.(i) ++ a.(n-1) < l then None
      else if a.(i) ++ a.(0) >= l then Some 0
      else Some (bsearch 0 (n-1))
    in

    let findw i =
      (* return Some v if a.(i) + a.(v) <= r and v is the largest such index.
	 None if there is no such index *)
      let rec bsearch lo hi =
      (* know that a.(i) + a.(hi) >= r and a.(i) + a.(lo) < r *)
	if hi = lo+1 then hi else
	  let m = (lo+hi)/2 in
	  if a.(i) ++ a.(m) < r then bsearch m hi else bsearch lo m
      in
      if a.(i) ++ a.(0) > r then None
      else if a.(i) ++ a.(n-1) <= r then Some (n-1)
      else Some (bsearch 0 (n-1))
    in

    let count = sum 0 (n-1) (fun i ->
      match (findv i, findw i) with
	| (None, _) | (_, None) -> 0
	| (Some v, Some w) -> max (w-v+1) 0
    ) in

    if n <= 1 then printf "0\n" else (
      let diag = sum 0 (n-1) (fun i -> if a.(i) ++ a.(i) <= r && a.(i) ++ a.(i) >= l then 1 else 0) in

      let answer = (count - diag)/2 in
      printf "%d\n" answer
    )
  done

open Printf
open Scanf

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

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

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

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_long _ = bscanf Scanning.stdin " %Ld " (fun x -> x)
let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))
let () =
  let cases = read_int() in
  for case = 1 to cases do
    let n = read_int () in
    let l = read_long () in
    let r = read_long () in
    let a = Array.init n read_long in
    Array.sort compare a;

    let rec scan i v w count = if i=n then count else (
      let rec loopv v = if v <= 0 then v else (
	if a.(i) ++ a.(v-1) >= l then loopv (v-1) else v
      ) in
      let v = loopv v in

      let rec loopw w = if w < 0 then w else (
	if a.(i) ++ a.(w) > r then loopw (w-1) else w
      ) in
      let w = loopw w in
      if a.(i) ++ a.(v) < l then scan (i+1) v w count
      else if w < 0 then count else (
	let count = count + max (w-v+1) 0 in
	scan (i+1) v w count
      )
    ) in

    let count = scan 0 (n-1) (n-1) 0 in
    let diag = sum 0 (n-1) (fun i -> if a.(i) ++ a.(i) <= r && a.(i) ++ a.(i) >= l then 1 else 0) in
    let answer = (count - diag)/2 in
    printf "%d\n" answer
  done


Luyi has n circles on the plane. The i-th circle is centered at (xi, yi). At the time zero circles start to grow simultaneously. In other words, the radius of each circle at time t (t > 0) is equal to t. The circles are drawn as black discs on an infinite white plane. So at each moment the plane consists of several black and white regions. Note that the circles may overlap while growing.  We define a hole as a closed, connected white region. For instance, the figure contains two holes shown by red border. During growing some holes may be created and it is easy to see that each created hole will disappear eventually. Luyi asks you to find moment of time such that the last hole disappears. In other words, you should find the first moment such that no hole can be seen after that.

The first line of the input contains integer n (1 ≤ n ≤ 100). Each of the next n lines contains two integers xi and yi ( - 104 ≤ xi, yi ≤ 104), indicating the location of i-th circle. It's guaranteed that no two circles are centered at the same point.

Print the moment where the last hole disappears. If there exists no moment in which we can find holes print -1. The answer will be considered correct if the absolute or relative error does not exceed 10 - 4.

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

(* http://www.cs.cmu.edu/~quake/robust.html *)

let sq x = x ** x

let det ((a,b,c),(d,e,f),(g,h,i)) =
  a**(e**i -- f**h) -- b**(d**i -- f**g) ++ c**(d**h -- e**g)

(* This returns 0 if the four points are on the same circle.
   It returns >0 if going around the circle in the direction
   a --> b --> c then d is on the side of the circle pointed
   to by my left hand.  It returns >0 otherwise.  It's a fourth
   degree function in the given coordinates. *)

let incircle (ax,ay) (bx,by) (cx,cy) (dx,dy) =
  let row ax dx ay dy =
    let a = ax -- dx in
    let b = ay -- dy in
      (a, b, (sq a) ++ (sq b))
  in
    det (row ax dx ay dy, row bx dx by dy, row cx dx cy dy)

let (---) (x1,y1) (x2,y2) = (x1--x2, y1--y2);;
let (+++) (x1,y1) (x2,y2) = (x1++x2, y1++y2);;
let cross (x1,y1) (x2,y2) = (x1**y2) -- (y1**x2);;
let dot (x1,y1) (x2,y2) = (x1**x2) ++ (y1**y2);;

(* radius of a circle given three points from
   http://en.wikipedia.org/wiki/Circumscribed_circle *)

let length (x,y) =
  let (x,y) = (Int64.to_float x, Int64.to_float y) in
    sqrt (x*.x +. y*.y)

let radius a b c  =
  let a = a --- c in
  let b = b --- c in
    (length a) *. (length b) *. (length (a --- b)) /.
      (2.0 *. (abs_float (Int64.to_float (cross a b))))

(* this returns >0 if c on the left side of a-->b, <0 if on the right, and 0 if on. *)
let leftside a b c = cross (a---c) (b---c)

(* The following function takes a list of points as input, and returns true
   if it's smooth, that is, if none of the angles as we walk around the points
   subsumes more than half of the circle *)
let smooth_set a =
  let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init) in
  let sum i j f = fold i j (fun i a -> (f i) +. a) 0.0 in
  let float_of_array a n =
    Array.init n (fun i -> let (xi, yi) = a.(i) in (Int64.to_float xi, Int64.to_float yi))
  in

  let a = Array.of_list a in
  let n = Array.length a in
  let af = float_of_array a n in
  let cx = (sum 0 (n-1) (fun i -> fst af.(i))) /. (float n) in
  let cy = (sum 0 (n-1) (fun i -> snd af.(i))) /. (float n) in
  let ang = Array.init n (fun i -> (atan2 ((fst af.(i) -. cx)) ((snd af.(i)) -. cy), i)) in
  let () = Array.sort compare ang in

  let rec loop i = i=n || (
    let j1 = snd ang.(i) in
    let j2 = snd (ang.((i+1) mod n)) in
    let j3 = snd (ang.((i+2) mod n)) in
    let v1 = a.(j3) --- a.(j1) in
    let v2 = a.(j2) --- a.(j3) in
      dot v1 v2 < 0L && loop (i+1)
  ) in
    loop 0

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

let print_smooth_set s =
  Printf.printf "smooth set: ";
  List.iter (fun (x,y) -> Printf.printf "(%Ld,%Ld) " x y) s;
  print_newline()

let () =
  let n = read_int() in
  let c = Array.init n read_pair in

  let bestr = ref (-1.0) in

    for i=0 to n-1 do
      for j=0 to n-1 do
	if i <> j then (
	  let prev = ref (-1) in
	    for k=0 to n-1 do
	      if k <> i && k <> j && (leftside c.(i) c.(j) c.(k) > 0L) then (
		if !prev = -1 || (incircle c.(i) c.(j) c.(!prev) c.(k)) > 0L then prev := k
	      )
	    done;
	    if !prev >0 then (
	      let bad = ref false in
	      let onlist = ref [] in
		for k=0 to n-1 do
		  let cval = incircle c.(i) c.(j) c.(!prev) c.(k) in
		    if cval = 0L then onlist := c.(k) :: !onlist
		    else if cval > 0L then bad := true
		done;
		if (not !bad) && (smooth_set !onlist) then (
(*		  print_smooth_set !onlist; *)
		  let r = radius c.(i) c.(j) c.(!prev) in
		    bestr := max r !bestr
		)
	    )
	)
      done
    done;

    if !bestr < 0.0 then Printf.printf "-1\n" else Printf.printf "%.6f\n" !bestr

(* O(n^2) Delaunay triangulation algorithm *)

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

(* http://www.cs.cmu.edu/~quake/robust.html *)

(* This returns 0 if the four points are on the same circle.
   It returns >0 if going around the circle in the direction
   a --> b --> c then d is on the side of the circle pointed
   to by my left hand.  It returns >0 otherwise.  It's a fourth
   degree function in the given coordinates. *)

let (---) (x1,y1) (x2,y2) = (x1--x2, y1--y2);;
let (+++) (x1,y1) (x2,y2) = (x1++x2, y1++y2);;
let cross (x1,y1) (x2,y2) = (x1**y2) -- (y1**x2);;
let dot (x1,y1) (x2,y2) = (x1**x2) ++ (y1**y2);;
let sq x = x ** x
let length (x,y) =
  let (x,y) = (Int64.to_float x, Int64.to_float y) in
    sqrt (x*.x +. y*.y)

let incircle (ax,ay) (bx,by) (cx,cy) (dx,dy) =
  let det ((a,b,c),(d,e,f),(g,h,i)) =
    a**(e**i -- f**h) -- b**(d**i -- f**g) ++ c**(d**h -- e**g)
  in

  let row ax dx ay dy =
    let a = ax -- dx in
    let b = ay -- dy in
      (a, b, (sq a) ++ (sq b))
  in
    det (row ax dx ay dy, row bx dx by dy, row cx dx cy dy)

(* radius of a circle given three points from
   http://en.wikipedia.org/wiki/Circumscribed_circle *)

let radius a b c  =
  let a = a --- c in
  let b = b --- c in
    (length a) *. (length b) *. (length (a --- b)) /.
      (2.0 *. (abs_float (Int64.to_float (cross a b))))

(* this returns >0 if c on the left side of a-->b, <0 if on the right, and 0 if on. *)
let leftside a b c = cross (a---c) (b---c)

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

(* takes as input an array of p of n points, and computes
   the Delaunay triangulation of them *)
let delaunay p n =

  let len2 (px,py) (qx,qy) = (sq (px--qx)) ++ (sq (py--qy)) in

  let rec closest (i,j) (bi,bj) dist =
    if j=n then (bi,bj) else
      let d = len2 p.(i) p.(j) in
      let next = if i+1<j then (i+1,j) else (0,j+1) in
	if bj=0 || d<dist then closest next (i,j) d else closest next (bi,bj) dist
  in
  let (bi,bj) = closest (0,1) (0,0) 0L in

  let order_face i j face nv =
    (* This returns an array of indices of this face in counterclockwise order.
       Think of i pointing up to j.  all the other points of the face are to the
       left of this line.  We sort them by taking the dot product of the i-->j vector
       with the normalized j-->k vector, and sort it in decreasing order.  *)
    let v = Array.make (nv-2) (0.0, 0) in
    let rec loadv k li = match li with [] -> () | h::li ->
      let a = p.(j) --- p.(i) in
      let b = p.(h) --- p.(j) in
      let dp = (Int64.to_float (dot a b)) /. (length b) in
	v.(k) <- (dp, h);
	loadv (k+1) li
    in
      loadv 0 face;
      Array.sort (fun a b -> compare b a) v;
      Array.init nv (fun k -> if k=0 then i else if k=1 then j else snd v.(k-2))
  in

  let rec loop (completed,todo) ac =
    match todo with
      | [] -> ac
      | (i,j)::todo ->
	  if Pset.mem (i,j) completed then loop (completed,todo) ac else
	    let rec findface ac k = if k=n then ac else
	      if k = i || k = j || (leftside p.(i) p.(j) p.(k) <= 0L) then findface ac (k+1) else
		if ac = [] then findface [k] (k+1) else
		  let ic = incircle p.(i) p.(j) p.(List.hd ac) p.(k) in
		    if ic > 0L then findface [k] (k+1)
		    else if ic = 0L then findface (k::ac) (k+1)
		    else findface ac (k+1)
	    in
	    let face = findface [] 0 in

	      if face = [] then loop (Pset.add (i,j) completed, todo) ac (* convex hull edge *)
	      else (
		let nv = 2 + (List.length face) in
		let v = order_face i j face nv in
		let rec process_face k (s,t) = if k = nv then (s,t) else
		  let l = (k+1) mod nv in
		  let s = Pset.add (v.(k), v.(l)) s in
		  let t = (v.(l), v.(k)) :: t in
		    process_face (k+1) (s,t)
		in
		  loop (process_face 0 (completed,todo)) (v::ac)
	      )
  in
    loop (Pset.empty, [(bi,bj); (bj,bi)]) []

(*----------------------------------------------------------------------*)

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

let () =
  let n = read_int() in
  let p = Array.init n read_pair in

  (* The following function takes an array of indices on a circle as input,
     and returns true if it's smooth, that is, if the polygon strictly
     contains the center.  *)
  let smooth_set a n =
    let rec loop i = i=n || (
      let j1 = a.(i) in
      let j2 = a.((i+1) mod n) in
      let j3 = a.((i+2) mod n) in
      let v1 = p.(j3) --- p.(j1) in
      let v2 = p.(j2) --- p.(j3) in
	dot v1 v2 < 0L && loop (i+1)
    ) in
      loop 0
  in

  let rec loop bestr f = match f with [] -> bestr
    | a::f ->
	let nv = Array.length a in
	let bestr = if smooth_set a nv then
	  max bestr (radius p.(a.(0)) p.(a.(1)) p.(a.(2))) else bestr
	in
	  loop bestr f
  in
  let bestr = loop (-1.0) (delaunay p n) in
    if bestr < 0.0 then Printf.printf "-1\n" else Printf.printf "%.6f\n" bestr


There are three horses living in a horse land: one gray, one white and one gray-and-white. The horses are really amusing animals, which is why they adore special cards. Each of those cards must contain two integers, the first one on top, the second one in the bottom of the card. Let's denote a card with a on the top and b in the bottom as (a, b).Each of the three horses can paint the special cards. If you show an (a, b) card to the gray horse, then the horse can paint a new (a + 1, b + 1) card. If you show an (a, b) card, such that a and b are even integers, to the white horse, then the horse can paint a new  card. If you show two cards (a, b) and (b, c) to the gray-and-white horse, then he can paint a new (a, c) card.Polycarpus really wants to get n special cards (1, a1), (1, a2), ..., (1, an). For that he is going to the horse land. He can take exactly one (x, y) card to the horse land, such that 1 ≤ x < y ≤ m. How many ways are there to choose the card so that he can perform some actions in the horse land and get the required cards?Polycarpus can get cards from the horses only as a result of the actions that are described above. Polycarpus is allowed to get additional cards besides the cards that he requires.

The first line contains two integers n, m (1 ≤ n ≤ 105, 2 ≤ m ≤ 109). The second line contains the sequence of integers a1, a2, ..., an (2 ≤ ai ≤ 109). Note, that the numbers in the sequence can coincide. The numbers in the lines are separated by single spaces.

Print a single integer — the answer to the problem.  Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

let ( |> ) x f = f x
let ( <| ) f x = f x

let foi = float_of_int
let iof = int_of_float

let next_int () = Scanf.scanf "%d%c" (fun x _ -> x)
let next_flt () = Scanf.scanf "%f%c" (fun x _ -> x)

let seq n =
  let rec aux n acc =
	if n = 0 then acc
	else aux (n-1) (n :: acc) in
  aux n []

let rec show_flt_list x =
  match x with
	  [] -> print_newline ()
	| x::xs -> print_float x; print_string " "; show_flt_list xs

let rec show_int_list x =
  match x with
	  [] -> print_newline ()
	| x::xs -> print_int x; print_string " "; show_int_list xs

let rec loop n f acc =
  if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)

let rec gcd x y =
  if y = 0 then x else gcd y (x mod y)
;;

let n = next_int ()
let m = next_int ()

let a = loop n (fun _ -> (next_int()) - 1) []
let d = List.fold_left gcd (List.hd a) a

let calc x =
  let m = Int64.of_int m in
  let rec aux acc x =
	if x >= m then acc
	else aux (Int64.add acc (Int64.sub m x)) (Int64.add x x) in
  aux (Int64.zero) (Int64.of_int x)

let get_dvsr () =
  let up = iof (sqrt (foi d)) in
  let rec aux n acc =
	if n > up then acc
	else
	  if d mod n = 0 then
		if n * n <> d then aux (n + 1) (n :: (d/n) :: acc)
		else aux (n + 1) (n :: acc)
	  else
		aux (n + 1) acc
  in
  aux 1 []

let () =
  Printf.printf "%Ld" (
	List.filter (fun x -> x mod 2 = 1) (get_dvsr () )
						  |> List.fold_left (fun acc y -> Int64.add acc (calc y)) Int64.zero)

let ( |> ) x f = f x
let ( <| ) f x = f x

let foi = float_of_int
let iof = int_of_float

let next_int () = Scanf.scanf "%d%c" (fun x _ -> x)
let next_flt () = Scanf.scanf "%f%c" (fun x _ -> x)

let seq n =
  let rec aux n acc =
	if n = 0 then acc
	else aux (n-1) (n :: acc) in
  aux n []

let rec show_flt_list x =
  match x with
	  [] -> print_newline ()
	| x::xs -> print_float x; print_string " "; show_flt_list xs

let rec show_int_list x =
  match x with
	  [] -> print_newline ()
	| x::xs -> print_int x; print_string " "; show_int_list xs

let rec loop n f acc =
  if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)

let rec gcd x y =
  if y = 0 then x else gcd y (x mod y)
;;

let n = next_int ()
let m = next_int ()

let a = loop n (fun _ -> (next_int()) - 1) []
let d = List.fold_left gcd (List.hd a) a

let calc x =
  let m = Int64.of_int m in
  let rec aux acc x =
	if x >= m then acc
	else aux (Int64.add acc (Int64.sub m x)) (Int64.add x x) in
  aux (Int64.zero) (Int64.of_int x)

let get_dvsr () =
  let up = iof (sqrt (foi d)) in
  let rec aux n acc =
	if n > up then acc
	else
	  if d mod n = 0 then
		if n * n <> d then aux (n + 1) (n :: (d/n) :: acc)
		else aux (n + 1) (n :: acc)
	  else
		aux (n + 1) acc
  in
  aux 1 []

let () =
  List.filter (fun x -> x mod 2 = 1) (get_dvsr () )
	|> List.fold_left (fun acc y -> Int64.add acc (calc y)) Int64.zero
	|> Printf.printf "%Ld"

let ( |> ) x f = f x
let ( <| ) f x = f x

let foi = float_of_int
let iof = int_of_float

let next_int () = Scanf.scanf "%d%c" (fun x _ -> x)
let next_flt () = Scanf.scanf "%f%c" (fun x _ -> x)

let seq n =
  let rec aux n acc =
	if n = 0 then acc
	else aux (n-1) (n :: acc) in
  aux n []

let rec show_flt_list x =
  match x with
	  [] -> print_newline ()
	| x::xs -> print_float x; print_string " "; show_flt_list xs

let rec show_int_list x =
  match x with
	  [] -> print_newline ()
	| x::xs -> print_int x; print_string " "; show_int_list xs

let rec loop n f acc =
  if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)

let rec gcd x y =
  if x mod y = 0 then y else gcd y (x mod y)
;;

let n = next_int ()
let m = next_int ()

let a = loop n (fun _ -> (next_int()) - 1) []
let d = List.fold_left gcd (List.hd a) a

let calc x =
  let m = Int64.of_int m in
  let rec aux acc x =
	if x >= m then acc
	else aux (Int64.add acc (Int64.sub m x)) (Int64.add x x) in
  aux (Int64.zero) (Int64.of_int x)

let get_dvsr () =
  let up = iof (sqrt (foi d)) in
  let rec aux n acc =
	if n > up then acc
	else
	  if d mod n = 0 then
		if n * n <> d then aux (n + 1) (n :: (d/n) :: acc)
		else aux (n + 1) (n :: acc)
	  else
		aux (n + 1) acc
  in
  aux 1 []

let () =
  List.filter (fun x -> x mod 2 = 1) (get_dvsr () )
	|> List.fold_left (fun acc y -> Int64.add acc (calc y)) Int64.zero
	|> Printf.printf "%Ld"

let ( |> ) x f = f x
let ( <| ) f x = f x

let foi = float_of_int
let iof = int_of_float

let next_int () = Scanf.scanf "%d%c" (fun x _ -> x)
let next_flt () = Scanf.scanf "%f%c" (fun x _ -> x)

let seq n =
  let rec aux n acc =
	if n = 0 then acc
	else aux (n-1) (n :: acc) in
  aux n []

let rec show_flt_list x =
  match x with
	  [] -> print_newline ()
	| x::xs -> print_float x; print_string " "; show_flt_list xs

let rec show_int_list x =
  match x with
	  [] -> print_newline ()
	| x::xs -> print_int x; print_string " "; show_int_list xs

let rec loop n f acc =
  if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)

let rec gcd x y =
  if x mod y = 0 then y else gcd y (x mod y)
;;

let n = next_int ()
let m = next_int ()

(* let () =
  print_newline(); print_int n; print_newline (); print_int m; print_newline()
*)

let a = loop n (fun _ -> (next_int()) - 1) []
let d = List.fold_left gcd (List.hd a) a

let chk y =
  let rec aux acc x =
	if x >= m then acc
	else aux (acc + m - x) (2 * x) in
  aux 0 y

let calc x =
  let m = Int64.of_int m in
  let rec aux acc x =
	if x >= m then acc
	else aux (Int64.add acc (Int64.sub m x)) (Int64.add x x) in
  aux (Int64.zero) (Int64.of_int x)

let get_dvsr () =
  let up = iof (sqrt (foi d)) in
  let rec aux n acc =
	if n > up then acc
	else
	  if d mod n = 0 then
		if n * n <> d then aux (n + 1) (n :: (d/n) :: acc)
		else aux (n + 1) (n :: acc)
	  else
		aux (n + 1) acc
  in
  aux 1 []

let () =
  Printf.printf "%Ld" (
	List.filter (fun x -> x mod 2 = 1) (get_dvsr () )
						  |> List.map calc
						  |> List.fold_left (fun x y -> Int64.add x y) Int64.zero)

let ( |> ) x f = f x
let ( <| ) f x = f x

let foi = float_of_int
let iof = int_of_float

let next_int () = Scanf.scanf "%d%c" (fun x _ -> x)
let next_flt () = Scanf.scanf "%f%c" (fun x _ -> x)

let seq n =
  let rec aux n acc =
	if n = 0 then acc
	else aux (n-1) (n :: acc) in
  aux n []

let rec show_flt_list x =
  match x with
	  [] -> print_newline ()
	| x::xs -> print_float x; print_string " "; show_flt_list xs

let rec loop n f acc =
  if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)

let rec gcd x y =
  if x mod y = 0 then y else gcd y (x mod y)
;;

let n = next_int ()
let m = next_int ()

(* let () =
  print_newline(); print_int n; print_newline (); print_int m; print_newline()
*)

let a = loop n (fun _ -> (next_int()) - 1) []
let d = List.fold_left gcd (List.hd a) a

let chk y =
  let rec aux acc x =
	if x >= m then acc
	else aux (acc + m - x) (2 * x) in
  aux 0 y

let calc x =
  let mm = Int64.of_int (min m 800000000) in
  let rec aux acc x =
	if x >= mm then acc
	else aux (Int64.add acc (Int64.sub mm x)) (Int64.add x x) in
  aux (Int64.zero) (Int64.of_int x)

let () =
  Printf.printf "%Ld" (List.filter (fun x -> x mod 2 = 1 && d mod x = 0) (seq d)
	|> List.map calc
	|> List.fold_left (fun x y -> Int64.add x y) Int64.zero)

let ( |> ) x f = f x
let ( <| ) f x = f x

let foi = float_of_int
let iof = int_of_float

let next_int () = Scanf.scanf "%d%c" (fun x _ -> x)
let next_flt () = Scanf.scanf "%f%c" (fun x _ -> x)

let seq n =
  let rec aux n acc =
	if n = 0 then acc
	else aux (n-1) (n :: acc) in
  aux n []

let rec show_flt_list x =
  match x with
	  [] -> print_newline ()
	| x::xs -> print_float x; print_string " "; show_flt_list xs

let rec loop n f acc =
  if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)

let rec gcd x y =
  if x mod y = 0 then y else gcd y (x mod y)
;;

let n = next_int ()
let m = next_int ()

(* let () =
  print_newline(); print_int n; print_newline (); print_int m; print_newline()
*)

let a = loop n (fun _ -> (next_int()) - 1) []
let d = List.fold_left gcd (List.hd a) a

let chk y =
  let rec aux acc x =
	if x >= m then acc
	else aux (acc + m - x) (2 * x) in
  aux 0 y

let calc x =
  let mm = min m 500000011 in
  let rec aux acc x =
	if x >= mm then acc
	else aux (acc +. foi (mm - x)) (2 * x) in
  aux 0. x

let () =
  Printf.printf "%.0f" (List.filter (fun x -> x mod 2 = 1 && d mod x = 0) (seq d)
	|> List.map calc
	|> List.fold_left (+.) 0.)

let ( |> ) x f = f x
let ( <| ) f x = f x

let foi = float_of_int
let iof = int_of_float

let next_int () = Scanf.scanf "%d%c" (fun x _ -> x)
let next_flt () = Scanf.scanf "%f%c" (fun x _ -> x)

let seq n =
  let rec aux n acc =
	if n = 0 then acc
	else aux (n-1) (n :: acc) in
  aux n []

let rec show_flt_list x =
  match x with
	  [] -> print_newline ()
	| x::xs -> print_float x; print_string " "; show_flt_list xs

let rec loop n f acc =
  if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)

let rec gcd x y =
  if x mod y = 0 then y else gcd y (x mod y)
;;

let n = next_int ()
let m = next_int ()

(* let () =
  print_newline(); print_int n; print_newline (); print_int m; print_newline()
*)

let a = loop n (fun _ -> (next_int()) - 1) []
let d = List.fold_left gcd (List.hd a) a

let chk y =
  let rec aux acc x =
	if x >= m then acc
	else aux (acc + m - x) (2 * x) in
  aux 0 y

let calc x =
  let mm = min m 1000011 in
  let rec aux acc x =
	if x >= mm then acc
	else aux (acc + mm - x) (2 * x) in
  aux 0 x

let () =
  List.filter (fun x -> x mod 2 = 1 && d mod x = 0) (seq d)
	|> List.map calc
	|> List.fold_left (+) 0
	|> print_int

let ( |> ) x f = f x
let ( <| ) f x = f x

let foi = float_of_int
let iof = int_of_float

let next_int () = Scanf.scanf "%d%c" (fun x _ -> x)
let next_flt () = Scanf.scanf "%f%c" (fun x _ -> x)

let seq n =
  let rec aux n acc =
	if n = 0 then acc
	else aux (n-1) (n :: acc) in
  aux n []

let rec show_flt_list x =
  match x with
	  [] -> print_newline ()
	| x::xs -> print_float x; print_string " "; show_flt_list xs

let rec loop n f acc =
  if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)

let rec gcd x y =
  if x mod y = 0 then y else gcd y (x mod y)
;;

let n = next_int ()
let m = next_int ()

(* let () =
  print_newline(); print_int n; print_newline (); print_int m; print_newline()
*)

let a = loop n (fun _ -> (next_int()) - 1) []
let d = List.fold_left gcd (List.hd a) a

let chk y =
  let rec aux acc x =
	if x >= m then acc
	else aux (acc + m - x) (2 * x) in
  aux 0 y

let calc x =
  let mm = min m 10011 in
  let rec aux acc x =
	if x >= mm then acc
	else aux (acc + mm - x) (2 * x) in
  aux 0 x

let () =
  List.filter (fun x -> x mod 2 = 1 && d mod x = 0) (seq d)
	|> List.map calc
	|> List.fold_left (+) 0
	|> print_int

let ( |> ) x f = f x
let ( <| ) f x = f x

let foi = float_of_int
let iof = int_of_float

let next_int () = Scanf.scanf "%d%c" (fun x _ -> x)
let next_flt () = Scanf.scanf "%f%c" (fun x _ -> x)

let seq n =
  let rec aux n acc =
	if n = 0 then acc
	else aux (n-1) (n :: acc) in
  aux n []

let rec show_flt_list x =
  match x with
	  [] -> print_newline ()
	| x::xs -> print_float x; print_string " "; show_flt_list xs

let rec loop n f acc =
  if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)

let rec gcd x y =
  if x mod y = 0 then y else gcd y (x mod y)
;;

let n = next_int ()
let m = next_int ()

(* let () =
  print_newline(); print_int n; print_newline (); print_int m; print_newline()
*)

let a = loop n (fun _ -> (next_int()) - 1) []
let d = List.fold_left gcd (List.hd a) a

let chk y =
  let rec aux acc x =
	if x >= m then acc
	else aux (acc + m - x) (2 * x) in
  aux 0 y

let calc x =
  let mm = min m 100000011 in
  let rec aux acc x =
	if x >= mm then acc
	else aux (acc + mm - x) (2 * x) in
  aux 0 x

let () =
  List.filter (fun x -> x mod 2 = 1 && d mod x = 0) (seq d)
	|> List.map calc
	|> List.fold_left (+) 0
	|> print_int

let ( |> ) x f = f x
let ( <| ) f x = f x

let foi = float_of_int
let iof = int_of_float

let next_int () = Scanf.scanf "%d%c" (fun x _ -> x)
let next_flt () = Scanf.scanf "%f%c" (fun x _ -> x)

let seq n =
  let rec aux n acc =
	if n = 0 then acc
	else aux (n-1) (n :: acc) in
  aux n []

let rec show_flt_list x =
  match x with
	  [] -> print_newline ()
	| x::xs -> print_float x; print_string " "; show_flt_list xs

let rec loop n f acc =
  if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)

let rec gcd x y =
  if x mod y = 0 then y else gcd y (x mod y)
;;

let n = next_int ()
let m = next_int ()

(* let () =
  print_newline(); print_int n; print_newline (); print_int m; print_newline()
*)

let a = loop n (fun _ -> (next_int()) - 1) []
let d = List.fold_left gcd (List.hd a) a

let chk y =
  let rec aux acc x =
	if x >= m then acc
	else aux (acc + m - x) (2 * x) in
  aux 0 y

let calc x =
  let mm = min m 500000011 in
  let rec aux acc x =
	if x >= mm then acc
	else aux (acc + mm - x) (2 * x) in
  aux 0 x

let () =
  List.filter (fun x -> x mod 2 = 1 && d mod x = 0) (seq d)
	|> List.map calc
	|> List.fold_left (+) 0
	|> print_int

let ( |> ) x f = f x
let ( <| ) f x = f x

let foi = float_of_int
let iof = int_of_float

let next_int () = Scanf.scanf "%d%c" (fun x _ -> x)
let next_flt () = Scanf.scanf "%f%c" (fun x _ -> x)

let seq n =
  let rec aux n acc =
	if n = 0 then acc
	else aux (n-1) (n :: acc) in
  aux n []

let rec show_flt_list x =
  match x with
	  [] -> print_newline ()
	| x::xs -> print_float x; print_string " "; show_flt_list xs

let rec loop n f acc =
  if n = 0 then List.rev acc else loop (n-1) f ((f n) :: acc)

let rec gcd x y =
  if x mod y = 0 then y else gcd y (x mod y)
;;

let n = next_int ()
let m = next_int ()

(* let () =
  print_newline(); print_int n; print_newline (); print_int m; print_newline()
*)

let a = loop n (fun _ -> (next_int()) - 1) []
let d = List.fold_left gcd (List.hd a) a

let chk y =
  let rec aux acc x =
	if x >= m then acc
	else aux (acc + m - x) (2 * x) in
  aux 0 y

let calc x =
  let mm = min m 100011 in
  let rec aux acc x =
	if x >= mm then acc
	else aux (acc + mm - x) (2 * x) in
  aux 0 x

let () =
  List.filter (fun x -> x mod 2 = 1 && d mod x = 0) (seq d)
	|> List.map calc
	|> List.fold_left (+) 0
	|> print_int


City X consists of n vertical and n horizontal infinite roads, forming n × n intersections. Roads (both vertical and horizontal) are numbered from 1 to n, and the intersections are indicated by the numbers of the roads that form them.Sand roads have long been recognized out of date, so the decision was made to asphalt them. To do this, a team of workers was hired and a schedule of work was made, according to which the intersections should be asphalted.Road repairs are planned for n2 days. On the i-th day of the team arrives at the i-th intersection in the list and if none of the two roads that form the intersection were already asphalted they asphalt both roads. Otherwise, the team leaves the intersection, without doing anything with the roads.According to the schedule of road works tell in which days at least one road will be asphalted.

The first line contains integer n (1 ≤ n ≤ 50) — the number of vertical and horizontal roads in the city.  Next n2 lines contain the order of intersections in the schedule. The i-th of them contains two numbers hi, vi (1 ≤ hi, vi ≤ n), separated by a space, and meaning that the intersection that goes i-th in the timetable is at the intersection of the hi-th horizontal and vi-th vertical roads. It is guaranteed that all the intersections in the timetable are distinct.

In the single line print the numbers of the days when road works will be in progress in ascending order. The days are numbered starting from 1.

NoteIn the sample the brigade acts like that:  On the first day the brigade comes to the intersection of the 1-st horizontal and the 1-st vertical road. As none of them has been asphalted, the workers asphalt the 1-st vertical and the 1-st horizontal road;  On the second day the brigade of the workers comes to the intersection of the 1-st horizontal and the 2-nd vertical road. The 2-nd vertical road hasn't been asphalted, but as the 1-st horizontal road has been asphalted on the first day, the workers leave and do not asphalt anything;  On the third day the brigade of the workers come to the intersection of the 2-nd horizontal and the 1-st vertical road. The 2-nd horizontal road hasn't been asphalted but as the 1-st vertical road has been asphalted on the first day, the workers leave and do not asphalt anything;  On the fourth day the brigade come to the intersection formed by the intersection of the 2-nd horizontal and 2-nd vertical road. As none of them has been asphalted, the workers asphalt the 2-nd vertical and the 2-nd horizontal road.

open Printf
open Scanf

let () =
    let n =  read_int() in
    let arrv : bool array = Array.create n false in
    let arrh : bool array = Array.create n false in
    for i = 1 to n*n do
        let h, v = scanf "%d %d\n" (fun x y -> x, y) in
    if not (arrh.(h-1) || arrv.(v-1)) then begin
       arrh.(h-1) <- true;
       arrv.(v-1) <- true;
       printf "%d " i
    end;
    printf "\n%!"
done

let () = Scanf.scanf "%d\n" (fun n ->
    let h = Array.make n false
    and v = Array.make n false in
    for i = 1 to n*n do
        Scanf.scanf "%d %d\n" (fun x y ->
            if not (h.(x - 1) || v.(y - 1)) then begin
                h.(x - 1) <- true;
                v.(y - 1) <- true;
                Printf.printf "%d " i
            end)
    done)

open Printf
open Scanf

let () =
  let n = read_int () in
  let vert : bool array = Array.create n false in
  let horz : bool array = Array.create n false in
  for i = 1 to n * n do
    let h, v = scanf "%d %d\n" (fun x y -> x - 1, y - 1) in
    if not (horz.(h) || vert.(v)) then begin
      horz.(h) <- true;
      vert.(v) <- true;
      printf "%d " i
    end;
    printf "\n%!"
  done


There is a famous olympiad, which has more than a hundred participants. The Olympiad consists of two stages: the elimination stage, and the final stage. At least a hundred participants will advance to the final stage. The elimination stage in turn consists of two contests.A result of the elimination stage is the total score in two contests, but, unfortunately, the jury lost the final standings and has only standings for the first and for the second contest separately. In each contest, the participants are ranked by their point score in non-increasing order. When two participants have a tie (earned the same score), they are ranked by their passport number (in accordance with local regulations, all passport numbers are distinct). In the first contest, the participant on the 100-th place scored $$$a$$$ points. Also, the jury checked all participants from the 1-st to the 100-th place (inclusive) in the first contest and found out that all of them have at least $$$b$$$ points in the second contest.Similarly, for the second contest, the participant on the 100-th place has $$$c$$$ points. And the jury checked that all the participants from the 1-st to the 100-th place (inclusive) have at least $$$d$$$ points in the first contest.After two contests, all participants are ranked by their total score in two contests in non-increasing order. When participants have the same total score, tie-breaking with passport numbers is used. The cutoff score to qualify to the final stage is the total score of the participant on the 100-th place.Given integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$, please help the jury determine the smallest possible value of the cutoff score.

You need to process $$$t$$$ test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 3025$$$) — the number of test cases. Then descriptions of $$$t$$$ test cases follow. The first line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0 \le a,\,b,\,c,\,d \le 9$$$; $$$d \leq a$$$; $$$b \leq c$$$).  One can show that for any test case satisfying the constraints above, there is at least one olympiad scenario possible.

For each test case print a single integer — the smallest possible cutoff score in some olympiad scenario satisfying the given information.

NoteFor the first test case, consider the following olympiad scenario: there are $$$101$$$ participants in the elimination stage, each having $$$1$$$ point for the first contest and $$$2$$$ points for the second contest. Hence the total score of the participant on the 100-th place is $$$3$$$.For the second test case, consider the following olympiad scenario:   there are $$$50$$$ participants with points $$$5$$$ and $$$9$$$ for the first and second contest respectively;  $$$50$$$ participants with points $$$4$$$ and $$$8$$$ for the first and second contest respectively;  and $$$50$$$ participants with points $$$2$$$ and $$$9$$$ for the first and second contest respectively.  Hence the total point score of the participant on the 100-th place is $$$12$$$.

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

let () =
  let t = read_int () in
  let solve a b c d =
    max (a + b) (d + c)
  in
  for i = 1 to t do
    let a = read_int () in
    let b = read_int () in
    let c = read_int () in
    let d = read_int () in
    Printf.printf "%d\n" (solve a b c d)
  done


Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits begin to march, so it is only important how many soldiers march in step.There will be n columns participating in the parade, the i-th column consists of li soldiers, who start to march from left leg, and ri soldiers, who start to march from right leg.The beauty of the parade is calculated by the following formula: if L is the total number of soldiers on the parade who start to march from the left leg, and R is the total number of soldiers on the parade who start to march from the right leg, so the beauty will equal |L - R|.No more than once you can choose one column and tell all the soldiers in this column to switch starting leg, i.e. everyone in this columns who starts the march from left leg will now start it from right leg, and vice versa. Formally, you can pick no more than one index i and swap values li and ri. Find the index of the column, such that switching the starting leg for soldiers in it will maximize the the beauty of the parade, or determine, that no such operation can increase the current beauty.

The first line contains single integer n (1 ≤ n ≤ 105) — the number of columns.  The next n lines contain the pairs of integers li and ri (1 ≤ li, ri ≤ 500) — the number of soldiers in the i-th column which start to march from the left or the right leg respectively.

Print single integer k — the number of the column in which soldiers need to change the leg from which they start to march, or 0 if the maximum beauty is already reached. Consider that columns are numbered from 1 to n in the order they are given in the input data. If there are several answers, print any of them.

NoteIn the first example if you don't give the order to change the leg, the number of soldiers, who start to march from the left leg, would equal 5 + 8 + 10 = 23, and from the right leg — 6 + 9 + 3 = 18. In this case the beauty of the parade will equal |23 - 18| = 5.If you give the order to change the leg to the third column, so the number of soldiers, who march from the left leg, will equal 5 + 8 + 3 = 16, and who march from the right leg — 6 + 9 + 10 = 25. In this case the beauty equals |16 - 25| = 9.It is impossible to reach greater beauty by giving another orders. Thus, the maximum beauty that can be achieved is 9.

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

let () =
  let n = read_int () in
  let rec loop
      neg_max neg_max_index neg_sum
      pos_max pos_max_index pos_sum i =
    if i > n then
      begin
        if (pos_max - neg_sum) > (pos_sum - neg_max) then pos_max_index
        else neg_max_index
      end
    else
      begin
        let l = read_int () and r = read_int () in
        let diff = l - r in
        if diff < 0 then
          begin
            if (diff < neg_max) then
              loop
                diff i (neg_sum + diff)
                pos_max pos_max_index pos_sum
                (i + 1)
            else
              loop
                neg_max neg_max_index (neg_sum + diff)
                pos_max pos_max_index pos_sum (i + 1)
          end
        else if diff > 0 then
          begin
            if (diff > pos_max) then
              loop
                neg_max neg_max_index neg_sum
                diff i (pos_sum + diff) (i + 1)
            else
              loop
                neg_max neg_max_index neg_sum
                pos_max pos_max_index (pos_sum + diff)
                (i + 1)
          end
        else
          loop
            neg_max neg_max_index neg_sum
            pos_max pos_max_index pos_sum (i + 1)
      end
  in
  loop 0 0 0 0 0 0 1 |> Printf.printf "%d"

let solve n ds =
  let beauty = List.fold_left ( + ) 0 ds in
  let rec loop best index i = function
    | [] -> index
    | d :: ds ->
      let b = abs (beauty - 2 * d) in
      if b > best then
        loop b i (i - 1) ds
      else
        loop best index (i - 1) ds
  in loop (abs beauty) 0 n ds

let () =
  Scanf.scanf "%d " @@ fun n ->
  let ds =
    let rec loop acc = function
      | 0 -> acc
      | n ->
        let d = Scanf.scanf "%d %d\n" @@ ( - ) in
        loop (d :: acc) (n - 1)
    in loop [] n in
  solve n ds |> string_of_int |> print_endline


Let's define a multiplication operation between a string $$$a$$$ and a positive integer $$$x$$$: $$$a \cdot x$$$ is the string that is a result of writing $$$x$$$ copies of $$$a$$$ one after another. For example, "abc" $$$\cdot~2~=$$$ "abcabc", "a" $$$\cdot~5~=$$$ "aaaaa".A string $$$a$$$ is divisible by another string $$$b$$$ if there exists an integer $$$x$$$ such that $$$b \cdot x = a$$$. For example, "abababab" is divisible by "ab", but is not divisible by "ababab" or "aa".LCM of two strings $$$s$$$ and $$$t$$$ (defined as $$$LCM(s, t)$$$) is the shortest non-empty string that is divisible by both $$$s$$$ and $$$t$$$.You are given two strings $$$s$$$ and $$$t$$$. Find $$$LCM(s, t)$$$ or report that it does not exist. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of test cases. Each test case consists of two lines, containing strings $$$s$$$ and $$$t$$$ ($$$1 \le |s|, |t| \le 20$$$). Each character in each of these strings is either 'a' or 'b'.

For each test case, print $$$LCM(s, t)$$$ if it exists; otherwise, print -1. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.

NoteIn the first test case, "baba" = "baba" $$$\cdot~1~=$$$ "ba" $$$\cdot~2$$$.In the second test case, "aaaaaa" = "aa" $$$\cdot~3~=$$$ "aaa" $$$\cdot~2$$$.

open Str
open Big_int
open Num

let multitest = true

module Shortcuts = struct
  let loop n f = for i = 0 to n - 1 do f i; done

end

module Helper = struct
  open Shortcuts

  let read_s () = Scanf.scanf "%s\n" (fun x -> x)

  let read_int ?endl () =
    match endl with
    | None -> Scanf.scanf "%d " (fun x -> x)
    | Some () -> Scanf.scanf "%d\n" (fun x -> x)

  let read_array n =
    let a = Array.make n 0 in
    loop (n-1) (fun i -> a.(i) <- read_int ());
    a.(n-1) <- read_int ~endl:() ();
    a

end

module Ext = struct
  module List = struct
    let rec make n x =
      if (n <= 0) then []
      else x :: make (n-1) x

  end

end

module Alg = struct
  let rec gcd x y =
    if y <> 0 then (gcd y (x mod y))
    else (abs x)

  let lcm x y =
    if x = 0 || y = 0 then 0
    else abs (x * y) / (gcd x y)

end

let solve _ =
  let open Shortcuts in
  let open Helper in
  let open Printf in
  let open Ext in
  let open Alg in
  (* ***** Solution code here ***** *)
  let s = read_s () in
  let t = read_s () in
  let sl = String.length s in
  let tl = String.length t in
  let lcm = lcm sl tl in
  let ss = String.concat "" (List.make (lcm / sl) s) in
  let tt = String.concat "" (List.make (lcm / tl) t) in
  if (ss = tt) then printf "%s\n" ss
  else printf "-1\n";
  (* ***** ******************* ***** *)
;;

let () =
  let open Helper in
  let open Shortcuts in
  let t = if multitest then read_int ~endl:() () else 1 in
  loop t solve;;


New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as total length of roads on the path between city u and city v.As an annual event, people in Tree World repairs exactly one road per year. As a result, the length of one road decreases. It is already known that in the i-th year, the length of the ri-th road is going to become wi, which is shorter than its length before. Assume that the current year is year 1.Three Santas are planning to give presents annually to all the children in Tree World. In order to do that, they need some preparation, so they are going to choose three distinct cities c1, c2, c3 and make exactly one warehouse in each city. The k-th (1 ≤ k ≤ 3) Santa will take charge of the warehouse in city ck.It is really boring for the three Santas to keep a warehouse alone. So, they decided to build an only-for-Santa network! The cost needed to build this network equals to d(c1, c2) + d(c2, c3) + d(c3, c1) dollars. Santas are too busy to find the best place, so they decided to choose c1, c2, c3 randomly uniformly over all triples of distinct numbers from 1 to n. Santas would like to know the expected value of the cost needed to build the network.However, as mentioned, each year, the length of exactly one road decreases. So, the Santas want to calculate the expected after each length change. Help them to calculate the value.

The first line contains an integer n (3 ≤ n ≤ 105) — the number of cities in Tree World. Next n - 1 lines describe the roads. The i-th line of them (1 ≤ i ≤ n - 1) contains three space-separated integers ai, bi, li (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ li ≤ 103), denoting that the i-th road connects cities ai and bi, and the length of i-th road is li. The next line contains an integer q (1 ≤ q ≤ 105) — the number of road length changes. Next q lines describe the length changes. The j-th line of them (1 ≤ j ≤ q) contains two space-separated integers rj, wj (1 ≤ rj ≤ n - 1, 1 ≤ wj ≤ 103). It means that in the j-th repair, the length of the rj-th road becomes wj. It is guaranteed that wj is smaller than the current length of the rj-th road. The same road can be repaired several times.

Output q numbers. For each given change, print a line containing the expected cost needed to build the network in Tree World. The answer will be considered correct if its absolute and relative error doesn't exceed 10 - 6.

NoteConsider the first sample. There are 6 triples: (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1). Because n = 3, the cost needed to build the network is always d(1, 2) + d(2, 3) + d(3, 1) for all the triples. So, the expected cost equals to d(1, 2) + d(2, 3) + d(3, 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.0

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

let () =
  let n = read_int () in

  let tree = Array.make n [] in
  let len = Array.make (n-1) 0.0 in
  let size = Array.make n 0 in
  let coeff = Array.make (n-1) 0.0 in
  let edge = Array.make (n-1) (0,0) in

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

  let q = read_int() in

  let changes = Array.make q (0, 0.0) in

  for i=0 to q-1 do
    let r = read_int() -1 in
    let w = read_int() in
    changes.(i) <- (r, float w)
  done;

  let rec dfs u p =
    size.(u) <- List.fold_left (fun t v ->
      if v = p then t else t + (dfs v u)
    ) 1 tree.(u);
    size.(u)
  in

  if dfs 0 (-1) <> n then failwith "bad dfs";

  for e = 0 to n-2 do
    let (a,b) = edge.(e) in
    let se = float (min size.(a) size.(b)) in
    let fn = float n in
    coeff.(e) <- 2.0 *. (se *. (fn -. se)) /. (fn *. (fn -. 1.0))
  done;

  let exp_pair_dist = ref 0.0 in

  exp_pair_dist := sum 0 (n-2) (fun e -> len.(e) *. coeff.(e));

  for i=0 to q-1 do
    let (e,newweight) = changes.(i) in
    exp_pair_dist := !exp_pair_dist +. (newweight -. len.(e)) *. coeff.(e);
    len.(e) <- newweight;
    printf "%.10f\n" (3.0 *. !exp_pair_dist)
  done;

open Printf
open Scanf

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

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

let () =
  let n = read_int () in

  let tree = Array.make n [] in
  let len = Array.make (n-1) 0.0 in
  let size = Array.make n 0 in
  let coeff = Array.make (n-1) 0.0 in
  let edge = Array.make (n-1) (0,0) in

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

  let q = read_int() in

  let changes = Array.make q (0, 0.0) in

  for i=0 to q-1 do
    let r = read_int() -1 in
    let w = read_int() in
    changes.(i) <- (r, float w)
  done;

  let rec dfs u p =
    size.(u) <- List.fold_left (fun t v ->
      if v = p then t else t + (dfs v u)
    ) 1 tree.(u);
    size.(u)
  in

  if dfs 0 (-1) <> n then failwith "bad dfs";

  for e = 0 to n-2 do
    let (a,b) = edge.(e) in
    let se = min size.(a) size.(b) in
    coeff.(e) <- 2.0 *. (float (se * (n - se))) /. (float (n * (n-1)))
  done;

  let exp_pair_dist = ref 0.0 in

  exp_pair_dist := sum 0 (n-2) (fun e -> len.(e) *. coeff.(e));

  for i=0 to q-1 do
    let (e,newweight) = changes.(i) in
    exp_pair_dist := !exp_pair_dist +. (newweight -. len.(e)) *. coeff.(e);
    len.(e) <- newweight;
    printf "%.10f\n" (3.0 *. !exp_pair_dist)
  done;