Every Codeforces user has rating, described with one integer, possibly negative or zero. Users are divided into two divisions. The first division is for users with rating 1900 or higher. Those with rating 1899 or lower belong to the second division. In every contest, according to one's performance, his or her rating changes by some value, possibly negative or zero.Limak competed in n contests in the year 2016. He remembers that in the i-th contest he competed in the division di (i.e. he belonged to this division just before the start of this contest) and his rating changed by ci just after the contest. Note that negative ci denotes the loss of rating.What is the maximum possible rating Limak can have right now, after all n contests? If his rating may be arbitrarily big, print "Infinity". If there is no scenario matching the given information, print "Impossible".

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000). The i-th of next n lines contains two integers ci and di ( - 100 ≤ ci ≤ 100, 1 ≤ di ≤ 2), describing Limak's rating change after the i-th contest and his division during the i-th contest contest.

If Limak's current rating can be arbitrarily big, print "Infinity" (without quotes). If the situation is impossible, print "Impossible" (without quotes). Otherwise print one integer, denoting the maximum possible value of Limak's current rating, i.e. rating after the n contests.

NoteIn the first sample, the following scenario matches all information Limak remembers and has maximum possible final rating:  Limak has rating 1901 and belongs to the division 1 in the first contest. His rating decreases by 7.  With rating 1894 Limak is in the division 2. His rating increases by 5.  Limak has rating 1899 and is still in the division 2. In the last contest of the year he gets  + 8 and ends the year with rating 1907. In the second sample, it's impossible that Limak is in the division 1, his rating increases by 57 and after that Limak is in the division 2 in the second contest.

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

let ( $ ) f x = f x

let main () =
  let n = ref (read_int ()) in
  let l = ref (-123456789) in
  let r = ref 123456789 in
  let a, b = ref 0, ref 0 in
  for i = 1 to !n do
    a := read_int();
    b := read_int();
    if !b = 1 then
      l := max !l 1900
    else
      r := min !r 1899;
    l := (!l + !a);
    r := (!r + !a);
  done;
  if !l > !r then Printf.printf "Impossible"
  else if !r > 100000000 then Printf.printf "Infinity"
  else Printf.printf "%d" !r

let () = main ()

open Printf
open Scanf

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

let () =
  let n = read_int () in

  let inf = 1_000_000_000 in

  let (++) a b = if abs a = inf then a else a+b in

  let rec loop i (lo,hi) = if i=n then (lo,hi) else
      let (c,div) = read_pair() in
      let hi = if div = 2 then min hi 1899 else hi in
      let lo = if div = 1 then max lo 1900 else lo in
      let lo = lo ++ c in
      let hi = hi ++ c in
      if lo > hi then (lo,hi)
      else loop (i+1) (lo,hi)
  in

  let (lo,hi) = loop 0 (-inf,inf) in

  if lo > hi then printf "Impossible\n"
  else if hi = inf then printf "Infinity\n"
  else printf "%d\n" hi

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

let ( $ ) f x = f x

let main () =
  let n = ref (read_int ()) in
  let l = ref (-min_int) in
  let r = ref max_int in
  let a, b = ref 0, ref 0 in
  for i = 1 to !n do
    a := read_int();
    b := read_int();
    if !b = 1 then
      l := max !l 1900
    else
      r := min !r 1899;
    l := (!l + !a);
    r := (!r + !a);
  done;
  if !l > !r then Printf.printf "Impossible"
  else if !r > 100000000 then Printf.printf "Infinity"
  else Printf.printf "%d" !r

let () = main ()


Malek has recently found a treasure map. While he was looking for a treasure he found a locked door. There was a string s written on the door consisting of characters '(', ')' and '#'. Below there was a manual on how to open the door. After spending a long time Malek managed to decode the manual and found out that the goal is to replace each '#' with one or more ')' characters so that the final string becomes beautiful. Below there was also written that a string is called beautiful if for each i (1 ≤ i ≤ |s|) there are no more ')' characters than '(' characters among the first i characters of s and also the total number of '(' characters is equal to the total number of ')' characters. Help Malek open the door by telling him for each '#' character how many ')' characters he must replace it with.

The first line of the input contains a string s (1 ≤ |s| ≤ 105). Each character of this string is one of the characters '(', ')' or '#'. It is guaranteed that s contains at least one '#' character.

If there is no way of replacing '#' characters which leads to a beautiful string print  - 1. Otherwise for each character '#' print a separate line containing a positive integer, the number of ')' characters this character must be replaced with. If there are several possible answers, you may output any of them.

Note|s| denotes the length of the string s.

let s = read_line ();;
let l = Str.split (Str.regexp "") s;;

let rec balance op = function (* returns to_close net_closed *)
| _ when op < 0 -> (-1, -1, [])
| [] -> (op, 0, [])
| "(" :: xs ->
    let (o, n, ys) = balance (op + 1) xs in
    if (n <= 0) then
        (o, n+1, ys)
    else
        (-1, -1, [])
| ")" :: xs ->
    let (o, n, ys) = balance (op - 1) xs in
    if (n <= 0) then
        (o, n-1, ys)
    else
        (-1, -1, [])
| "#" :: xs ->
    let (o, n, ys) = balance (op - 1) xs in
    if (o >= 0 && n <= 0) then
        (0, n - (o+1), (o+1) :: ys)
    else
        (-1, -1, [])
| _ -> assert false;;

let (o, n, xs) = balance 0 l;;
if o <> 0 then
    print_newline (print_string "-1")
else
    List.iter (fun x -> print_newline (print_int x)) xs

let s = read_line ();;
let l = Str.split (Str.regexp "") s;;

let rec balance op = function (* returns to_close *)
| _ when op < 0 -> (-1, [])
| [] -> (op, [])
| "(" :: xs -> balance (op + 1) xs
| ")" :: xs -> balance (op - 1) xs
| "#" :: xs ->
    let (n, ys) = balance (op - 1) xs
    in
        if (n >= 0) then
            (0, (n+1) :: ys)
        else
            (-1, []);;

let (n, xs) = balance 0 l;;
if n <> 0 then
    print_newline (print_string "-1")
else
    List.iter (fun x -> print_newline (print_int x)) xs

let s = read_line ();;
let l = Str.split (Str.regexp "") s;;

let rec balance op = function (* returns to_close net_closed *)
| _ when op < 0 -> (-1, -1, [])
| [] -> (op, 0, [])
| "(" :: xs -> let (o, n, ys) = balance (op + 1) xs in (o, n+1, ys)
| ")" :: xs -> let (o, n, ys) = balance (op - 1) xs in (o, n-1, ys)
| "#" :: xs ->
    let (o, n, ys) = balance (op - 1) xs
    in
        if (o >= 0 && n <= 0) then
            (0, 0, (o+1) :: ys)
        else
            (-1, -1, []);;

let (o, n, xs) = balance 0 l;;
if o <> 0 then
    print_newline (print_string "-1")
else
    List.iter (fun x -> print_newline (print_int x)) xs

let s = read_line ();;
let l = Str.split (Str.regexp "") s;;

let rec balance op = function (* returns to_close net_closed *)
| _ when op < 0 -> (-1, -1, [])
| [] -> (op, 0, [])
| "(" :: xs -> let (o, n, ys) = balance (op + 1) xs in (o, n+1, ys)
| ")" :: xs -> let (o, n, ys) = balance (op - 1) xs in (o, n-1, ys)
| "#" :: xs ->
    let (o, n, ys) = balance (op - 1) xs
    in
        if (o >= 0 && n <= 0) then
            (0, n - (o+1), (o+1) :: ys)
        else
            (-1, -1, [])
| _ -> assert false;;

let (o, n, xs) = balance 0 l;;
if o <> 0 then
    print_newline (print_string "-1")
else
    List.iter (fun x -> print_newline (print_int x)) xs

let s = read_line ();;
let l = Str.split (Str.regexp "") s;;

let rec balance op net = function (* returns to_close net_closed *)
| _ when op < 0 -> (-1, -1, [])
| [] -> (op, net, [])
| "(" :: xs -> balance (op + 1) 1 xs
| ")" :: xs -> balance (op - 1) (-1) xs
| "#" :: xs ->
    let (o, n, ys) = balance (op - 1) 0 xs
    in
        if (o >= 0 && n <= 0) then
            (0, 0, (o+1) :: ys)
        else
            (-1, -1, []);;

let (o, n, xs) = balance 0 0 l;;
if o <> 0 then
    print_newline (print_string "-1")
else
    List.iter (fun x -> print_newline (print_int x)) xs


Not so long ago, Vlad came up with an interesting function: $$$f_a(x)=\left\lfloor\frac{x}{a}\right\rfloor + x \bmod a$$$, where $$$\left\lfloor\frac{x}{a}\right\rfloor$$$ is $$$\frac{x}{a}$$$, rounded down, $$$x \bmod a$$$ — the remainder of the integer division of $$$x$$$ by $$$a$$$.For example, with $$$a=3$$$ and $$$x=11$$$, the value $$$f_3(11) = \left\lfloor\frac{11}{3}\right\rfloor + 11 \bmod 3 = 3 + 2 = 5$$$.The number $$$a$$$ is fixed and known to Vlad. Help Vlad find the maximum value of $$$f_a(x)$$$ if $$$x$$$ can take any integer value from $$$l$$$ to $$$r$$$ inclusive ($$$l \le x \le r$$$).

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of input test cases. This is followed by $$$t$$$ lines, each of which contains three integers $$$l_i$$$, $$$r_i$$$ and $$$a_i$$$ ($$$1 \le l_i \le r_i \le 10^9, 1 \le a_i \le 10^9$$$) — the left and right boundaries of the segment and the fixed value of $$$a$$$.

For each test case, output one number on a separate line — the maximum value of the function on a given segment for a given $$$a$$$.

NoteIn the first sample:  $$$f_3(1) = \left\lfloor\frac{1}{3}\right\rfloor + 1 \bmod 3 = 0 + 1 = 1$$$,  $$$f_3(2) = \left\lfloor\frac{2}{3}\right\rfloor + 2 \bmod 3 = 0 + 2 = 2$$$,  $$$f_3(3) = \left\lfloor\frac{3}{3}\right\rfloor + 3 \bmod 3 = 1 + 0 = 1$$$,  $$$f_3(4) = \left\lfloor\frac{4}{3}\right\rfloor + 4 \bmod 3 = 1 + 1 = 2$$$ As an answer, obviously, $$$f_3(2)$$$ and $$$f_3(4)$$$ are suitable.

let hasMax l r a = r-l+1 >= a || (r mod a < l mod a) ;;

let searchMax r a = let toto = r/a in if r mod a = a-1 then (toto + a-1) else toto-1 + a -1;;

let n = int_of_string(input_line stdin) in
for i = 0 to n-1 do
  let l,r,a = Scanf.sscanf(input_line stdin)" %d  %d  %d"(fun l r a->l,r,a) in
  let toto = if hasMax l r a then searchMax r a else (r/a + r mod a) in
  print_endline (string_of_int toto)
done;
;;

(* Codeforces 1638 A Reverse train done *)

(* you can use either gr or rdln but not both, several gr() - inverted order *)
let gr () = Scanf.scanf " %d" (fun i -> i);;
let grf () = Scanf.scanf " %f" (fun i -> i);;
let grl () = Scanf.scanf " %Ld" (fun i -> i);;
let rdln() = input_line stdin;;
(* let spli s = Str.split (Str.regexp " ") s;; *)
let printlisti li = List.iter (fun i -> (print_int i; print_string " ")) li;;
let printarri ai = Array.iter (fun i -> (print_int i; print_string " ")) ai;;
let debug = false;;

(* reading list *)
let rec readlist n acc = match n with
	| 0 -> List.rev acc
	| _ -> readlist (n -1) (gr() :: acc);;
let printlisti li = List.iter (fun i -> (print_int i; print_string " ")) li;;
let printlists ls = List.iter (fun s -> (print_string s; print_string " ")) ls;;
let list_to_s li = String.concat " " (List.map string_of_int li);;

let do_one () =
    let a,r,l = gr(), gr(), gr() in
    (* let _ = Printf.printf "l,r,a = %d %d %d\n" l r a in *)
    let dl = l / a in
    let dr = r / a in
    let oor = r mod a in
    let mx = if dl == dr then dr + oor
        else
            let dr1 = if oor==a-1 then dr else dr-1 in
            dr1 + a - 1 in
    (print_int mx; print_string "\n");;

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

let main() =
	do_all ();;

main();;

let hasMax l r a = r-l+1 >= a || (r mod a < l mod a) ;;

let searchMax r a = let toto = r/a in if r mod a = a-1 then (toto + a-1) else toto-1 + a -1;;

let n = int_of_string(input_line stdin) in
for i = 0 to n-1 do
  let l,r,a = Scanf.sscanf(input_line stdin)" %d  %d  %d"(fun l r a->l,r,a) in
  let toto = if hasMax l r a then searchMax r a else (r/a + r mod a) in
  prerr_endline (string_of_int toto)
done;
;;


CQXYM is counting permutations length of $$$2n$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).A permutation $$$p$$$(length of $$$2n$$$) will be counted only if the number of $$$i$$$ satisfying $$$p_i<p_{i+1}$$$ is no less than $$$n$$$. For example:  Permutation $$$[1, 2, 3, 4]$$$ will count, because the number of such $$$i$$$ that $$$p_i<p_{i+1}$$$ equals $$$3$$$ ($$$i = 1$$$, $$$i = 2$$$, $$$i = 3$$$). Permutation $$$[3, 2, 1, 4]$$$ won't count, because the number of such $$$i$$$ that $$$p_i<p_{i+1}$$$ equals $$$1$$$ ($$$i = 3$$$). CQXYM wants you to help him to count the number of such permutations modulo $$$1000000007$$$ ($$$10^9+7$$$).In addition, modulo operation is to get the remainder. For example:  $$$7 \mod 3=1$$$, because $$$7 = 3 \cdot 2 + 1$$$,  $$$15 \mod 4=3$$$, because $$$15 = 4 \cdot 3 + 3$$$.

The input consists of multiple test cases.  The first line contains an integer $$$t (t \geq 1)$$$ — the number of test cases. The description of the test cases follows. Only one line of each test case contains an integer $$$n(1 \leq n \leq 10^5)$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$

For each test case, print the answer in a single line.

(* OCaml template *)
open Printf
open Scanf

(* Redefine operators for Int64 *)
let ( + ) = Int64.add;;
let ( - ) = Int64.sub;;
let ( * ) = Int64.mul;;
let ( / ) = Int64.div;;
let ( % ) = Int64.rem;;

(* Input *)
let read_int _ = bscanf Scanning.stdin "%d " @@ fun x -> x;;
let read_int64 _ = bscanf Scanning.stdin "%Ld " @@ fun x -> x;;

(* Output *)
let print_int n = printf "%d " n;;
let print_int_endl n = printf "%d\n" n;;
let print_int64 n = printf "%Ld " n;;
let print_int64_endl n = printf "%Ld\n" n;;

(* Utility functions *)
(*
let sum = List.fold_left (+) 0;;
*)

(* Solve test case *)
let rec solve n = if n = 2L then 1L else n * solve (n - 1L) % 1000000007L;;

(* Main *)
let t = read_int ();;

for t' = 1 to t do
	(* Solve test case here *)
	let n = read_int64 () in
		print_int64_endl @@ solve @@ 2L * n
done

(* OCaml template *)

(* Redefine operators for Int64 *)
let ( + ) = Int64.add;;
let ( - ) = Int64.sub;;
let ( * ) = Int64.mul;;
let ( / ) = Int64.div;;
let ( % ) = Int64.rem;;

(* Utility functions *)
let sum = List.fold_left (+) 0L;;

(* Main *)
let m = 1000000007L;;

let rec solve (n:int64) = if n = 2L then 1L else n * solve (n - 1L) % m;;

let t = read_int ();;

for t' = 1 to t do
	(* Solve test case here *)
	let n = read_int () in
		print_endline @@ Int64.to_string @@ solve @@ 2L * Int64.of_int n
done

(* OCaml template *)

(* Utility functions *)
let sum = List.fold_left (+) 0;;

(* Main *)
let m = 1000000007L;;

let rec solve (n:int64) = if n = 2L then 1L else Int64.rem (Int64.mul n (solve (Int64.pred n))) m;;

let t = read_int ();;

for t' = 1 to t do
	(* Solve test case here *)
	let n = read_int () in
		print_endline @@ Int64.to_string @@ solve @@ Int64.mul 2L (Int64.of_int n)
done

(* OCaml template *)

type int = int64;;

(* Utility functions *)
let print_int_endline n = print_endline @@ string_of_int n
let sum = List.fold_left (+) 0;;

let rec solve n = if n = 2 then 1 else n * solve (n - 1) mod 1000000007;;

(* Main *)
let t = read_int ();;

for t' = 1 to t do
	(* Solve test case here *)
	let n = read_int () in
		print_int_endline @@ solve @@ 2 * n
done

(* OCaml template *)

(* Utility functions *)
let sum = List.fold_left (+) 0;;

(* Main *)
let m = 1000000007;;

let rec solve (n:int) = if n = 2 then 1 else n * solve (n - 1) mod m;;

let t = read_int ();;

for t' = 1 to t do
	(* Solve test case here *)
	let n = read_int () in
		print_endline @@ string_of_int @@ solve @@ 2 * n;
done


Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant.Shop, where Noora is working, has a plan on the following n days. For each day sales manager knows exactly, that in i-th day ki products will be put up for sale and exactly li clients will come to the shop that day. Also, the manager is sure, that everyone, who comes to the shop, buys exactly one product or, if there aren't any left, leaves the shop without buying anything. Moreover, due to the short shelf-life of the products, manager established the following rule: if some part of the products left on the shelves at the end of the day, that products aren't kept on the next day and are sent to the dump.For advertising purposes manager offered to start a sell-out in the shop. He asked Noora to choose any f days from n next for sell-outs. On each of f chosen days the number of products were put up for sale would be doubled. Thus, if on i-th day shop planned to put up for sale ki products and Noora has chosen this day for sell-out, shelves of the shop would keep 2·ki products. Consequently, there is an opportunity to sell two times more products on days of sell-out.Noora's task is to choose f days to maximize total number of sold products. She asks you to help her with such a difficult problem.

The first line contains two integers n and f (1 ≤ n ≤ 105, 0 ≤ f ≤ n) denoting the number of days in shop's plan and the number of days that Noora has to choose for sell-out. Each line of the following n subsequent lines contains two integers ki, li (0 ≤ ki, li ≤ 109) denoting the number of products on the shelves of the shop on the i-th day and the number of clients that will come to the shop on i-th day.

Print a single integer denoting the maximal number of products that shop can sell.

NoteIn the first example we can choose days with numbers 2 and 4 for sell-out. In this case new numbers of products for sale would be equal to [2, 6, 2, 2] respectively. So on the first day shop will sell 1 product, on the second — 5, on the third — 2, on the fourth — 2. In total 1 + 5 + 2 + 2 = 10 product units.In the second example it is possible to sell 5 products, if you choose third day for sell-out.

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 sum i j f = fold i j (fun i a -> (f i) ++ a) 0L

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

let () =
  let n = read_int () in
  let f = read_int () in
  let day = Array.init n read_pair in

  let value i =
    let (k,l) = day.(i) in
    min l k
  in

  let delta i =
    let (k,l) = day.(i) in
    let before = min l k in
    let after = min l (2L ** k) in
    (after -- before, i)
  in

  let gain = Array.init n delta in

  Array.sort (fun a b -> compare b a) gain;

  let answer = sum 0 (n-1) (fun i -> (if i<f then fst gain.(i) else 0L) ++ (value i)) in

  printf "%Ld\n" answer


In an ICPC contest, balloons are distributed as follows:   Whenever a team solves a problem, that team gets a balloon.  The first team to solve a problem gets an additional balloon.  A contest has 26 problems, labelled $$$\textsf{A}$$$, $$$\textsf{B}$$$, $$$\textsf{C}$$$, ..., $$$\textsf{Z}$$$. You are given the order of solved problems in the contest, denoted as a string $$$s$$$, where the $$$i$$$-th character indicates that the problem $$$s_i$$$ has been solved by some team. No team will solve the same problem twice.Determine the total number of balloons that the teams received. Note that some problems may be solved by none of the teams.

The first line of the input contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of testcases. The first line of each test case contains an integer $$$n$$$ ($$$1 \leq n \leq 50$$$) — the length of the string. The second line of each test case contains a string $$$s$$$ of length $$$n$$$ consisting of uppercase English letters, denoting the order of solved problems.

For each test case, output a single integer — the total number of balloons that the teams received.

6

3

ABA

1

A

3

ORZ

5

BAAAA

4

BKPT

10

CODEFORCES

NoteIn the first test case, $$$5$$$ balloons are given out:   Problem $$$\textsf{A}$$$ is solved. That team receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\textsf{A}$$$.  Problem $$$\textsf{B}$$$ is solved. That team receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\textsf{B}$$$.  Problem $$$\textsf{A}$$$ is solved. That team receives only $$$1$$$ balloon, because they solved the problem. Note that they don't get an additional balloon because they are not the first team to solve problem $$$\textsf{A}$$$.  The total number of balloons given out is $$$2+2+1=5$$$.In the second test case, there is only one problem solved. The team who solved it receives $$$2$$$ balloons: one because they solved the problem, an an additional one because they are the first team to solve problem $$$\textsf{A}$$$.

(* From @Darooha's code (https://codeforces.com/profile/Darooha) *)

open Printf
open Scanf

let ( ** ) a b = Int64.mul a b
let ( ++ ) a b = Int64.add a b
let long x = Int64.of_int x
let short x = Int64.to_int x

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

(* Main Code file *)

let rec sum = function
        | [] -> 0
        | h::t -> if h then sum(t) + 1 else sum(t)

let () =
    let exist str i =
        String.contains str (char_of_int (i + 65))
    in
    let n = read_int() in
    for i=1 to n do
        let len = read_int() in
        let x = read_string() in
        let arr = Array.init 26 (exist x) in
        printf "%d\n" (len + (sum (Array.to_list arr)))
    done;


The Little Elephant has two permutations a and b of length n, consisting of numbers from 1 to n, inclusive. Let's denote the i-th (1 ≤ i ≤ n) element of the permutation a as ai, the j-th (1 ≤ j ≤ n) element of the permutation b — as bj.The distance between permutations a and b is the minimum absolute value of the difference between the positions of the occurrences of some number in a and in b. More formally, it's such minimum |i - j|, that ai = bj.A cyclic shift number i (1 ≤ i ≤ n) of permutation b consisting from n elements is a permutation bibi + 1... bnb1b2... bi - 1. Overall a permutation has n cyclic shifts.The Little Elephant wonders, for all cyclic shifts of permutation b, what is the distance between the cyclic shift and permutation a?

The first line contains a single integer n (1 ≤ n ≤ 105) — the size of the permutations. The second line contains permutation a as n distinct numbers from 1 to n, inclusive. The numbers are separated with single spaces. The third line contains permutation b in the same format.

In n lines print n integers — the answers for cyclic shifts. Print the answers to the shifts in the order of the shifts' numeration in permutation b, that is, first for the 1-st cyclic shift, then for the 2-nd, and so on.

module IntPairSet = Set.Make(
  struct
    type t = int * int
    (*let compare ((x, x') : int * int) (y, y') =
      if x < y
      then -1
      else if x > y
      then 1
      else 0*)
    let compare = compare
  end
)
(*
module IntSet = Set.Make(
  struct
    type t = int
    let compare (x : int) y =
      if x < y
      then -1
      else if x > y
      then 1
      else 0
  end
)
*)

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let b = Array.make n 0 in
  let ra = Array.make n 0 in
  let rb = Array.make n 0 in
  let d = Array.make n 0 in
  let f = ref IntPairSet.empty in
  let g = ref IntPairSet.empty in
  let () =
    for i = 0 to n - 1 do
      let k = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
	a.(i) <- k;
	ra.(k) <- i;
    done;
    for i = 0 to n - 1 do
      let k = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
	b.(i) <- k;
	rb.(k) <- i;
    done;
    for i = 0 to n - 1 do
      d.(i) <- rb.(a.(i)) - i;
      if d.(i) < 0
      then f := IntPairSet.add (d.(i), i) !f
      else g := IntPairSet.add (d.(i), i) !g
    done
  in
    for i = 0 to n - 1 do
      (try
	 while fst (IntPairSet.min_elt !g) - i < 0 do
	   let k = IntPairSet.min_elt !g in
	     g := IntPairSet.remove k !g;
	     f := IntPairSet.add k !f;
	 done;
       with
	 | Not_found -> ()
      );
      (*(try
	 while fst (IntPairSet.min_elt !f) - i <= -n do
	   let (x, y) as k = IntPairSet.min_elt !f in
	     f := IntPairSet.remove k !f;
	     g := IntPairSet.add (x + n, y) !g;
	 done;
       with
	 | Not_found -> ()
      );*)
      if i <> 0 then (
	try
	  let x = ra.(b.(i - 1)) in
	  let k = (d.(x), x) in
	    f := IntPairSet.remove k !f;
	    g := IntPairSet.add (d.(x) + n, x) !g;
	with
	  | Not_found -> assert false
      );
      let k1 =
	try
	  fst (IntPairSet.min_elt !g) - i
	with
	  | Not_found -> n + 1
      in
      let k2 =
	try
	  -(fst (IntPairSet.max_elt !f) - i)
	with
	  | Not_found -> n + 1
      in
	(*IntPairSet.iter (fun (k, y) -> Printf.printf "f %d %d\n" k y) !f;
	IntPairSet.iter (fun (k, y) -> Printf.printf "g %d %d\n" k y) !g;
	Printf.printf "kk %d %d\n" k1 k2;*)
      let res = min k1 k2 in
	Printf.printf "%d\n" res
    done

module IntSet = Set.Make(
  struct
    type t = int
    let compare (x : int) y =
      if x < y
      then -1
      else if x > y
      then 1
      else 0
  end
)

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let b = Array.make n 0 in
  let ra = Array.make n 0 in
  let rb = Array.make n 0 in
  let d = Array.make n 0 in
  let f = ref IntSet.empty in
  let g = ref IntSet.empty in
  let () =
    for i = 0 to n - 1 do
      let k = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
	a.(i) <- k;
	ra.(k) <- i;
    done;
    for i = 0 to n - 1 do
      let k = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
	b.(i) <- k;
	rb.(k) <- i;
    done;
    for i = 0 to n - 1 do
      d.(i) <- rb.(i) - ra.(i);
      if d.(i) < 0
      then f := IntSet.add d.(i) !f
      else g := IntSet.add d.(i) !g
    done
  in
    for i = 0 to n - 1 do
      (try
	 while IntSet.min_elt !g - i < 0 do
	   let k = IntSet.min_elt !g in
	     g := IntSet.remove k !g;
	     f := IntSet.add k !f;
	 done;
       with
	 | Not_found -> ()
      );
      (try
	 while IntSet.min_elt !f - i <= -n do
	   let k = IntSet.min_elt !f in
	     f := IntSet.remove k !f;
	     g := IntSet.add (k + n) !g;
	 done;
       with
	 | Not_found -> ()
      );
      let k1 =
	try
	  IntSet.min_elt !g - i
	with
	  | Not_found -> n + 1
      in
      let k2 =
	try
	  -(IntSet.max_elt !f - i)
	with
	  | Not_found -> n + 1
      in
      let res = min k1 k2 in
	Printf.printf "%d\n" res
    done


Little walrus Fangy loves math very much. That's why when he is bored he plays with a number performing some operations.Fangy takes some positive integer x and wants to get a number one from it. While x is not equal to 1, Fangy repeats the following action: if x is odd, then he adds 1 to it, otherwise he divides x by 2. Fangy knows that for any positive integer number the process ends in finite time.How many actions should Fangy perform to get a number one from number x?

The first line contains a positive integer x in a binary system. It is guaranteed that the first digit of x is different from a zero and the number of its digits does not exceed 106.

NoteLet's consider the third sample. Number 101110 is even, which means that we should divide it by 2. After the dividing Fangy gets an odd number 10111 and adds one to it. Number 11000 can be divided by 2 three times in a row and get number 11. All that's left is to increase the number by one (we get 100), and then divide it by 2 two times in a row. As a result, we get 1.

let len = ref 0;;
let c0 = ref 0;;
let c1 = ref 0;;
let m = ref (0-1);;
try while true do
	let c = input_byte stdin - 48 in
	(if 10 - 48 = c then raise End_of_file ;
	incr (if c = 0 then c0 else c1);
	if c = 1 then m := (0-1) else incr m)
done with _ -> ();;

if (!c1) = 1 then begin
	print_int (!c0);
	exit 0
end;;

print_int ((!c0)*2+(!c1)-(!m));;

let read_bin () =
	let x = Stack.create () in
	let _ = (String.iter (fun c ->
		Stack.push (if c = '0' then 0 else 1) x
	) (read_line())) in x
;;

let rec inc_bin x =
	let y = try Stack.pop x with _ -> 0 in
	if y = 0 then begin
		Stack.push 1 x
	end else begin
		inc_bin x;
		Stack.push 0 x
	end
;;

let div2_bin x =
	ignore(Stack.pop x)
;;

let () =
	let i = ref 0 in
	let x = Stack.create () in
        let _ = (String.iter (fun c ->
                if c = '0' && Stack.top x = 0 then (incr i; incr i)
			else Stack.push (if c = '0' then 0 else 1) x
        ) (read_line())) in
	let _ = (while Stack.length x <> 1 || Stack.top x <> 1 do
		if Stack.top x = 1 then inc_bin x else div2_bin x;
		incr i
	done) in print_int (!i)
;;


And again a misfortune fell on Poor Student. He is being late for an exam.Having rushed to a bus stop that is in point (0, 0), he got on a minibus and they drove along a straight line, parallel to axis OX, in the direction of increasing x.Poor Student knows the following:   during one run the minibus makes n stops, the i-th stop is in point (xi, 0)  coordinates of all the stops are different  the minibus drives at a constant speed, equal to vb  it can be assumed the passengers get on and off the minibus at a bus stop momentarily  Student can get off the minibus only at a bus stop  Student will have to get off the minibus at a terminal stop, if he does not get off earlier  the University, where the exam will be held, is in point (xu, yu)  Student can run from a bus stop to the University at a constant speed vs as long as needed  a distance between two points can be calculated according to the following formula:   Student is already on the minibus, so, he cannot get off at the first bus stop Poor Student wants to get to the University as soon as possible. Help him to choose the bus stop, where he should get off. If such bus stops are multiple, choose the bus stop closest to the University.

The first line contains three integer numbers: 2 ≤ n ≤ 100, 1 ≤ vb, vs ≤ 1000. The second line contains n non-negative integers in ascending order: coordinates xi of the bus stop with index i. It is guaranteed that x1 equals to zero, and xn ≤ 105. The third line contains the coordinates of the University, integers xu and yu, not exceeding 105 in absolute value.

In the only line output the answer to the problem — index of the optimum bus stop.

NoteAs you know, students are a special sort of people, and minibuses usually do not hurry. That's why you should not be surprised, if Student's speed is higher than the speed of the minibus.

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

let () =
  let n = read_int 0 in
  let vb = read_float 0 in
  let vs = read_float 0 in
  let a = Array.init n read_float in
  let x = read_float 0 in
  let y = read_float 0 in
  let rec go i (mit,mid,mii as mi) =
    if i = n then
      mi
    else
      let d = (a.(i)-.x)**2.0 +. y*.y |> sqrt in
      let t = a.(i)/.vb+.d/.vs in
      if t < mit || t = mit && d < mid then
        go (i+1) (t,d,i)
      else
        go (i+1) mi
  in
  let _,_,i = go 1 (1e9,1e9,-1) in
  Printf.printf "%d\n" (i+1)


Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up $$$q$$$ questions about this song. Each question is about a subsegment of the song starting from the $$$l$$$-th letter to the $$$r$$$-th letter. Vasya considers a substring made up from characters on this segment and repeats each letter in the subsegment $$$k$$$ times, where $$$k$$$ is the index of the corresponding letter in the alphabet. For example, if the question is about the substring "abbcb", then Vasya repeats letter 'a' once, each of the letters 'b' twice, letter 'c" three times, so that the resulting string is "abbbbcccbb", its length is $$$10$$$. Vasya is interested about the length of the resulting string.Help Petya find the length of each string obtained by Vasya.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1\leq n\leq 100\,000$$$, $$$1\leq q \leq 100\,000$$$) — the length of the song and the number of questions.  The second line contains one string $$$s$$$ — the song, consisting of $$$n$$$ lowercase letters of English letters. Vasya's questions are contained in the next $$$q$$$ lines. Each line contains two integers $$$l$$$ and $$$r$$$ ($$$1 \leq l \leq r \leq n$$$) — the bounds of the question.

Print $$$q$$$ lines: for each question print the length of the string obtained by Vasya.

NoteIn the first example Vasya is interested in three questions. In the first question Vasya considers the substring "aba", that transforms to "abba", so the answer is equal to $$$4$$$. In the second question Vasya considers "baca", that transforms to "bbaccca", so the answer is $$$7$$$. In the third question Vasya considers the string "abacaba",that transforms to "abbacccabba" of length $$$11$$$.

let scan_int () = Scanf.scanf " %d" (fun x -> x)
let to_array s = Array.init (String.length s) (
  fun t ->
    (int_of_char (String.get s t)) - (int_of_char 'a') + 1
  )
let scan_string () = Scanf.scanf " %s" (fun s -> to_array s)
let cal_pre a =
  for i = 1 to (Array.length a) - 1 do
    a.(i) <- a.(i) + a.(i - 1)
  done;
  Array.append [|0|] a

let n = scan_int ()
let q = scan_int ()
let pre = cal_pre (scan_string());;

for i = 1 to q do
  let l = scan_int() in
  let r = scan_int() in
  Printf.printf "%d\n" (pre.(r) - pre.(l - 1))
done


You are given an array a consisting of n integers. You have to process q queries to this array; each query is given as four numbers l, r, x and y, denoting that for every i such that l ≤ i ≤ r and ai = x you have to set ai equal to y.Print the array after all queries are processed.

The first line contains one integer n (1 ≤ n ≤ 200000) — the size of array a. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100) — the elements of array a. The third line contains one integer q (1 ≤ q ≤ 200000) — the number of queries you have to process. Then q lines follow. i-th line contains four integers l, r, x and y denoting i-th query (1 ≤ l ≤ r ≤ n, 1 ≤ x, y ≤ 100).

Print n integers — elements of array a after all changes are made.

module Ints =
  struct
    type t = int
    let compare = Pervasives.compare
  end;;

module IntSet = Set.Make(Ints);;

let indexes_of_values =
  Array.make 101 IntSet.empty;;

let rev_split_on_char sep s =
  let len = String.length s in
  let rec aux first_index acc =
    if first_index = len then
      acc
    else
      try
        let i = String.index_from s first_index sep in
        aux (i + 1) ((String.sub s first_index (i - first_index)) :: acc)
      with Not_found -> (String.sub s first_index (len - first_index)) :: acc
  in
  aux 0 []

let read_line_of_ints () =
  let line = read_line () in
  let items = rev_split_on_char ' ' line in
  List.rev_map int_of_string items;;

let affect first_index last_index former_value new_value =
  let former_value_indexes = Array.get indexes_of_values former_value in
  let (smaller_indexes_set, first_is_former, matching_and_higher) = IntSet.split first_index former_value_indexes in
  let (matching_indexes_set, last_is_former, higher_indexes_set) = IntSet.split last_index matching_and_higher in
  Array.set indexes_of_values former_value (IntSet.union smaller_indexes_set higher_indexes_set);
  let new_values_old_set = Array.get indexes_of_values new_value in
  let new_values_new_set = IntSet.union new_values_old_set matching_indexes_set in
  let new_values_new_with_last = if last_is_former then IntSet.add last_index new_values_new_set else new_values_new_set in
  let final_new_values = if first_is_former then IntSet.add first_index new_values_new_with_last else new_values_new_with_last in
  Array.set indexes_of_values new_value final_new_values;;

let n = read_int ();;
let a = read_line_of_ints ();;
(* TODO: put initial values in the indexes thing *)
List.iteri (fun i x -> Array.set indexes_of_values x (IntSet.add i indexes_of_values.(x))) a;;
let queries_count = read_int ();;
for i = 1 to queries_count do
  let l :: r :: x :: y :: [] = read_line_of_ints () in
  affect (l - 1) (r - 1) x y
done;;
let final_array = Array.make n (-1);;
for i = 1 to 100 do
  IntSet.iter (fun j -> Array.set final_array j i) indexes_of_values.(i)
done;;
Array.iter (fun x -> print_int x; print_char ' ') final_array;;
print_newline ();;


The array a with n integers is given. Let's call the sequence of one or more consecutive elements in a segment. Also let's call the segment k-good if it contains no more than k different values.Find any longest k-good segment.As the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

The first line contains two integers n, k (1 ≤ k ≤ n ≤ 5·105) — the number of elements in a and the parameter k. The second line contains n integers ai (0 ≤ ai ≤ 106) — the elements of the array a.

Print two integers l, r (1 ≤ l ≤ r ≤ n) — the index of the left and the index of the right ends of some k-good longest segment. If there are several longest segments you can print any of them. The elements in a are numbered from 1 to n from left to right.

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

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

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

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

let licz x = (x-|Int64.one)/|two_64;;

let _ =
  let (n,k) = Scanf.scanf "%d %d\n" (fun x y-> x, y) in
  let ile = Array.make 1000001 0
  and tab = Array.make 1000001 0
  and id = ref 1
  and wyn = ref 0
  and obc = ref 1
  and suma = ref 0 in
  for i=1 to n do
    let x = read (n-i) in
    tab.(i) <- x;
    if ile.(x) = 0 then incr suma;
    ile.(x) <- ile.(x) + 1;
    while !suma > k do
      ile.( tab.(!obc) ) <- ile.( tab.(!obc) ) - 1;
      if ile.( tab.(!obc) ) = 0 then suma := !suma - 1;
      incr obc
    done;
    if i - !obc + 1 > !wyn then begin
      id := !obc;
      wyn := i - !obc + 1
    end
  done;
  Printf.printf "%d %d\n" !id (!id + !wyn -1 ) ;;

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

let () =
  let n = xint() and k = xint() in
  let a = Array.make n 0 in
  let c = Array.make 1000001 0 in
  for i = 0 to n - 1 do
    a.(i) <- xint();
  done;
  let add x =
    c.(x) <- c.(x) + 1;
    if c.(x) = 1 then 1 else 0
  in
  let sub x =
    c.(x) <- c.(x) - 1;
    if c.(x) = 0 then 1 else 0;
  in
  let j = ref 0 and tot = ref 0 in
  let sx = ref 0 and sy = ref ~-1 in
  for i = 0 to n - 1 do
    tot := !tot + (add a.(i));
    while !tot > k do
      tot := !tot - (sub a.(!j));
      j := !j + 1;
    done;
    if i - !j > !sy - !sx then (
      sx := !j;
      sy := i;
    );
  done;
  sx := !sx + 1;
  sy := !sy + 1;
  Printf.printf "%d %d\n" !sx !sy;


Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise.Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time.

The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ n). Note that Xenia can have multiple consecutive tasks in one house.

Print a single integer — the time Xenia needs to complete all tasks. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units.

module My_int64 =
struct
    let ( + ) = Int64.add
    let ( - ) = Int64.sub
    let zero = Int64.zero
    let one = Int64.one
end

open My_int64

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

let input () =
    let houses = read () in
    let jobs = read () in
    let rec loop job_houses i =
        if i < jobs
        then
            let job_house = read () in
            loop (job_house :: job_houses) (i + one)
        else
            (houses, (List.rev job_houses))
    in loop [] zero

let solve (houses, job_houses) =
    let rec loop count last list =
        match list with
        | (head :: tail) ->
            if head < last
            then
                loop (count + (houses - last) + head) head tail
            else
                loop (count + head - last) head tail
        | [] -> count
    in loop zero one job_houses

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

let (n, m) = Scanf.scanf "%Ld %d\n" (fun x y -> (x, y)) in
let pos = ref Int64.one in
let t = ref Int64.zero in
for i = 1 to m do
    let p = Scanf.scanf "%Ld%[ ]" (fun x _ -> x) in
    t := Int64.add !t (Int64.rem (Int64.sub (Int64.add p n) !pos) n) ;
    pos := p
done ;
Printf.printf "%Ld\n" !t ;;

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

let input () =
    let houses = read () in
    let jobs = read () in
    let rec loop job_houses i =
        if i < jobs
        then
            let job_house = Scanf.scanf "%d " (fun n -> n) in
            loop (job_house :: job_houses) (i + 1)
        else
            (houses, jobs, (List.rev job_houses))
    in loop [] 0

let solve (houses, jobs, job_houses) =
    let rec loop count last list =
        match list with
        | (head :: tail) ->
            if head < last
            then
                loop (count + (houses - last) + head) head tail
            else
                loop (count + head - last) head tail
        | [] -> count
    in loop 0 1 job_houses

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


A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$:  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$.  $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$.  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$.  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain.

For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$.

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

let get_permutation = function
| (k, num_swaps) ->
     (* 1,2,3,4,5
        2,1,3,4,5
        2,3,1,4,5
        2,3,4,1,5
        2,3,4,5,1

        1=number of swaps index
        do rest in order , skipping
        the number of swaps index
     *)
     let rec iter_p = function
     | i ->
          if (i=k) then []
          else if (i<num_swaps) then
              (i+2)::(iter_p (i+1))
          else if (i>num_swaps) then
              (i+1)::(iter_p (i+1))
          else
               1::(iter_p (i+1))
     in iter_p (0)
;;

let run_case = function
| k ->
    print_int (k);
    print_newline ();
    let rec run_permutations = function
     | swaps ->
          if (swaps =k) then ()
          else begin
          let p = get_permutation (k, swaps) in
          let rec out_p = function
          | [] -> print_newline ()
          | x::xs ->
              Printf.printf "%d " x;
              out_p (xs)
          in out_p (p);
          run_permutations (swaps+1)
          end
     in run_permutations (0);
;;

let rec iter_cases = function
| 0 -> ()
| n ->
     let k = read_int () in
     run_case (k);
     iter_cases (n-1)
;;

let cases = read_int () in iter_cases (cases);;


Two people play the following string game. Initially the players have got some string s. The players move in turns, the player who cannot make a move loses. Before the game began, the string is written on a piece of paper, one letter per cell.  An example of the initial situation at s = "abacaba" A player's move is the sequence of actions:  The player chooses one of the available pieces of paper with some string written on it. Let's denote it is t. Note that initially, only one piece of paper is available.  The player chooses in the string t = t1t2... t|t| character in position i (1 ≤ i ≤ |t|) such that for some positive integer l (0 < i - l; i + l ≤ |t|) the following equations hold: ti - 1 = ti + 1, ti - 2 = ti + 2, ..., ti - l = ti + l.  Player cuts the cell with the chosen character. As a result of the operation, he gets three new pieces of paper, the first one will contain string t1t2... ti - 1, the second one will contain a string consisting of a single character ti, the third one contains string ti + 1ti + 2... t|t|.   An example of making action (i = 4) with string s = «abacaba» Your task is to determine the winner provided that both players play optimally well. If the first player wins, find the position of character that is optimal to cut in his first move. If there are multiple positions, print the minimal possible one.

The first line contains string s (1 ≤ |s| ≤ 5000). It is guaranteed that string s only contains lowercase English letters.

If the second player wins, print in the single line "Second" (without the quotes). Otherwise, print in the first line "First" (without the quotes), and in the second line print the minimal possible winning move — integer i (1 ≤ i ≤ |s|).

NoteIn the first sample the first player has multiple winning moves. But the minimum one is to cut the character in position 2. In the second sample the first player has no available moves.

(*
Subject: Re: CF 184 div 2 E (game theory problem)
Date: May 21, 2013 7:14:46 AM EDT

An allowed move is of the form:   a1 a2 ... an    --->    a1...ai -1              ai             a+1....an
as long as ai-1 = ai+1.  The middle piece is irrelevant because no future move can
be made there.   (This description of the allowed moves seems to differ from yours.)

There's an O(n^3) algorithm.   For every (i,j) we're going to compute the nimber
of the game ai....aj, using DP.  For a given string you try all the legal moves,
and look up the nimbers of the left and right part.  Take the xor of the two
parts.  And over all these options, take the MEX.  This gives you the nimber of
the string.

[[
The MEX of a set of numbers is the minimum excluded integer.
e.g. MEX(2,3,4,5)= 0.  MEX(0,1,2,3,5) = 4.

I'm attaching my 251 lecture which contains a description of this material
on sums of games in the following message
]]

If the nimber of the final string is 0 then then it's a Second player win, otherwise
it is a First player win.  In the latter case the winning move is any one that makes
the nimber be 0.

Since n=5000, the O(n^3) algorithm will be too slow.   So another trick is
needed.

Here's how to make this O(n^2).  Let's go through and mark all the positions
which admit a legal move at the beginning.  Let a 1 indicate the position is
legal to move and a 0 otherwise.  This pattern of zeros and ones completely
determines the game.

If two 1s are isolated, as in 01010, then those two moves are completely
independent.  (both moves can be made independently of the other).  The
same holds for any blocks of 1s.  So, 00111101110. has two separate
games, one  is "1111" and the other is "111".  So all that is required to figure
out the nimber of a game is to evaluate the nimbers of all the blocks of 1s
of various sizes.   When you make a move in a block of 1s, the move
splits the string in two, and removes up to two neighboring ones.  E.g. the
legal moves from 111111 are to 1111, 111, 1+11,11+1,111, 1111.

For each block length we just have to try all the moves, each of which splits
it into two blocks, and xor the parts together, then take the MEX (just like the
above algorithm).  The difference here is that only the length matters, not
the starting and ending points.  So it's O(n^2) to evaluate the nimber of
all block lengths up to n.

*)

open Printf

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

let solve n s =
  let bits = Array.init n (
    fun i -> if i=0 || i=n-1 then 0 else if s.[i-1] = s.[i+1] then 1 else 0
  ) in

  let rec find_blocks i j ac = if i=n then List.rev ac else
    (* j is the length of the block of 1s prior to this point *)
    if bits.(i) = 1 then find_blocks (i+1) (j+1) ac
    else find_blocks (i+1) 0 (if j>0 then (i-j,j)::ac else ac)
  in

  let blocks = find_blocks 0 0 [] in

(*
    List.iter (fun (p,j) -> printf "(%d,%d) " p j) blocks;
    print_newline()
*)

  let m = List.fold_left (fun ac (_,j) -> max ac j) 0 blocks in

  let nimber = Array.make (m+1) 0 in

  let mex_of_set s =
    let rec loop i = if Iset.mem i s then loop (i+1) else i in
      loop 0
  in

  let eval_move k j =
    let leftnimber = if k=0 then 0 else nimber.(k-1) in
    let rightnimber = if k=j-1 then 0 else nimber.(j-k-2) in
      leftnimber lxor rightnimber
  in

    for j=1 to m do
      let rec loop k s = if k=(j+1)/2 then s else
	  loop (k+1) (Iset.add (eval_move k j) s)
      in
      let s = loop 0 Iset.empty in
	nimber.(j) <- mex_of_set s;
(*	printf "nimber.(%d) = %d\n" j nimber.(j) *)
    done;

    let total_nimber = List.fold_left (fun ac (_,j) -> ac lxor nimber.(j)) 0 blocks in
      if total_nimber = 0 then 0 else
	let rec loop bl = match bl with
	  | [] -> failwith "should not happen"
	  | (p,j)::bl ->
	      let goal = total_nimber lxor nimber.(j) in
	      let rec findmove k = if k=(j+1)/2 then -1 else
		if eval_move k j = goal then k else findmove (k+1) in
	      let k = findmove 0 in
		if k<0 then loop bl else k+p+1
	in
	  loop blocks

let () =
  let s = read_line() in
  let n = String.length s in
  let k = solve n s in
    if k=0 then printf "Second\n"
    else printf "First\n%d\n" k

(*
Subject: Re: CF 184 div 2 E (game theory problem)
Date: May 21, 2013 7:14:46 AM EDT

An allowed move is of the form:   a1 a2 ... an    --->    a1...ai -1              ai             a+1....an
as long as ai-1 = ai+1.  The middle piece is irrelevant because no future move can
be made there.   (This description of the allowed moves seems to differ from yours.)

There's an O(n^3) algorithm.   For every (i,j) we're going to compute the nimber
of the game ai....aj, using DP.  For a given string you try all the legal moves,
and look up the nimbers of the left and right part.  Take the xor of the two
parts.  And over all these options, take the MEX.  This gives you the nimber of
the string.

[[
The MEX of a set of numbers is the minimum excluded integer.
e.g. MEX(2,3,4,5)= 0.  MEX(0,1,2,3,5) = 4.

I'm attaching my 251 lecture which contains a description of this material
on sums of games in the following message
]]

If the nimber of the final string is 0 then then it's a Second player win, otherwise
it is a First player win.  In the latter case the winning move is any one that makes
the nimber be 0.

Since n=5000, the O(n^3) algorithm will be too slow.   So another trick is
needed.

Here's how to make this O(n^2).  Let's go through and mark all the positions
which admit a legal move at the beginning.  Let a 1 indicate the position is
legal to move and a 0 otherwise.  This pattern of zeros and ones completely
determines the game.

If two 1s are isolated, as in 01010, then those two moves are completely
independent.  (both moves can be made independently of the other).  The
same holds for any blocks of 1s.  So, 00111101110. has two separate
games, one  is "1111" and the other is "111".  So all that is required to figure
out the nimber of a game is to evaluate the nimbers of all the blocks of 1s
of various sizes.   When you make a move in a block of 1s, the move
splits the string in two, and removes up to two neighboring ones.  E.g. the
legal moves from 111111 are to 1111, 111, 1+11,11+1,111, 1111.

For each block length we just have to try all the moves, each of which splits
it into two blocks, and xor the parts together, then take the MEX (just like the
above algorithm).  The difference here is that only the length matters, not
the starting and ending points.  So it's O(n^2) to evaluate the nimber of
all block lengths up to n.

*)

open Printf

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

let solve n s =
  let bits = Array.init n (
    fun i -> if i=0 || i=n-1 then 0 else if s.[i-1] = s.[i+1] then 1 else 0
  ) in

  let rec find_blocks i j ac = if i=n then List.rev ac else
    (* j is the length of the block of 1s prior to this point *)
    if bits.(i) = 1 then find_blocks (i+1) (j+1) ac
    else find_blocks (i+1) 0 (if j>0 then (i-j,j) ::ac else ac)
  in

  let blocks = find_blocks 0 0 [] in

(*
    List.iter (fun (p,j) -> printf "(%d,%d) " p j) blocks;
    print_newline()
*)

  let m = List.fold_left (fun ac (_,j) -> max ac j) 0 blocks in

  let nimber = Array.make (m+1) 0 in

  let mex_of_set s =
    let rec loop i = if Iset.mem i s then loop (i+1) else i in
      loop 0
  in

  let eval_move k j =
    let leftnimber = if k=0 then 0 else nimber.(k-1) in
    let rightnimber = if k=j-1 then 0 else nimber.(j-k-2) in
      leftnimber lxor rightnimber
  in

    for j=1 to m do
      let rec loop k s = if k=(j+1)/2 then s else
	  loop (k+1) (Iset.add (eval_move k j) s)
      in
      let s = loop 0 Iset.empty in
	nimber.(j) <- mex_of_set s;
(*	printf "nimber.(%d) = %d\n" j nimber.(j) *)
    done;

    let total_nimber = List.fold_left (fun ac (_,j) -> ac lxor nimber.(j)) 0 blocks in
      if total_nimber = 0 then 0 else
	let rec loop bl = match bl with
	  | [] -> failwith "should not happen"
	  | (p,j)::bl ->
	      if (total_nimber lxor nimber.(j)) < nimber.(j) then (p,j) else loop bl
	in
	let (p,j) = loop blocks in
	let goal = total_nimber lxor nimber.(j) in
	let rec findmove k = if eval_move k j = goal then k else findmove (k+1) in
	  (findmove 0) + p + 1

let () =
  let s = read_line() in
  let n = String.length s in
  let k = solve n s in
    if k=0 then printf "Second\n"
    else printf "First\n%d\n" k


Ashishgup and FastestFinger play a game. They start with a number $$$n$$$ and play in turns. In each turn, a player can make any one of the following moves:  Divide $$$n$$$ by any of its odd divisors greater than $$$1$$$.  Subtract $$$1$$$ from $$$n$$$ if $$$n$$$ is greater than $$$1$$$. Divisors of a number include the number itself.The player who is unable to make a move loses the game.Ashishgup moves first. Determine the winner of the game if both of them play optimally.

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

For each test case, print "Ashishgup" if he wins, and "FastestFinger" otherwise (without quotes).

FastestFinger
Ashishgup
Ashishgup
FastestFinger
Ashishgup
FastestFinger
Ashishgup

NoteIn the first test case, $$$n = 1$$$, Ashishgup cannot make a move. He loses.In the second test case, $$$n = 2$$$, Ashishgup subtracts $$$1$$$ on the first move. Now $$$n = 1$$$, FastestFinger cannot make a move, so he loses.In the third test case, $$$n = 3$$$, Ashishgup divides by $$$3$$$ on the first move. Now $$$n = 1$$$, FastestFinger cannot make a move, so he loses.In the last test case, $$$n = 12$$$, Ashishgup divides it by $$$3$$$. Now $$$n = 4$$$, FastestFinger is forced to subtract $$$1$$$, and Ashishgup gets $$$3$$$, so he wins by dividing it by $$$3$$$.

let rec is_pow_of_two (t : int) =
  if t mod 2 = 1 then
    false
  else
  if t = 2 then
    true
  else
    is_pow_of_two (t / 2)
;;

let rec is_prime (t : int) (i : int) =
  if t = 1 then
    false
  else if i * i > t then
    true
  else
  if t mod i = 0 then
    false
  else
    is_prime t (i + 1)
;;

let rec main (t : int) =
  if t = 0 then
    ()
  else
    let n = read_int () in
    (if (n = 1) || ((is_pow_of_two n) && n <> 2) || (n mod 2 = 0 && is_prime (n / 2) 2) then
      print_endline "FastestFinger"
    else
      print_endline "Ashishgup"; main (t-1))

;;

let n = read_int ()
in
main n


Mocha is a young girl from high school. She has learned so much interesting knowledge from her teachers, especially her math teacher. Recently, Mocha is learning about binary system and very interested in bitwise operation.This day, Mocha got a sequence $$$a$$$ of length $$$n$$$. In each operation, she can select an arbitrary interval $$$[l, r]$$$ and for all values $$$i$$$ ($$$0\leq i \leq r-l$$$), replace $$$a_{l+i}$$$ with $$$a_{l+i} \,\&\, a_{r-i}$$$ at the same time, where $$$\&$$$ denotes the bitwise AND operation. This operation can be performed any number of times.For example, if $$$n=5$$$, the array is $$$[a_1,a_2,a_3,a_4,a_5]$$$, and Mocha selects the interval $$$[2,5]$$$, then the new array is $$$[a_1,a_2\,\&\, a_5, a_3\,\&\, a_4, a_4\,\&\, a_3, a_5\,\&\, a_2]$$$.Now Mocha wants to minimize the maximum value in the sequence. As her best friend, can you help her to get the answer?

Each test contains multiple test cases.  The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the sequence. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$).

For each test case, print one integer — the minimal value of the maximum value in the sequence.

NoteIn the first test case, Mocha can choose the interval $$$[1,2]$$$, then the sequence becomes $$$[ 0, 0]$$$, where the first element is $$$1\,\&\,2$$$, and the second element is $$$2\,\&\,1$$$.In the second test case, Mocha can choose the interval $$$[1,3]$$$, then the sequence becomes $$$[ 1,1,1]$$$, where the first element is $$$1\,\&\,3$$$, the second element is $$$1\,\&\,1$$$, and the third element is $$$3\,\&\,1$$$.

(* This is an OCaml editor.
   Enter your program here and send it to the toplevel using the "Eval code"
   button. *)

let readInt () = Scanf.scanf " %d" (fun i -> i);;

let print_number x = print_string (string_of_int x); print_newline();;

let p2 = Array.make 31 0;;
let p = ref 1;;

for i = 0 to 30 do
  p2.(i) <- !p;
  p := 2 * !p;
done;;

let f x y z =
  if x + y = 2 then p2.(z) else 0;;

let rec func x y z =
  match z with
  | 31 -> 0
  | z -> f (x mod 2) (y mod 2) z + func (x / 2) (y / 2) (z + 1);;

let comp x y = func x y 0;;

let t = readInt() in
for _ = 1 to t do
  let l = ref [] in
  let n = readInt() in
  let x = readInt() in
  if n = 1 then print_number x
  else
    for i = 2 to n do
      l := readInt() :: !l;
      if i = n then print_number (List.fold_left comp (x) !l);
    done;
done;;

(* This is an OCaml editor.
   Enter your program here and send it to the toplevel using the "Eval code"
   button. *)

let readInt () = Scanf.scanf " %d" (fun i -> i);;

let print_number x = print_string (string_of_int x); print_newline();;

let p2 = Array.make 31 0;;
let p = ref 1;;

for i = 0 to 30 do
  p2.(i) <- !p;
  p := 2 * !p;
done;;

let f x y z =
  if x + y = 2 then p2.(z) else 0;;

let rec func x y z =
  match z with
  | 31 -> 0
  | z -> f (x mod 2) (y mod 2) z + func (x / 2) (y / 2) (z + 1);;

let comp x y = func x y 0;;

let t = readInt() in
for _ = 1 to t do
  let l = ref [] in
  let n = readInt() in
  let x = readInt() in
  for i = 2 to n do
    l := readInt() :: !l;
    if i = n then print_number (List.fold_left comp (x) !l);
  done;
done;;


You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times:  if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;  if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;  ...  remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.

The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.

Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).

let ( */ ) = Big_int.mult_big_int;;
let ( +/ ) = Big_int.add_big_int;;
let ( -/ ) = Big_int.sub_big_int;;
let to_int = Big_int.int_of_big_int;;
let of_int = Big_int.big_int_of_int;;
let min = Big_int.min_big_int;;
let (modi) = Big_int.mod_big_int;;
let to_string = Big_int.string_of_big_int;;
let of_string = Big_int.big_int_of_string;;
let (</) = Big_int.lt_big_int;;

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

exception End;;

let split n s =
  let a = Array.make n ' ' in
  for i = 0 to n-1 do
    a.(i) <- s.[i]
  done;
  a
;;
let compare_ci (x,a) (y,b) = match compare x y
  with 0 -> compare a b | c -> c
;;

let n,k = Scanf.sscanf (read_line ()) "%i %i" (fun n k -> n,k)  in
let s = read_line () |> split n in
let sorted_s = Array.mapi (fun i c -> (c,i)) s in
Array.sort compare_ci sorted_s;
let remove = Array.sub sorted_s 0 k in
Array.sort (fun (_,x) (_,y) -> compare x y) remove;
let position = ref 0 in
for i = 0 to n - 1 do
  if !position = Array.length remove || snd remove.(!position) != i then Printf.printf "%c" s.(i)
  else incr position
done;
print_newline ()


The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.If there is no police officer free (isn't busy with crime) during the occurrence of a crime, it will go untreated.Given the chronological order of crime occurrences and recruit hirings, find the number of crimes which will go untreated.

The first line of input will contain an integer n (1 ≤ n ≤ 105), the number of events. The next line will contain n space-separated integers. If the integer is -1 then it means a crime has occurred. Otherwise, the integer will be positive, the number of officers recruited together at that time. No more than 10 officers will be recruited at a time.

Print a single integer, the number of crimes which will go untreated.

NoteLets consider the second example:  Firstly one person is hired.  Then crime appears, the last hired person will investigate this crime.  One more person is hired.  One more crime appears, the last hired person will investigate this crime.  Crime appears. There is no free policeman at the time, so this crime will go untreated.  One more person is hired.  One more person is hired.  One more person is hired. The answer is one, as one crime (on step 5) will go untreated.

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

let solve () =
    let n = read () in
    let rec loop i unsolved police =
        if i < n
        then
            let temp = read () in
            if temp < 0
            then
                if police >= 1
                then
                    loop (i + 1) unsolved (police - 1)
                else
                    loop (i + 1) (unsolved + 1) police
            else
                loop (i + 1) unsolved (police + temp)
        else
            unsolved
    in loop 0 0 0

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

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

let () =
  let n = read_int () in
  let rec loop unsolved police = function
    | 0 -> unsolved
    | n ->
        let x = read_int () in
        if x < 0 then
          if police > 0 then
            loop unsolved (police - 1)  (n - 1)
          else
            loop (unsolved + 1) police (n - 1)
        else
          loop unsolved (police + x) (n - 1)
  in Printf.printf "%d\n" (loop 0 0 n)

open Scanf
open Printf

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

let n = read_int ()
let a = Array.init n (fun i -> read_int ())

let comp (s, r) x =
    match (x, s) with
    | (-1, 0) -> (0, r + 1)
    | _       -> (s + x, r)

let () = printf "%d\n" (snd (Array.fold_left comp (0, 0) a))


You are given a permutation of integers from 1 to n. Exactly once you apply the following operation to this permutation: pick a random segment and shuffle its elements. Formally:  Pick a random segment (continuous subsequence) from l to r. All  segments are equiprobable.  Let k = r - l + 1, i.e. the length of the chosen segment. Pick a random permutation of integers from 1 to k, p1, p2, ..., pk. All k! permutation are equiprobable.  This permutation is applied to elements of the chosen segment, i.e. permutation a1, a2, ..., al - 1, al, al + 1, ..., ar - 1, ar, ar + 1, ..., an is transformed to a1, a2, ..., al - 1, al - 1 + p1, al - 1 + p2, ..., al - 1 + pk - 1, al - 1 + pk, ar + 1, ..., an. Inversion if a pair of elements (not necessary neighbouring) with the wrong relative order. In other words, the number of inversion is equal to the number of pairs (i, j) such that i < j and ai > aj. Find the expected number of inversions after we apply exactly one operation mentioned above.

The first line contains a single integer n (1 ≤ n ≤ 100 000) — the length of the permutation. The second line contains n distinct integers from 1 to n — elements of the permutation.

Print one real value — the expected number of inversions. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 9.  Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

module Fenwick64 :
sig
  type t
  val create : int -> t
  val add : t -> int -> int64 -> unit
  val sumto : t -> int -> int64
end=
struct
  type t = int64 array

  let create n =
    Array.make (n+1) Int64.zero

  let add fw n x =
    let len = Array.length fw in
    let pos = ref (n+1) in
    let rec loop () =
      let p = !pos in
      if p < len
      then
        begin
          Array.set fw p (Int64.add fw.(p) x);
          pos := p + (p land (~- p));
          loop ()
        end
    in loop ()

  let sumto fw n =
    let pos, sum = ref n, ref Int64.zero in
    let rec loop () =
      let p = !pos in
      if p > 0
      then
        begin
          sum := Int64.add (!sum) fw.(p);
          pos := p - (p land (~- p));
          loop ()
        end
      else
        !sum
    in loop ()
end

let inversion_in_interval (n, a) =
  let ans = ref Int64.zero in
  let fw = Fenwick64.create n in
  for i = n-1 downto 0 do
    ans := Int64.add (!ans) (Int64.mul (Int64.of_int (i+1)) (Fenwick64.sumto fw a.(i)));
    Fenwick64.add fw a.(i) (Int64.of_int (n-i))
  done;
  !ans

let inversion (n, a) =
  let ans = ref Int64.zero in
  let fw = Fenwick64.create n in
  for i = n-1 downto 0 do
    ans := Int64.add (!ans) (Fenwick64.sumto fw a.(i));
    Fenwick64.add fw a.(i) Int64.one
  done;
  !ans

let inversion_after_shuffle (n, a) =
  Int64.to_float (inversion (n, a))
  +. float (n+2) *. float (n-1) /. 24.
  -. Int64.to_float (inversion_in_interval (n, a)) /. (float n *. float (n+1) /. 2.)

let main () =
  let n = read_int () in
  let a = Array.make n 0 in
  for i = 0 to n-1 do
    Scanf.scanf " %u"
      (fun x -> Array.set a i (x-1))
  done;
  print_float (inversion_after_shuffle (n, a))

let () = main ()

module Fenwick :
sig
  type t
  val create : int -> t
  val add : t -> int -> int -> unit
  val sumto : t -> int -> int
end=
struct
  type t = int array

  let create n =
    Array.make (n+1) 0

  let add fw n x =
    let len = Array.length fw in
    let pos = ref (n+1) in
    let rec loop () =
      let p = !pos in
      if p < len
      then
        begin
          Array.set fw p (fw.(p) + x);
          pos := p + (p land (~- p));
          loop ()
        end
    in loop ()

  let sumto fw n =
    let pos, sum = ref n, ref 0 in
    let rec loop () =
      let p = !pos in
      if p > 0
      then
        begin
          sum := (!sum) + fw.(p);
          pos := p - (p land (~- p));
          loop ()
        end
      else
        !sum
    in loop ()
end

let inversion_in_interval (n, a) =
  let ans = ref 0 in
  let fw = Fenwick.create n in
  for i = n-1 downto 0 do
    ans := (!ans) + (i+1) * Fenwick.sumto fw a.(i);
    Fenwick.add fw a.(i) (n-i)
  done;
  !ans

let inversion (n, a) =
  let ans = ref 0 in
  let fw = Fenwick.create n in
  for i = n-1 downto 0 do
    ans := (!ans) + Fenwick.sumto fw a.(i);
    Fenwick.add fw a.(i) 1
  done;
  !ans

let inversion_after_shuffle (n, a) =
  (float (inversion (n, a)))
  +. (float ((n+2) * (n-1))) /. 24.
  -.  (float (inversion_in_interval (n, a)) /. float (n * (n+1) / 2))

let main () =
  let n = read_int () in
  let a = Array.make n 0 in
  for i = 0 to n-1 do
    Scanf.scanf " %u"
      (fun x -> Array.set a i (x-1))
  done;
  print_float (inversion_after_shuffle (n, a))

let () = main ()

module Fenwick :
sig
  type t
  val create : int -> t
  val add : t -> int -> int -> unit
  val sumto : t -> int -> int
end=
struct
  type t = int array

  let create n =
    Array.make (n+1) 0

  let add fw n x =
    let len = Array.length fw in
    let pos = ref (n+1) in
    let rec loop () =
      let p = !pos in
      if p < len
      then
        begin
          Array.set fw p (fw.(p) + x);
          pos := p + (p land (~- p));
          loop ()
        end
    in loop ()

  let sumto fw n =
    let pos, sum = ref n, ref 0 in
    let rec loop () =
      let p = !pos in
      if p > 0
      then
        begin
          sum := (!sum) + fw.(p);
          pos := p - (p land (~- p));
          loop ()
        end
      else
        !sum
    in loop ()
end

let inversion_in_interval (n, a) =
  let ansf = ref 0. in
  let fw = Fenwick.create n in
  for i = n-1 downto 0 do
    ansf := (!ansf) +. float ((i+1) * Fenwick.sumto fw a.(i));
    Fenwick.add fw a.(i) (n-i)
  done;
  !ansf

let inversion (n, a) =
  let ans = ref 0 in
  let fw = Fenwick.create n in
  for i = n-1 downto 0 do
    ans := (!ans) + Fenwick.sumto fw a.(i);
    Fenwick.add fw a.(i) 1
  done;
  !ans

let inversion_after_shuffle (n, a) =
  (float (inversion (n, a)))
  +. (float ((n+2) * (n-1))) /. 24.
  -. (inversion_in_interval (n, a)) /. float (n * (n+1) / 2)

let main () =
  let n = read_int () in
  let a = Array.make n 0 in
  for i = 0 to n-1 do
    Scanf.scanf " %u"
      (fun x -> Array.set a i (x-1))
  done;
  print_float (inversion_after_shuffle (n, a))

let () = main ()


There are n banks in the city where Vasya lives, they are located in a circle, such that any two banks are neighbouring if their indices differ by no more than 1. Also, bank 1 and bank n are neighbours if n > 1. No bank is a neighbour of itself.Vasya has an account in each bank. Its balance may be negative, meaning Vasya owes some money to this bank.There is only one type of operations available: transfer some amount of money from any bank to account in any neighbouring bank. There are no restrictions on the size of the sum being transferred or balance requirements to perform this operation.Vasya doesn't like to deal with large numbers, so he asks you to determine the minimum number of operations required to change the balance of each bank account to zero. It's guaranteed, that this is possible to achieve, that is, the total balance of Vasya in all banks is equal to zero.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of banks. The second line contains n integers ai ( - 109 ≤ ai ≤ 109), the i-th of them is equal to the initial balance of the account in the i-th bank. It's guaranteed that the sum of all ai is equal to 0.

Print the minimum number of operations required to change balance in each bank to zero.

NoteIn the first sample, Vasya may transfer 5 from the first bank to the third.In the second sample, Vasya may first transfer 1 from the third bank to the second, and then 1 from the second to the first.In the third sample, the following sequence provides the optimal answer:   transfer 1 from the first bank to the second bank;  transfer 3 from the second bank to the third;  transfer 6 from the third bank to the fourth.

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 read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let a = Array.init n (fun i -> long (read_int())) in

  let count = Hashtbl.create 10 in

  let increment key =
    let c = try Hashtbl.find count key with Not_found -> 0 in
    Hashtbl.replace count key (c+1)
  in

  let rec scan i carry = if i=n then () else
      let carry = carry ++ a.(i) in
      increment carry;
      scan (i+1) carry
  in

  scan 0 0L;

  let mcount = Hashtbl.fold (fun _ v ac -> max ac v) count 0 in

  printf "%d\n" (n-mcount)


Monocarp is playing a computer game. Now he wants to complete the first level of this game.A level is a rectangular grid of $$$2$$$ rows and $$$n$$$ columns. Monocarp controls a character, which starts in cell $$$(1, 1)$$$ — at the intersection of the $$$1$$$-st row and the $$$1$$$-st column.Monocarp's character can move from one cell to another in one step if the cells are adjacent by side and/or corner. Formally, it is possible to move from cell $$$(x_1, y_1)$$$ to cell $$$(x_2, y_2)$$$ in one step if $$$|x_1 - x_2| \le 1$$$ and $$$|y_1 - y_2| \le 1$$$. Obviously, it is prohibited to go outside the grid.There are traps in some cells. If Monocarp's character finds himself in such a cell, he dies, and the game ends.To complete a level, Monocarp's character should reach cell $$$(2, n)$$$ — at the intersection of row $$$2$$$ and column $$$n$$$.Help Monocarp determine if it is possible to complete the level.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow. Each test case consists of three lines. The first line contains a single integer $$$n$$$ ($$$3 \le n \le 100$$$) — the number of columns. The next two lines describe the level. The $$$i$$$-th of these lines describes the $$$i$$$-th line of the level — the line consists of the characters '0' and '1'. The character '0' corresponds to a safe cell, the character '1' corresponds to a trap cell. Additional constraint on the input: cells $$$(1, 1)$$$ and $$$(2, n)$$$ are safe.

For each test case, output YES if it is possible to complete the level, and NO otherwise.

NoteConsider the example from the statement.In the first test case, one of the possible paths is $$$(1, 1) \rightarrow (2, 2) \rightarrow (2, 3)$$$.In the second test case, one of the possible paths is $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 3) \rightarrow (2, 4)$$$.In the fourth test case, one of the possible paths is $$$(1, 1) \rightarrow (2, 2) \rightarrow (1, 3) \rightarrow (2, 4) \rightarrow (1, 5) \rightarrow (2, 6)$$$.

let solve () =
  let n = read_int () in
  let s1 = read_line () in
  let s2 = read_line () in
  let rec parse d1 d2 = function
    i when i = n -> d2
  | i -> ((s1.[i] = '0') ||
          (s2.[i] = '0')) &&
         parse (s1.[i] = '0') (s2.[i] = '0') (i+1)
    in
  parse true false 0;;

let t = read_int () ;;

let rec main = function
  0 -> ();
| n ->
    begin
      (if solve () then print_string "YES\n"
      else print_string "NO\n") ;
      main (n-1)
    end ;;

main t;;

let solve () =
  let n = read_int () in
  let s1 = read_line () in
  let s2 = read_line () in
  let rec parse d1 d2 = function
    i when i = n -> d2
  | i -> ((d1 && s1.[i] = '0') ||
          (d2 && s2.[i] = '0')) &&
         parse (s1.[i] = '0') (s2.[i] = '0') (i+1)
    in
  parse true false 0;;

let t = read_int () ;;

let rec main = function
  0 -> ();
| n ->
    begin
      (if solve () then print_string "YES\n"
      else print_string "NO\n") ;
      main (n-1)
    end ;;

main t;;

let solve () =
  let n = read_int () in
  let s1 = read_line () in
  let s2 = read_line () in
  let rec parse d1 d2 = function
    i when i = n -> d2
  | i -> ((d1 && s1.[i] = '1') ||
          (d2 && s2.[i] = '1')) &&
         parse (s1.[i] = '1') (s2.[i] = '1') (i+1)
    in
  parse true false 0;;

let t = read_int () ;;

let rec main = function
  0 -> ();
| n ->
    begin
      (if solve () then print_string "YES\n"
      else print_string "NO\n") ;
      main (n-1)
    end ;;

main t;;


Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park.She has only two pockets. She can put at most k pebbles in each pocket at the same time. There are n different pebble types in the park, and there are wi pebbles of the i-th type. Anastasia is very responsible, so she never mixes pebbles of different types in same pocket. However, she can put different kinds of pebbles in different pockets at the same time. Unfortunately, she can't spend all her time collecting pebbles, so she can collect pebbles from the park only once a day.Help her to find the minimum number of days needed to collect all the pebbles of Uzhlyandian Central Park, taking into consideration that Anastasia can't place pebbles of different types in same pocket.

The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of different pebble types and number of pebbles Anastasia can place in one pocket. The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 104) — number of pebbles of each type.

The only line of output contains one integer — the minimum number of days Anastasia needs to collect all the pebbles.

NoteIn the first sample case, Anastasia can collect all pebbles of the first type on the first day, of second type — on the second day, and of third type — on the third day.Optimal sequence of actions in the second sample case:   In the first day Anastasia collects 8 pebbles of the third type.  In the second day she collects 8 pebbles of the fourth type.  In the third day she collects 3 pebbles of the first type and 1 pebble of the fourth type.  In the fourth day she collects 7 pebbles of the fifth type.  In the fifth day she collects 1 pebble of the second type.

(*#load "str.cma"*)
open Printf;;
let ans = ref 0;;
let proc k vs =
	let x = (int_of_string vs) in
		ans := !ans + (x / k) + (if x mod k != 0 then 1 else 0);;
let main  =
	let [n; k] = List.map (int_of_string) (Str.split (Str.regexp " ") (read_line ())) in
	let ans = ref 0 in
	let s = List.map (proc k) (Str.split (Str.regexp " ") (read_line ())) in 0;;
print_int (!ans / 2 + !ans mod 2);;


Vasya used to be an accountant before the war began and he is one of the few who knows how to operate a computer, so he was assigned as the programmer.We all know that programs often store sets of integers. For example, if we have a problem about a weighted directed graph, its edge can be represented by three integers: the number of the starting vertex, the number of the final vertex and the edge's weight. So, as Vasya was trying to represent characteristics of a recently invented robot in his program, he faced the following problem.Vasya is not a programmer, so he asked his friend Gena, what the convenient way to store n integers is. Gena used to code in language X-- and so he can use only the types that occur in this language. Let's define, what a "type" is in language X--:  First, a type is a string "int".  Second, a type is a string that starts with "pair", then followed by angle brackets listing exactly two comma-separated other types of language X--. This record contains no spaces.  No other strings can be regarded as types. More formally: type := int | pair<type,type>. For example, Gena uses the following type for graph edges: pair<int,pair<int,int>>.Gena was pleased to help Vasya, he dictated to Vasya a type of language X--, that stores n integers. Unfortunately, Gena was in a hurry, so he omitted the punctuation. Now Gena has already left and Vasya can't find the correct punctuation, resulting in a type of language X--, however hard he tries.Help Vasya and add the punctuation marks so as to receive the valid type of language X--. Otherwise say that the task is impossible to perform.

The first line contains a single integer n (1 ≤ n ≤ 105), showing how many numbers the type dictated by Gena contains. The second line contains space-separated words, said by Gena. Each of them is either "pair" or "int" (without the quotes). It is guaranteed that the total number of words does not exceed 105 and that among all the words that Gena said, there are exactly n words "int".

If it is possible to add the punctuation marks so as to get a correct type of language X-- as a result, print a single line that represents the resulting type. Otherwise, print "Error occurred" (without the quotes). Inside the record of a type should not be any extra spaces and other characters.  It is guaranteed that if such type exists, then it is unique. Note that you should print the type dictated by Gena (if such type exists) and not any type that can contain n values.

type t0 = P | I
type t1 = Pair of t1 * t1 | Int

let _ =
    let rec dump k =
        match k with
        | Int -> print_string "int"
        | Pair (a, b) -> print_string "pair<";dump a;print_string ","; dump b; print_string ">"
    in

    let main () =
        let _ = read_int () in
        let s = read_line () in
        let l = String.length s in
        let rec loop p acc =
            if p >= l then acc else
            if s.[p] = 'p' then loop (p + 4) (P :: acc) else
            if s.[p] = 'i' then loop (p + 3) (I :: acc) else
            loop (p + 1) acc
        in
        let k = List.rev (loop 0 []) in
        let rec parse = function
            | [] -> None
            | I :: tl -> Some (Int, tl)
            | P :: tl -> (
                match parse tl with
                | None -> None
                | Some (a, tl2) -> (
                    match parse tl2 with
                    | None -> None
                    | Some (b, tl3) -> Some (Pair (a, b), tl3)
                )
            )
        in
        match parse k with
        | Some (a, []) -> dump a; print_newline ()
        | _ -> print_endline "Error occurred"
    in
    main ()

open Scanf;;
open Printf;;
open Str;;

let split_by_space = split (regexp " +")

type token = P | I

let token_of_str = function
    "pair" -> P
  | "int" -> I
  | _ -> failwith "hoge"

let input () =
  let n = int_of_string(read_line ()) in
  let str = read_line () in
  (n, List.map token_of_str (split_by_space str))

type tree = Pair of (tree * tree) | Int

let solve ls =
  let rec solve = function
      [] -> failwith ""
    | P::ls ->
        let (res1, ls) = solve ls in
        let (res2, ls) = solve ls in
        (Pair (res1, res2), ls)
    | I::ls ->
        (Int, ls) in
  let (res, ls) = solve ls in
  match ls with
    [] -> res
  | _ -> failwith ""

let rec print_res = function
    Pair(x, y) ->
      print_string "pair<";
      print_res x;
      print_string ",";
      print_res y;
      print_string ">"
  | Int ->
      print_string "int"

let () =
  let (n, ss) = input () in
  (* List.iter (fun x -> printf "%s\n" x) ss; *)
  try
    let res = solve ss in
    print_res res;
    print_string "\n"
  with
    Failure _ -> print_endline "Error occurred"


Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?There are $$$n$$$ students living in a building, and for each of them the favorite drink $$$a_i$$$ is known. So you know $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ ($$$1 \le a_i \le k$$$) is the type of the favorite drink of the $$$i$$$-th student. The drink types are numbered from $$$1$$$ to $$$k$$$.There are infinite number of drink sets. Each set consists of exactly two portions of the same drink. In other words, there are $$$k$$$ types of drink sets, the $$$j$$$-th type contains two portions of the drink $$$j$$$. The available number of sets of each of the $$$k$$$ types is infinite.You know that students will receive the minimum possible number of sets to give all students exactly one drink. Obviously, the number of sets will be exactly $$$\lceil \frac{n}{2} \rceil$$$, where $$$\lceil x \rceil$$$ is $$$x$$$ rounded up.After students receive the sets, they will distribute their portions by their choice: each student will get exactly one portion. Note, that if $$$n$$$ is odd then one portion will remain unused and the students' teacher will drink it.What is the maximum number of students that can get their favorite drink if $$$\lceil \frac{n}{2} \rceil$$$ sets will be chosen optimally and students will distribute portions between themselves optimally?

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n, k \le 1\,000$$$) — the number of students in the building and the number of different drinks. The next $$$n$$$ lines contain student's favorite drinks. The $$$i$$$-th line contains a single integer from $$$1$$$ to $$$k$$$ — the type of the favorite drink of the $$$i$$$-th student.

Print exactly one integer — the maximum number of students that can get a favorite drink.

NoteIn the first example, students could choose three sets with drinks $$$1$$$, $$$1$$$ and $$$2$$$ (so they will have two sets with two drinks of the type $$$1$$$ each and one set with two drinks of the type $$$2$$$, so portions will be $$$1, 1, 1, 1, 2, 2$$$). This way all students except the second one will get their favorite drinks.Another possible answer is sets with drinks $$$1$$$, $$$2$$$ and $$$3$$$. In this case the portions will be $$$1, 1, 2, 2, 3, 3$$$. Then all the students except one will gain their favorite drinks. The only student that will not gain the favorite drink will be a student with $$$a_i = 1$$$ (i.e. the first, the third or the fourth).

(* Input *)
let (num_students, num_drink_types) = Scanf.scanf "%d %d\n" (fun x y -> (x, y));;
let student_drink_types =
  let rec read_int_list = function
    | 0 -> []
    | n -> (Scanf.scanf "%d\n" (fun x -> x - 1)) :: read_int_list (n - 1)
  in
    List.rev (read_int_list num_students)
;;

(* Process *)
let favorite_counts = Array.make num_drink_types 0;;
List.iter (fun tp -> (favorite_counts.(tp) <- favorite_counts.(tp) + 1)) student_drink_types;;

let num_leftout = Array.fold_left (fun a b -> a + b mod 2) 0 favorite_counts;;
let result = num_students - num_leftout + (num_leftout + 1) / 2;;
Printf.printf "%d\n" result;;

(* Input *)
let (num_students, num_drink_types) = Scanf.scanf "%d %d\n" (fun x y -> (x, y));;

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

let student_drink_types = List.rev (read_rev_int_list (num_students));;

(* Process *)
let favorite_counts = Array.make num_drink_types 0;;
List.iter (fun tp -> (favorite_counts.(tp) <- favorite_counts.(tp) + 1)) student_drink_types;;

let num_leftout = ref 0;;
Array.iter (fun cnt -> num_leftout := !num_leftout + (cnt mod 2)) favorite_counts;;

let result = num_students - !num_leftout + (!num_leftout + 1) / 2;;
Printf.printf "%d\n" result;;


Sensation, sensation in the two-dimensional kingdom! The police have caught a highly dangerous outlaw, member of the notorious "Pihters" gang. The law department states that the outlaw was driving from the gang's headquarters in his car when he crashed into an ice cream stall. The stall, the car, and the headquarters each occupies exactly one point on the two-dimensional kingdom.The outlaw's car was equipped with a GPS transmitter. The transmitter showed that the car made exactly n movements on its way from the headquarters to the stall. A movement can move the car from point (x, y) to one of these four points: to point (x - 1, y) which we will mark by letter "L", to point (x + 1, y) — "R", to point (x, y - 1) — "D", to point (x, y + 1) — "U".The GPS transmitter is very inaccurate and it doesn't preserve the exact sequence of the car's movements. Instead, it keeps records of the car's possible movements. Each record is a string of one of these types: "UL", "UR", "DL", "DR" or "ULDR". Each such string means that the car made a single movement corresponding to one of the characters of the string. For example, string "UL" means that the car moved either "U", or "L".You've received the journal with the outlaw's possible movements from the headquarters to the stall. The journal records are given in a chronological order. Given that the ice-cream stall is located at point (0, 0), your task is to print the number of different points that can contain the gang headquarters (that is, the number of different possible locations of the car's origin).

The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of the car's movements from the headquarters to the stall. Each of the following n lines describes the car's possible movements. It is guaranteed that each possible movement is one of the following strings: "UL", "UR", "DL", "DR" or "ULDR".  All movements are given in chronological order.  Please do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin and cout stream or the %I64d specifier.

Print a single integer — the number of different possible locations of the gang's headquarters.

NoteThe figure below shows the nine possible positions of the gang headquarters from the first sample:   For example, the following movements can get the car from point (1, 0) to point (0, 0):

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let w = ref 1 in
  let h = ref 1 in
    for i = 1 to n do
      let s = Scanf.bscanf sb "%s " (fun s -> s) in
	match s with
	  | "UL" ->
	      incr h
	  | "UR" ->
	      incr w
	  | "DL" ->
	      incr w
	  | "DR" ->
	      incr h
	  | "ULDR" ->
	      incr h;
	      incr w;
	  | _ -> assert false
    done;
    let res = Int64.mul (Int64.of_int !h) (Int64.of_int !w) in
      Printf.printf "%Ld\n" res


You are given a table $$$a$$$ of size $$$n \times m$$$. We will consider the table rows numbered from top to bottom from $$$1$$$ to $$$n$$$, and the columns numbered from left to right from $$$1$$$ to $$$m$$$. We will denote a cell that is in the $$$i$$$-th row and in the $$$j$$$-th column as $$$(i, j)$$$. In the cell $$$(i, j)$$$ there is written a number $$$(i - 1) \cdot m + j$$$, that is $$$a_{ij} = (i - 1) \cdot m + j$$$.A turtle initially stands in the cell $$$(1, 1)$$$ and it wants to come to the cell $$$(n, m)$$$. From the cell $$$(i, j)$$$ it can in one step go to one of the cells $$$(i + 1, j)$$$ or $$$(i, j + 1)$$$, if it exists. A path is a sequence of cells in which for every two adjacent in the sequence cells the following satisfies: the turtle can reach from the first cell to the second cell in one step. A cost of a path is the sum of numbers that are written in the cells of the path.  For example, with $$$n = 2$$$ and $$$m = 3$$$ the table will look as shown above. The turtle can take the following path: $$$(1, 1) \rightarrow (1, 2) \rightarrow (1, 3) \rightarrow (2, 3)$$$. The cost of such way is equal to $$$a_{11} + a_{12} + a_{13} + a_{23} = 12$$$. On the other hand, the paths $$$(1, 1) \rightarrow (1, 2) \rightarrow (2, 2) \rightarrow (2, 1)$$$ and $$$(1, 1) \rightarrow (1, 3)$$$ are incorrect, because in the first path the turtle can't make a step $$$(2, 2) \rightarrow (2, 1)$$$, and in the second path it can't make a step $$$(1, 1) \rightarrow (1, 3)$$$.You are asked to tell the turtle a minimal possible cost of a path from the cell $$$(1, 1)$$$ to the cell $$$(n, m)$$$. Please note that the cells $$$(1, 1)$$$ and $$$(n, m)$$$ are a part of the way.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The description of test cases follows. A single line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^4$$$) — the number of rows and columns of the table $$$a$$$ respectively.

For each test case output a single integer — a minimal possible cost of a path from the cell $$$(1, 1)$$$ to the cell $$$(n, m)$$$.

NoteIn the first test case the only possible path consists of a single cell $$$(1, 1)$$$.The path with the minimal cost in the second test case is shown in the statement.In the fourth and the fifth test cases there is only one path from $$$(1, 1)$$$ to $$$(n, m)$$$. Both paths visit every cell in the table.

(* nxm table, aij = (i-1)*m +j
   turtle in 1,1 wants to go to (n,m)
   find min possible cost to go from 1,1 to n,m

   down cost from aij = (i)*m + j
   right cost from aij = (i-1)*m + j+1

   down -right = m-1
   since m>=1, then down>=right

   d, r = (i*m +j) + (i*m + j +1) = 2*(i*m+j)+1
   r, d = ((i-1)*m + j+1) + (i*m + j+1) = 2*(i*m+j)+2-m

   since m>=1, then -m<=-1, 2-m<=1, (r, d<=d, r)

   d, d, r, r = 4*(i*m+j)+3*m+3
   d, r, d, r = 4*(i*m+j)+1+m+1+m+2

   diff = m-1, so (ddrr>=drdr)

   if (n>=m) then dr... m times... d... n-m times

   in any order we will have to pay:

   going down payment = m*(0 + 1 + 2 + ... + n-1) = m*n*(n-1)/2
   going along payment, exc row = 1 + 2 + 3 + 4+ ... + m = m*(m+1)/2

   payment = e + m * (n(n-1)/2 + (m+1)/2)

   e = (m*m*(n-k1)) + (n*(m-k2)) where m*(n-k1) is mean row going along and m-k2 is mean column going down

   e = m(n(m+1)) - m*m*k1 - n*k2
   (want to maximise k1 and k2)
   k1 <= n and k2 <= m
   m*m*k1 <= m*m*n, n*k2 <= n*m

   (k1, k2) = (0, n), (1)

   so better to maximise k1 than k2
   for each increase in k1, cost decreases by m*m
   for each increase in k2, cost decreases by n

   we can increase k1 n times and k2 m times.

   if k1 increases by 1, then

   3, 2 -> 1+2+4+6
   7, 1 -> 1+...+7
   1, 10 -> 1+2+...+10
   5, 5->1+2+...+5+10+15+20+25

   any extra cost is the cost of the row each
   time we go along + the cost of the column each
   time we go down

   there is always a +m increase going down
   there is always a +1 increase going along

   want to minimise the current sum

   current sum starts at 1

   need to go along m and down n

   always optimal to go along first and m>=1 then go along

   p(n+m)=p(n+m-1)+m=(p(n+m-2)+m)+m

   s = p(1)+p(2)+...+p(n+m-1)
     = p(1)+(p(1)+k1)+...+p(n+m-1)
     = p(1)+(p(1)+k1)+(p(1)+k1+k2)+...+p(n+m-1)
     = (n+m-1)p(1)+(n+m-2)*k1+(n+m-3)*k2+...+k(n+m-2)

    so to minimise the payment it is best to
    choose +1 first then +m

    we need choose n-1 +m and m-1 +1

    s = (n+m-1)p(1)+((n+m-1-1)+...+(n+m-1-(m-1)))+(n-1+...+1)*m
      = (n+m-1)+((m-1)(n+m-1)-(m(m-1)/2))+n(n-1)*m/2
      = (n+m-1)m-m((m-1)+n(n-1))/2
      = m((n+m-1)-((m-1)+n(n-1))/2)

    n=2, m=3

    s = (1+2+3+...+m-1)+m*(1+2+3+...+n)
    s = m(m-1)/2+m*n(n+1)/2

    n=2, m=3
    s=3+3*2*3/2=12

*)

let read_long () = Scanf.scanf " %Ld" (fun x->x);;
let read_int () = Scanf.scanf " %d" (fun x-> x);;
let run_case = function
| () ->
  let n = read_long () in
  let m = read_long () in
  let s1 = Int64.div (Int64.mul m (Int64.pred m)) (Int64.of_int 2) in
  let s2 = Int64.div (Int64.mul m (Int64.mul n (Int64.succ n))) (Int64.of_int 2) in
  let s = Int64.add s1 s2 in
  Printf.printf "%Ld\n" s
;;

let rec iter_cases = function
| 0 -> ()
| t ->
  run_case ();
  iter_cases (t-1)

;;

let t=read_int() in iter_cases t;;