"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).

The first line of the input data contains an integer n (1 ≤ n ≤ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 ≤ ai ≤ 5000, 1 ≤ i ≤ n).

Print the only number — the minimum number of changes needed to get the permutation.

NoteThe first sample contains the permutation, which is why no replacements are required.In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.In the third sample we can replace the second element with number 4 and the fourth element with number 2.

let getint () = Scanf.bscanf Scanf.Scanning.stdin " %d" (fun i->i)
let getstr () = Scanf.bscanf Scanf.Scanning.stdin " %s" (fun s-> s)
let getchar () = Scanf.bscanf Scanf.Scanning.stdin " %c" (fun i->i)

let inf = 1000000007

let _ =
  let n = getint () in
  let a = Array.make n 0 in
  for i = 0 to n-1 do
    let x = getint () - 1 in
    if x<n && x>=0 then a.(x) <- a.(x) + 1;
  done;
  let ans = ref 0 in
  for i = 0 to n-1 do
    if a.(i) = 0 then incr ans
  done;
  Printf.printf "%d\n" !ans

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

let n = read_int ();;

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

Array.sort compare data;;

let rec solve ac i data =
     if i>=n || data.(i)>n then ac
     else if i = 0 && data.(i) >= 1 && data.(i) <= n then solve (ac+1) (i+1) data
     else if i=0 && (data.(i)<1 || data.(i)>n) then solve ac (i+1) data
     else if data.(i) > n then ac
     else if data.(i) < 1 then solve ac (i+1) data
     else if data.(i) != data.(i-1) then solve (ac+1) (i+1) data
     else solve ac (i+1) data;;

Printf.printf "%d\n" (n-(solve 0 0 data));;

let () =
	let n = read_int() in
	let l = ref [] in
	(for i = 1 to n do
		let x = Scanf.scanf " %d" (fun i->i) in
		if x >= 1 && x <= n && not (List.mem x !l) then
			l := x::(!l);
	done; print_int (n-(List.length !l)))
;;

(*************** Ocaml stdio functions **********************)
let stdin_stream = Stream.of_channel stdin;;
let stdout_buffer = Buffer.create 65536;;
let rec gi() =
  match Stream.next stdin_stream with
    '-' ->  - (ri 0)
  | '+' ->  ri 0
  | '0'..'9' as c -> ri ((int_of_char c) - 48)
  | _ -> gi ()
and ri x =
  match Stream.next stdin_stream with
    '0'..'9' as c -> ri (((int_of_char c) - 48) + (x * 10))
  | _ -> x
;;
let flushout () = Buffer.output_buffer stdout stdout_buffer; Buffer.reset stdout_buffer;;
let putchar c =
  if (Buffer.length stdout_buffer) >= 65536 then flushout() else ();
  Buffer.add_char stdout_buffer c;;
let rec ppi i = if i < 10 then putchar (char_of_int (48 + i)) else (ppi (i / 10); putchar (char_of_int (48 + (i mod 10)))) ;;
let pi i = if i >= 0 then ppi i else (putchar ('-'); ppi (-i));;
let pa a = let n = Array.length a in Array.iteri (fun i j -> pi j; putchar (if i == (n-1) then '\n' else ' ')) a;;
(*************** Ocaml solution ******************************)
open Array
let main() =
  let n = gi() in
  let a = init n (fun i -> gi()) in
  let b = make (n+1) 0 in
  iter (fun i -> if (i >= 1 && i <= n) then b.(i) <- 1 else ()) a;
  let s = fold_left (+) 0 b in
  Printf.printf "%d\n" (n - s)
  ;;
main();;
flushout ()

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

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

let n = read_int()

let there = Array.make n false

let () =
  for i=0 to n-1 do
    let k = (read_int()) -1 in
      if k>=0 && k<n then there.(k) <- true
  done

let count = ref 0

let () =
  for i=0 to n-1 do
    count := !count + (if there.(i) then 0 else 1)
  done
;;

Printf.printf "%d\n" !count


Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).Help Daniel to process all queries.

The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries. The second line contains string s, consisting of n lowercase English letters and period signs. The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.

Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.

NoteNote to the first sample test (replaced periods are enclosed in square brackets).The original string is ".b..bz....". after the first query f(hb..bz....) = 4    ("hb[..]bz...."  →  "hb.bz[..].."  →  "hb.bz[..]."  →  "hb.bz[..]"  →  "hb.bz.") after the second query f(hbс.bz....) = 3    ("hbс.bz[..].."  →  "hbс.bz[..]."  →  "hbс.bz[..]"  →  "hbс.bz.") after the third query f(hbс.bz..f.) = 1    ("hbс.bz[..]f."  →  "hbс.bz.f.")Note to the second sample test.The original string is ".cc.". after the first query: f(..c.) = 1    ("[..]c."  →  ".c.") after the second query: f(....) = 3    ("[..].."  →  "[..]."  →  "[..]"  →  ".") after the third query: f(.a..) = 1    (".a[..]"  →  ".a.") after the fourth query: f(aa..) = 1    ("aa[..]"  →  "aa.")

module RangeSet = Map.Make(
    struct
        type t = int * int (* pairs of indices *)
        let compare (l1, r1) (l2, r2) =
            if r1 < l2 then -1
            else if r2 < l1 then 1
            else 0
    end)

let add elt s = RangeSet.add elt elt s

let () = Scanf.scanf "%d %d\n" (fun n m ->
    let s = Scanf.scanf "%s\n" (fun s -> s) in

    (* build a non-overlapping interval set *)
    let t, _ = List.fold_left (fun (acc, pos) hd ->
        match hd with
        | Str.Text s -> (acc, (pos + String.length s))
        | Str.Delim d ->
                let e = pos + String.length d in
                (add (pos, e - 1) acc, e))
        (RangeSet.empty, 1) (Str.full_split (Str.regexp "\\.+") s) in

    (* calculate the answer to the initial query *)
    let ans = ref (RangeSet.fold (fun _ (l, r) acc -> acc + (r - l)) t 0) in

    (* a query can have the following possible effects:
        * merge two intervals (or extend an interval)
        * split an interval
        * no effect on intervals *)
    let rec loop t i =
        if i <> m then
                Scanf.scanf "%d %c\n" (fun x c ->
                    let t' = match c with
                    | '.' ->
                            (* if this char is in an interval, no effect *)
                            if RangeSet.mem (x, x) t then t else

                            (* join two intervals *)
                            if RangeSet.mem (x-1,x-1) t && RangeSet.mem (x+1, x+1) t then begin
                                let l, _ = RangeSet.find (x-1, x-1) t
                                and _, r = RangeSet.find (x+1, x+1) t in
                                (* calculate new answer *)
                                ans := !ans + 2;
                                (* create new tree *)
                                add (l, r) (RangeSet.remove (x-1, x-1) (RangeSet.remove (x+1, x+1) t))
                            end else

                            (* extend left interval *)
                            if RangeSet.mem (x-1, x-1) t then begin
                                let l, _ = RangeSet.find (x-1, x-1) t in
                                incr ans;
                                add (l, x) (RangeSet.remove (x-1, x-1) t)
                            end else

                            (* extend right interval *)
                            if RangeSet.mem (x+1, x+1) t then begin
                                let _, r = RangeSet.find (x+1, x+1) t in
                                incr ans;
                                add (x, r) (RangeSet.remove (x+1, x+1) t)
                            end else

                            (* create new interval *)
                            add (x, x) t
                    | _ ->
                            (* if this char is in an interval, split it *)
                            if RangeSet.mem (x, x) t then begin
                                let l, r = RangeSet.find (x, x) t
                                and t = RangeSet.remove (x, x) t in
                                (* we take the interval (l, r) to (l,x-1) and (x+1,r)
                                 * check these new intervals are valid and subtract 1 from ans
                                 * for each valid new interval *)
                                let t =
                                    if l < x then begin
                                        decr ans;
                                        add (l, x-1) t
                                    end else t
                                in
                                if r > x then begin
                                    decr ans;
                                    add (x+1, r) t
                                end else t
                            (* otherwise nothing to do *)
                            end else t
                    in
                    Printf.printf "%d\n" !ans;
                    loop t' (i + 1))
    in loop t 0)

let () = Scanf.scanf "%d %d\n" (fun n m ->
    let s = Scanf.scanf "%s\n" (fun s -> s) in
    (* count number of groups in s *)
    let a = Array.init (n + 2) (fun i -> if i = 0 || i = n + 1 then false else s.[i-1] = '.') in

    let rec aux (groups, count) i =
        if i = n then (groups, count)
        else aux (if s.[i] = '.' then
            (groups + (if i = 0 || s.[i - 1] <> '.' then 1 else 0), count + 1)
            else (groups, count))
            (i + 1)
    in

    let g, c = aux (0, 0) 0 in

    let groups = ref g
    and count = ref c in

    for i = 1 to m do
        Scanf.scanf "%d %c\n" (fun x c ->
            (* only do something if we're changing the state *)
            if a.(x) <> (c = '.') then begin
                if c = '.' then begin
                    incr count;

                    (* merge groups *)
                    if a.(x - 1) && a.(x + 1)
                    then decr groups;

                    (* create a new group *)
                    if not (a.(x - 1) || a.(x + 1))
                    then incr groups

                (* check whether we merge or split a group *)
                end else begin
                    decr count;

                    (* split a group *)
                    if a.(x - 1) && a.(x + 1)
                    then incr groups;

                    (* remove a single point *)
                    if not (a.(x - 1) || a.(x + 1))
                    then decr groups
                end;

                a.(x) <- c = '.'
            end;

            Printf.printf "%d\n" (!count - !groups))
    done)


Petya and Vasya are tossing a coin. Their friend Valera is appointed as a judge. The game is very simple. First Vasya tosses a coin x times, then Petya tosses a coin y times. If the tossing player gets head, he scores one point. If he gets tail, nobody gets any points. The winner is the player with most points by the end of the game. If boys have the same number of points, the game finishes with a draw.At some point, Valera lost his count, and so he can not say exactly what the score is at the end of the game. But there are things he remembers for sure. He remembers that the entire game Vasya got heads at least a times, and Petya got heads at least b times. Moreover, he knows that the winner of the game was Vasya. Valera wants to use this information to know every possible outcome of the game, which do not contradict his memories.

The single line contains four integers x, y, a, b (1 ≤ a ≤ x ≤ 100, 1 ≤ b ≤ y ≤ 100). The numbers on the line are separated by a space.

In the first line print integer n — the number of possible outcomes of the game. Then on n lines print the outcomes. On the i-th line print a space-separated pair of integers ci, di — the number of heads Vasya and Petya got in the i-th outcome of the game, correspondingly. Print pairs of integers (ci, di) in the strictly increasing order. Let us remind you that the pair of numbers (p1, q1) is less than the pair of numbers (p2, q2), if p1 < p2, or p1 = p2 and also q1 < q2.

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

let () =
  let x = read_int() in
  let y = read_int() in
  let a = read_int() in
  let b = read_int() in

  let lis = ref [] in

    for i=a to x do
      for j=b to y do
	if i>j then lis := (i,j)::!lis
      done
    done;

    Printf.printf "%d\n" (List.length !lis);
    List.iter (fun (i,j) -> Printf.printf "%d %d\n" i j) (List.sort compare !lis)


Omkar and Akmar are playing a game on a circular board with $$$n$$$ ($$$2 \leq n \leq 10^6$$$) cells. The cells are numbered from $$$1$$$ to $$$n$$$ so that for each $$$i$$$ ($$$1 \leq i \leq n-1$$$) cell $$$i$$$ is adjacent to cell $$$i+1$$$ and cell $$$1$$$ is adjacent to cell $$$n$$$. Initially, each cell is empty.Omkar and Akmar take turns placing either an A or a B on the board, with Akmar going first. The letter must be placed on an empty cell. In addition, the letter cannot be placed adjacent to a cell containing the same letter. A player loses when it is their turn and there are no more valid moves.Output the number of possible distinct games where both players play optimally modulo $$$10^9+7$$$. Note that we only consider games where some player has lost and there are no more valid moves.Two games are considered distinct if the number of turns is different or for some turn, the letter or cell number that the letter is placed on were different.A move is considered optimal if the move maximizes the player's chance of winning, assuming the other player plays optimally as well. More formally, if the player who has to move has a winning strategy, they have to make a move after which they will still have a winning strategy. If they do not, they can make any move.

The only line will contain an integer $$$n$$$ ($$$2 \leq n \leq 10^6$$$) — the number of cells on the board.

Output a single integer — the number of possible distinct games where both players play optimally modulo $$$10^9+7$$$.

NoteFor the first sample case, the first player has $$$4$$$ possible moves. No matter what the first player plays, the second player only has $$$1$$$ possible move, so there are $$$4$$$ possible games.

let p = 1_000_000_007L

let ( %% ) x n = let y = Int64.rem x n in if y<0L then Int64.add y n else y
(* Now, arithmetic modulo p, assuming the arguments a and b are in [0,p-1] *)
let ( ** ) a b = Int64.rem (Int64.mul a b) p
let ( ++ ) a b = let y = Int64.add a b in if y >= p then Int64.sub y p else y
let ( -- ) a b = let y = Int64.sub a b in if y<0L then Int64.add y p else y
let long x = Int64.of_int x
let short x = Int64.to_int x

(*
let rec powermod a b =   (* a^b mod p.  b is a short a is a long *)
  if b=0 then 1L else
    let r = powermod a (b lsr 1) in
    let r2 = r**r in
      if b land 1 = 0 then r2 else r2**a
*)

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
(*
let product i j f = fold i j (fun i a -> (f i) ** a) 1L
*)

let inverse a =
  let rec egcd a b =
    (* given a and b this returns (x, y, g) where g = gcd(a,b) and ax+by=g  *)
    if a = 0 then (0,1,b) else
      let (x,y,g) = egcd (b mod a) a in
      (y-(b/a)*x, x, g)
  in
  let (x,_,_) = egcd (short a) (short p) in
  long (if x >= 0 then x else x+(short p))

let init_factorial n =
  let f = Array.make (n+1) 1L in
  for i=1 to n do
    f.(i) <- (long i) ** f.(i-1);
  done;
  f

let binom n k f =  (* n choose k (f is the factoral table) *)
  if k < 0 || n < k then 0L else
    f.(n) ** (inverse f.(k)) ** (inverse f.(n-k))

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

(* Discovered by f_nimber.ml, and subsequently via simple proof, the
   nimber of a position in this game is the number of non-empties in
   the board mod 2.  This means that the second player can always win.
   In fact, it means that any sequence of legal moves is optimal for
   the second player.  Also, if n is odd then the there will be an odd
   number of holes at the end, and if n is even there will be an even
   number of holes at the end.  Thus guaranteeing that the game lasts
   an even number of moves (giving the second player the win.)

   To count the number of distinct games, we consider the games based
   on the number of holes in the final positions.  If I have a board
   with k holes at the end, then we know that each hole is bounded by
   two different labels.  And also a sequence of non-holes alternates
   labels.  Therefore, deleting the holes, the labeled elements must
   simply be alternating.  Thus there are just two possibilities for
   the final labeling of the board.  And the order in which the game
   is filled in is totally arbitrary, thus it is 2(n-k)! .

   This leaves the question of how many arrangements of k non-adjacent
   holes are possible.  Here's a way to evaluate this.  If you take an
   arrangement and for each hole, delete the non-hole before it you
   have an arrangement of k holes in n-k positions.  So you can just
   take (n-k) choose k.  But this does not quite work.  The problem is
   that it does not generate solutions where the first hole is at
   position 0.  So you handle those separately.  Say the first hole is
   at position 0.  So delete it and the non-hole after it.  Now you
   have n-2 positions and k-1 holes to place.  Apply the same trick
   where an additional non-hole is added after each hole.  This gives
   an additional n-2-(k-1) choose (k-1) possibilities.

   So we compute the sum over k of 2(n-k)! * (# arrangements of k
   holes).  That's the answer.
*)

open Printf
open Scanf

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let () =
  let n = read_int () in
  let h = n/2 in  (* the maximum number of holes you can have *)
  let f = init_factorial n in
  let answer = sum (n mod 2) h 2 (fun k ->
    2L ** (f.(n-k)) **
      ((binom (n-k) k f) ++ (binom (n-2-(k-1)) (k-1) f))
  ) in
  printf "%Ld\n" answer


DZY loves planting, and he enjoys solving tree problems.DZY has a weighted tree (connected undirected graph without cycles) containing n nodes (they are numbered from 1 to n). He defines the function g(x, y) (1 ≤ x, y ≤ n) as the longest edge in the shortest path between nodes x and y. Specially g(z, z) = 0 for every z.For every integer sequence p1, p2, ..., pn (1 ≤ pi ≤ n), DZY defines f(p) as . DZY wants to find such a sequence p that f(p) has maximum possible value. But there is one more restriction: the element j can appear in p at most xj times.Please, find the maximum possible f(p) under the described restrictions.

The first line contains an integer n (1 ≤ n ≤ 3000). Each of the next n - 1 lines contains three integers ai, bi, ci (1 ≤ ai, bi ≤ n; 1 ≤ ci ≤ 10000), denoting an edge between ai and bi with length ci. It is guaranteed that these edges form a tree. Each of the next n lines describes an element of sequence x. The j-th line contains an integer xj (1 ≤ xj ≤ n).

Print a single integer representing the answer.

NoteIn the first sample, one of the optimal p is [4, 3, 2, 1].

open Printf
open Scanf

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

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

let () =
  let n = read_int () in
  let tree = Array.init (n-1) (
    fun _ ->
      let a = read_int() -1 in
      let b = read_int() -1 in
      let c = read_int() in
      (a,b,c)
  ) in

  let x = Array.init n (fun _ -> read_int()) in
  let xtotal = sum 0 (n-1) (fun i -> x.(i)) in

  Array.sort (fun (_,_,c1) (_,_,c2) -> compare c1 c2) tree;

  let s = Array.make n (-1) in  (* the sets *)
  let size = Array.make n 1 in  (* sizes of the sets *)
  let xsize = Array.init n (fun i -> x.(i)) in  (* the x sizes of the sets *)

  let rec find i = if s.(i) < 0 then i else
    let r = find s.(i) in
      s.(i) <- r;
      r
  in

  let union i j =
    let (i,j) = ((find i), (find j)) in
      if i <> j then (
	let (i,j) = if size.(i) < size.(j) then (i,j) else (j,i) in
	s.(i) <- j; (* union by rank *)
	size.(j) <- size.(i) + size.(j);
	xsize.(j) <- xsize.(i) + xsize.(j);
      )
  in

  let rec loop i =
    let (a,b,c) = tree.(i) in
    union a b;
    (* now check if "the condition" holds after the union *)
    let a = find a in
    if size.(a) <= xtotal - xsize.(a) then loop (i+1) else c
  in

  if n=1 then printf "0\n" else
    printf "%d\n" (loop 0)


An infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it either to the beginning of the train, or to the end of the train, at his desire. What is the minimum number of actions David Blaine needs to perform in order to sort the train?

The first line of the input contains integer n (1 ≤ n ≤ 100 000) — the number of cars in the train.  The second line contains n integers pi (1 ≤ pi ≤ n, pi ≠ pj if i ≠ j) — the sequence of the numbers of the cars in the train.

Print a single integer — the minimum number of actions needed to sort the railway cars.

NoteIn the first sample you need first to teleport the 4-th car, and then the 5-th car to the end of the train.

let n = read_int() and ind = Array.make 100001 0 and ans = ref 1;;
let a = Array.of_list (List.map (int_of_string) (Str.split (Str.regexp " ") (read_line())));;
for i = 0 to n - 1 do
	if a.(i) ==  1 then Array.set ind 1 1 else
	begin
		Array.set ind a.(i) (ind.(a.(i) - 1) + 1);
		ans := max !ans ind.(a.(i))
end done;;
print_int (n - !ans)

(* took 1:15 to get this *)

(* Invert the permutation, and call it x.  Now the operation is to
   pick an element from the outside and put it somewhere in the
   middle.  Make a set that contains i if x.(i) and x.(i+1) are
   inverted.  Add 0 and n into the set.  Now take the biggest gap
   between neighbors in this set.  n minus this is the answer.

   This is a lower and upper bound on the number of moves needed.
   It's an upper bound because you can clearly do it by building up
   the longest sorted region (i.e. biggest gap) in that many steps.
   It's a lower bound because for each neighboring pair that are
   inverted we must reach (from one end or the other) one of those
   elements.  The answer computed above gives the most efficient way
   to do this.
*)

open Printf
open Scanf

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

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let p = Array.init n (fun _ -> read_int() -1) in
  let x = Array.make n 0 in
  for i=0 to n-1 do
    x.(p.(i)) <- i
  done;

  let rec makel i ac = if i=n then n::ac else
      let ac = if x.(i-1) > x.(i) then (i::ac) else ac in
      makel (i+1) ac
  in
  let lg = Array.of_list (List.rev (makel 1 [0])) in
  let nn = Array.length lg in
  let answer = n - maxf 0 (nn-2) (fun i -> lg.(i+1) - lg.(i)) in
  printf "%d\n" answer

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

let () =
  let n = read_int () in
  let a = Array.init n (fun _ -> read_int ()) in
  let bio = Array.make (n+1) 0 in
  let _ = Array.iter (fun x -> bio.(x) <- bio.(x-1) + 1) a in
  let ans = n - (Array.fold_left max 0 bio) in
  Printf.printf "%d\n" ans

(*
#load "str.cma";;
#load "nums.cma";;
*)
let n = read_int  () and ans = ref 0 and m = ref 99999999999L;;
let a = Array.of_list (List.map (Int64.of_string) (Str.split (Str.regexp " ") (read_line ())));;
for i = n - 1 downto 0 do
	if Int64.compare a.(i) !m < 0 then m := a.(i);
	if Int64.compare a.(i) !m > 0 then ans := !ans + 1;
done;;
print_int !ans;;

let n = read_int  () and ans = ref 0 and m = ref 9999999;;
let a = Array.of_list (List.map (int_of_string) (Str.split (Str.regexp " ") (read_line ())));;
for i = n - 1 downto 0 do
	if a.(i) < !m then m := a.(i);
	if a.(i) > !m then ans := !ans + 1;
done;;
print_int !ans

let n = read_int  () and ans = ref 0 and m = ref 999999999L;;
let a = Array.of_list (List.map (Int64.of_string) (Str.split (Str.regexp " ") (read_line ())));;
for i = n - 1 downto 0 do
	if a.(i) < !m then m := a.(i);
	if a.(i) > !m then ans := !ans + 1;
done;;
print_int !ans


Polycarp has found a table having an infinite number of rows and columns. The rows are numbered from $$$1$$$, starting from the topmost one. The columns are numbered from $$$1$$$, starting from the leftmost one.Initially, the table hasn't been filled and Polycarp wants to fix it. He writes integers from $$$1$$$ and so on to the table as follows.  The figure shows the placement of the numbers from $$$1$$$ to $$$10$$$. The following actions are denoted by the arrows. The leftmost topmost cell of the table is filled with the number $$$1$$$. Then he writes in the table all positive integers beginning from $$$2$$$ sequentially using the following algorithm.First, Polycarp selects the leftmost non-filled cell in the first row and fills it. Then, while the left neighbor of the last filled cell is filled, he goes down and fills the next cell. So he goes down until the last filled cell has a non-filled neighbor to the left (look at the vertical arrow going down in the figure above).After that, he fills the cells from the right to the left until he stops at the first column (look at the horizontal row in the figure above). Then Polycarp selects the leftmost non-filled cell in the first row, goes down, and so on.A friend of Polycarp has a favorite number $$$k$$$. He wants to know which cell will contain the number. Help him to find the indices of the row and the column, such that the intersection of the row and the column is the cell containing the number $$$k$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing one integer $$$k$$$ ($$$1 \le k \le 10^9$$$) which location must be found.

For each test case, output in a separate line two integers $$$r$$$ and $$$c$$$ ($$$r, c \ge 1$$$) separated by spaces — the indices of the row and the column containing the cell filled by the number $$$k$$$, respectively.

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

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

let print_numbers x y = print_number x; print_number y;;

let t = readInt() in
for i = 1 to t do
  let k = readInt() in
  let x = int_of_float (ceil (sqrt (float_of_int k))) in
  let q = k - (x - 1) * (x - 1) in
  if q <= x then
    print_numbers q x
  else
    print_numbers x (2*x - q)
done;;


Little Vova studies programming in an elite school. Vova and his classmates are supposed to write n progress tests, for each test they will get a mark from 1 to p. Vova is very smart and he can write every test for any mark, but he doesn't want to stand out from the crowd too much. If the sum of his marks for all tests exceeds value x, then his classmates notice how smart he is and start distracting him asking to let them copy his homework. And if the median of his marks will be lower than y points (the definition of a median is given in the notes), then his mom will decide that he gets too many bad marks and forbid him to play computer games.Vova has already wrote k tests and got marks a1, ..., ak. He doesn't want to get into the first or the second situation described above and now he needs to determine which marks he needs to get for the remaining tests. Help him do that.

The first line contains 5 space-separated integers: n, k, p, x and y (1 ≤ n ≤ 999, n is odd, 0 ≤ k < n, 1 ≤ p ≤ 1000, n ≤ x ≤ n·p, 1 ≤ y ≤ p). Here n is the number of tests that Vova is planned to write, k is the number of tests he has already written, p is the maximum possible mark for a test, x is the maximum total number of points so that the classmates don't yet disturb Vova, y is the minimum median point so that mom still lets him play computer games. The second line contains k space-separated integers: a1, ..., ak (1 ≤ ai ≤ p) — the marks that Vova got for the tests he has already written.

If Vova cannot achieve the desired result, print "-1". Otherwise, print n - k space-separated integers — the marks that Vova should get for the remaining tests. If there are multiple possible solutions, print any of them.

NoteThe median of sequence a1, ..., an where n is odd (in this problem n is always odd) is the element staying on (n + 1) / 2 position in the sorted list of ai.In the first sample the sum of marks equals 3 + 5 + 4 + 4 + 1 = 17, what doesn't exceed 18, that means that Vova won't be disturbed by his classmates. And the median point of the sequence {1, 3, 4, 4, 5} equals to 4, that isn't less than 4, so his mom lets him play computer games.Please note that you do not have to maximize the sum of marks or the median mark. Any of the answers: "4 2", "2 4", "5 1", "1 5", "4 1", "1 4" for the first test is correct.In the second sample Vova got three '5' marks, so even if he gets two '1' marks, the sum of marks will be 17, that is more than the required value of 16. So, the answer to this test is "-1".

exception Fail

let fait r x y =
	 let total = ref x and res = ref [] in
		for i=1 to r do
			if !total <= r - i
				then raise Fail
				else (let a = min (!total-r+i) y in
					total := !total - a;
					res := a::!res);
		done;
	!res;;

let resout n k x y l =
	let sum = List.fold_left (fun a b -> a+b) 0 l in
	let res = fait (n-k) (x - sum) y in
		res;;

let resultat ini res n y =
	let l = List.sort compare (ini@res) in
		if List.nth l (n/2) >= y
			then begin
			List.iter (fun i -> Printf.printf "%d " i) res
			     end
			else Printf.printf "-1"

let _ =
	let (n,k,x,y) = Scanf.scanf "%d %d %d %d %d"
	(fun a b _ c d -> (a,b,c,d)) and l = ref [] in
		for i=1 to k do
			Scanf.scanf " %d" (fun i -> l:= i::!l);
		done;
	try (
	resultat !l (resout n k x y !l) n y
	) with Fail -> Printf.printf "-1"

exception Fail

let fait r x y =
	 let total = ref x and res = ref [] in
		for i=1 to r do
			if !total <= r - i
				then raise Fail
				else (let a = min (!total-r+i) y in
					total := !total - a;
					res := a::!res);
		done;
	!res;;

let resout n k x y l =
	let sum = List.fold_left (fun a b -> a+b) 0 l in
	let res = fait (n-k) (x - sum - 1) y in
		res;;

let resultat ini res n y =
	let l = List.sort compare (ini@res) in
		if List.nth l (n/2) >= y
			then begin
				List.iter (fun i -> Printf.printf "%d " i) res
			     end
			else Printf.printf "-1"

let _ =
	let (n,k,x,y) = Scanf.scanf "%d %d %d %d %d"
	(fun a b _ c d -> (a,b,c,d)) and l = ref [] in
		for i=1 to k do
			Scanf.scanf " %d" (fun i -> l:= i::!l);
		done;
	try (
	resultat !l (resout n k x y !l) n y
	) with Fail -> Printf.printf "-1"


You are given a rectangular field of n × m cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side.Let's call a connected component any non-extendible set of cells such that any two of them are connected by the path of adjacent cells. It is a typical well-known definition of a connected component.For each impassable cell (x, y) imagine that it is an empty cell (all other cells remain unchanged) and find the size (the number of cells) of the connected component which contains (x, y). You should do it for each impassable cell independently.The answer should be printed as a matrix with n rows and m columns. The j-th symbol of the i-th row should be "." if the cell is empty at the start. Otherwise the j-th symbol of the i-th row should contain the only digit —- the answer modulo 10. The matrix should be printed without any spaces.To make your output faster it is recommended to build the output as an array of n strings having length m and print it as a sequence of lines. It will be much faster than writing character-by-character.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

The first line contains two integers n, m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the field. Each of the next n lines contains m symbols: "." for empty cells, "*" for impassable cells.

Print the answer as a matrix as described above. See the examples to precise the format of the output.

NoteIn first example, if we imagine that the central cell is empty then it will be included to component of size 5 (cross). If any of the corner cell will be empty then it will be included to component of size 3 (corner).

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 (n,m) = read2 ();;

let ruch x y = [ (x+1,y); (x-1,y); (x,y+1); (x,y-1) ];;

let czy_dobry x y tab =
  if x < 0 || x >= n || y < 0 || y >= m then false
  else if tab.(x).(y) = '*' then false
  else true;;

let rec bfs ax ay k tab vis fuf size =
  let kol = Queue.create () in
  Queue.add (ax,ay) kol;
  vis.(ax).(ay) <- true;
  while not (Queue.is_empty kol) do
    let (x,y) = Queue.take kol in
    fuf.(x).(y) <- k;
    match k with
    | (a,b) -> size.(a).(b) <- size.(a).(b) + 1;
    List.iter ( fun (a,b) -> if (czy_dobry a b tab && not vis.(a).(b)) then begin vis.(a).(b) <- true; Queue.add (a,b) kol end ) ( ruch x y )
  done;;

let wynik x y tab fuf size =
  let ruchy = List.filter ( fun (x,y) -> czy_dobry x y tab ) (ruch x y) in
  List.fold_left (fun a (x,y) -> a + size.(x).(y)) 0
  (
    List.fold_left (fun a (x,y) -> if
      (List.fold_left (fun a b -> if b = fuf.(x).(y) then false else a ) true a )
      then fuf.(x).(y)::a else a ) [] ruchy
  );;

let _ =
  let tab = Array.make_matrix n m '.'
  and vis = Array.make_matrix n m false
  and fuf = Array.make_matrix n m (0,0)
  and size = Array.make_matrix n m 0 in
  for i=0 to (n-1) do
    let s = Scanf.scanf "%s\n" (fun x -> x) in
    for j=0 to (m-1) do
      tab.(i).(j) <- s.[j];
      fuf.(i).(j) <- (i,j)
    done
  done;
  for i =0 to (n-1) do
    for j=0 to (m-1) do
      if czy_dobry i j tab && not vis.(i).(j) then
      bfs i j (i,j) tab vis fuf size
    done
  done;
  for i=0 to (n-1) do
    for j=0 to (m-1) do
      if tab.(i).(j) = '.' then
        Printf.printf "."
      else Printf.printf "%d" ( ( wynik i j tab fuf size + 1) mod 10 )
    done;
    Printf.printf "\n"
  done;;

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

let () =
  let n = xint() and m = xint() in
  let upp = n * m / 2 + 1 in
  let mark = Array.make_matrix n m ~-1 in
  let cnt = Array.make upp 0 in
  let s = Array.make n "a" in
  for i = 0 to n - 1 do
    s.(i) <- xstr();
  done;
  let qx = Array.make (n * m) 0 in
  let qy = Array.make (n * m) 0 in
  let dx = Array.make 4 0 and dy = Array.make 4 0 in
  dx.(2) <- 1;
  dx.(3) <- ~-1;
  dy.(0) <- 1;
  dy.(1) <- ~-1;
  let idx = ref 0 in
  let bfs sx sy =
    let h = ref 0 and t = ref 1 in
    qx.(0) <- sx;
    qy.(0) <- sy;
    mark.(sx).(sy) <- !idx;
    while !h < !t do
      let x = qx.(!h) and y = qy.(!h) in
      h := !h + 1;
      for i = 0 to 3 do
        let xx = x + dx.(i) in
        let yy = y + dy.(i) in
        if xx >= 0 && xx < n && yy >= 0 && yy < m then (
          if s.(xx).[yy] = '.' && mark.(xx).(yy) = -1 then (
            mark.(xx).(yy) <- !idx;
            qx.(!t) <- xx;
            qy.(!t) <- yy;
            t := !t + 1;
          )
        )
      done;
    done;
    cnt.(!idx) <- !t;
  in

  let gao x y =
    let a = Array.make 4 ~-1 in
    for i = 0 to 3 do
      let xx = x + dx.(i) and yy = y + dy.(i) in
      if xx >= 0 && xx < n && yy >= 0 && yy < m then (
        a.(i) <- mark.(xx).(yy)
      )
    done;
    Array.sort (fun x y -> if x < y then -1 else (if x > y then 1 else 0)) a;
    let sum = ref 1 in
    for i = 0 to 3 do
      if a.(i) != ~-1 then (
        if i = 0 || a.(i) != a.(i - 1) then (
          sum := !sum + cnt.(a.(i))
        )
      )
    done;
    sum := !sum mod 10;
    Char.chr (48 + !sum)
  in

  for i = 0 to n - 1 do
    for j = 0 to m - 1 do
      if s.(i).[j] = '.' && mark.(i).(j) = -1 then (
        bfs i j;
        idx := !idx + 1;
      );
    done;
  done;
  for i = 0 to n - 1 do
    for j = 0 to m - 1 do
      s.(i).[j] <- (if s.(i).[j] = '*' then (gao i j) else '.');
    done;
    Printf.printf "%s\n" s.(i);
  done;

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 (n,m) = read2 ();;

let ruch x y = [ (x+1,y); (x-1,y); (x,y+1); (x,y-1) ];;

let czy_dobry x y tab =
  if x < 0 || x >= n || y < 0 || y >= m then false
  else if tab.(x).(y) = '*' then false
  else true;;

let rec dfs x y k tab vis fuf size =
  if not (czy_dobry x y tab) || vis.(x).(y) then ()
  else begin
  vis.(x).(y) <- true;
  fuf.(x).(y) <- k;
  match k with
  | (a,b) -> size.(a).(b) <- size.(a).(b) + 1;
  List.iter ( fun (a,b) -> dfs a b k tab vis fuf size ) ( ruch x y ) end;;

let wynik x y tab fuf size =
  let ruchy = List.filter ( fun (x,y) -> czy_dobry x y tab ) (ruch x y) in
  List.fold_left (fun a (x,y) -> a + size.(x).(y)) 0
  (
    List.fold_left (fun a (x,y) -> if
      (List.fold_left (fun a b -> if b = fuf.(x).(y) then false else a ) true a )
      then fuf.(x).(y)::a else a ) [] ruchy
  );;

let _ =
  let tab = Array.make_matrix n m '.'
  and vis = Array.make_matrix n m false
  and fuf = Array.make_matrix n m (0,0)
  and size = Array.make_matrix n m 0 in
  for i=0 to (n-1) do
    let s = Scanf.scanf "%s\n" (fun x -> x) in
    for j=0 to (m-1) do
      tab.(i).(j) <- s.[j];
      fuf.(i).(j) <- (i,j)
    done
  done;
  for i =0 to (n-1) do
    for j=0 to (m-1) do
      dfs i j (i,j) tab vis fuf size
    done
  done;
  for i=0 to (n-1) do
    for j=0 to (m-1) do
      if tab.(i).(j) = '.' then
        Printf.printf "."
      else Printf.printf "%d" ( wynik i j tab fuf size + 1)
    done;
    Printf.printf "\n"
  done;;


At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite sequence of Picks.Fortunately, Picks remembers how to repair the sequence. Initially he should create an integer array a[1], a[2], ..., a[n]. Then he should perform a sequence of m operations. An operation can be one of the following:  Print operation l, r. Picks should write down the value of .  Modulo operation l, r, x. Picks should perform assignment a[i] = a[i] mod x for each i (l ≤ i ≤ r).  Set operation k, x. Picks should set the value of a[k] to x (in other words perform an assignment a[k] = x). Can you help Picks to perform the whole sequence of operations?

The first line of input contains two integer: n, m (1 ≤ n, m ≤ 105). The second line contains n integers, separated by space: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109) — initial value of array elements. Each of the next m lines begins with a number type .    If type = 1, there will be two integers more in the line: l, r (1 ≤ l ≤ r ≤ n), which correspond the operation 1.  If type = 2, there will be three integers more in the line: l, r, x (1 ≤ l ≤ r ≤ n; 1 ≤ x ≤ 109), which correspond the operation 2.  If type = 3, there will be two integers more in the line: k, x (1 ≤ k ≤ n; 1 ≤ x ≤ 109), which correspond the operation 3.

For each operation 1, please print a line containing the answer. Notice that the answer may exceed the 32-bit integer.

NoteConsider the first testcase:  At first, a = {1, 2, 3, 4, 5}.  After operation 1, a = {1, 2, 3, 0, 1}.  After operation 2, a = {1, 2, 5, 0, 1}.  At operation 3, 2 + 5 + 0 + 1 = 8.  After operation 4, a = {1, 2, 2, 0, 1}.  At operation 5, 1 + 2 + 2 = 5.

(**D. The Child and Sequence*)

open Scanf;;
open Num;;
open Printf;;

let (n,m) = Scanf.bscanf Scanf.Scanning.stdin "%d %d " ( fun x y -> (x,y));;

(*Read the sequence*)
type node = {mutable l:int; mutable r:int; mutable mid:int; mutable maxx:int; mutable sum:num};;
let tree = Array.init ( 4 * n + 4 ) (fun _ -> {l=0;r=0;maxx=0; mid=0; sum = num_of_int 0});;

let rec build l r now =
    tree.(now).l <- l; tree.(now).r<-r; tree.(now).mid<- ((l+r)/2);
    if l = r then
        let x = Scanf.bscanf Scanf.Scanning.stdin "%d " ( fun x -> x) in
        tree.(now).maxx<-x;tree.(now).sum <- num_of_int x
    else
        let twonow = 2 * now in
        build l tree.(now).mid twonow;
        build (tree.(now).mid + 1) r (twonow + 1);
        tree.(now).sum <- Num.add_num tree.(twonow).sum tree.(twonow + 1).sum;
        tree.(now).maxx <- max tree.(twonow).maxx tree.(twonow + 1).maxx
in build 1 n 1 (*Note tree.(0) is not used*)

let rec query l r now =
    if tree.(now).l=l && tree.(now).r=r then
        tree.(now).sum
    else if l > tree.(now).mid then
        query l r (2*now + 1)
    else if r <= tree.(now).mid then
        query l r (2*now)
    else
        Num.add_num (query  l tree.(now).mid (2*now)) (query (tree.(now).mid + 1) r (
            2*now + 1))
;;

let rec mod_op l r x now = match now with
  |_ when  tree.(now).maxx < x -> ();
  |_ when tree.(now).l = tree.(now).r ->
    ( tree.(now).sum <- Num.mod_num tree.(now).sum (Num.num_of_int x);
       tree.(now).maxx <- Num.int_of_num tree.(now).sum )
  |_ ->(
      (
      match l with
      |_ when l > tree.(now).mid -> mod_op l r x (2*now+1)
      |_ when r <= tree.(now).mid -> mod_op l r x (2*now)
      |_ ->( mod_op l tree.(now).mid x (2*now);
             mod_op (tree.(now).mid + 1) r x (2*now + 1) )
      );
      tree.(now).sum <- Num.add_num tree.(2*now).sum
          tree.(2*now+1).sum;
      tree.(now).maxx <- max tree.(2*now).maxx tree.(2*now+1).maxx
    )
;;

let rec set_op k x now = match now with
  |_ when tree.(now).l = k && tree.(now).r = k ->
    tree.(now).maxx <- x;
    tree.(now).sum <- Num.num_of_int x
  |_ ->(
      (match k with
       |_ when k > tree.(now).mid  -> set_op k x (2*now+1)
       |_ -> set_op k x (2*now)
      );
      tree.(now).sum <- Num.add_num tree.(2*now).sum tree.(2*now+1).sum;
      tree.(now).maxx <- max tree.(2*now).maxx tree.(2*now+1).maxx
    )
;;

let print_info () =
  printf  "%s " "array: ";
  for i = 1 to n do
    printf "%s  "  (Num.string_of_num (query i i 1) )
  done;
  print_endline ""
;;

let print_info () = ()
;;

for i = 0 to m - 1 do
  let x = Scanf.bscanf Scanf.Scanning.stdin "%d " ( fun x -> x) in
  (*print_int x; print_endline "";*)
  match x with
  | 1  -> let (l,r) = Scanf.bscanf Scanf.Scanning.stdin "%d %d " (
      fun x y -> (x,y) ) in let rslt = query l r 1 in
    print_endline (Num.string_of_num rslt);
    print_info ()
  | 2 -> let (l,r,x) = Scanf.bscanf Scanf.Scanning.stdin "%d %d %d " (fun x
                                                                       y z -> (x,y,z)) in
    mod_op l r x 1; print_info ()
  | 3 -> let (k,x) = Scanf.bscanf Scanf.Scanning.stdin "%d %d " (
      fun x y -> (x,y) ) in
    set_op k x 1; print_info ()
done
;;

(**D. The Child and Sequence*)

open Scanf;;
open Num;;

let (n,m) = Scanf.bscanf Scanf.Scanning.stdin "%d %d " ( fun x y -> (x,y));;

let arr = Array.create n 0;;
for i = 0 to n - 1 do
  let x = Scanf.bscanf Scanf.Scanning.stdin "%d " ( fun x -> x) in
  arr.(i) <- x
done
;;

for i =0 to m  - 1 do
  let x = Scanf.bscanf Scanf.Scanning.stdin "%d " ( fun x -> x) in
  match x with
  | 1  -> let (l,r) = Scanf.bscanf Scanf.Scanning.stdin "%d %d " (
      fun x y -> (x,y) ) in let s = ref 0 in
    for j = l - 1 to r - 1 do
      s := !s + arr.(j)
    done; print_int !s; print_endline ""
  | 2 -> let (l,r,x) = Scanf.bscanf Scanf.Scanning.stdin "%d %d %d " (fun x
                                                                      y z -> (x,y,z)) in
      for j = l - 1 to r - 1  do
        arr.(j) <- arr.(j) mod x
      done;
  | 3 -> let (k,x) = Scanf.bscanf Scanf.Scanning.stdin "%d %d " (
      fun x y -> (x,y) ) in
    arr.(k - 1) <- x
done
;;

(*-------------Back up-------------*)

(* The next m lines*)

(* test
 *
let print_tuple x = match x with
    | (n, m) -> print_int n; print_string " "; print_int m; print_endline "";;

print_tuple nm;;
*)

(** The early version of my program.
 *
let n = ref 0;;
let m = ref 0;;

let line1 =  input_line stdin;;
let nm = Scanf.sscanf line1 "%d %d" ( fun x y -> (x, y) );;
let f x = match x with
| (x,y) -> n := x; m := y
in f nm;;
*)

(**D. The Child and Sequence*)

open Scanf;;

let (n,m) = Scanf.bscanf Scanf.Scanning.stdin "%d %d " ( fun x y -> (x,y));;

let arr = Array.create n 0;;
for i = 0 to n - 1 do
  let x = Scanf.bscanf Scanf.Scanning.stdin "%d " ( fun x -> x) in
  arr.(i) <- x
done
;;

for i =0 to m  - 1 do
  let x = Scanf.bscanf Scanf.Scanning.stdin "%d " ( fun x -> x) in
  match x with
  | 1  -> let (l,r) = Scanf.bscanf Scanf.Scanning.stdin "%d %d " (
      fun x y -> (x,y) ) in let s = ref 0 in
    for j = l - 1 to r - 1 do
      s := !s + arr.(j)
    done; print_int !s; print_endline ""
  | 2 -> let (l,r,x) = Scanf.bscanf Scanf.Scanning.stdin "%d %d %d " (fun x
                                                                      y z -> (x,y,z)) in
      for j = l - 1 to r - 1  do
        arr.(j) <- arr.(j) mod x
      done;
  | 3 -> let (k,x) = Scanf.bscanf Scanf.Scanning.stdin "%d %d " (
      fun x y -> (x,y) ) in
    arr.(k - 1) <- x
done
;;

(*-------------Back up-------------*)

(* The next m lines*)

(* test
 *
let print_tuple x = match x with
    | (n, m) -> print_int n; print_string " "; print_int m; print_endline "";;

print_tuple nm;;
*)

(** The early version of my program.
 *
let n = ref 0;;
let m = ref 0;;

let line1 =  input_line stdin;;
let nm = Scanf.sscanf line1 "%d %d" ( fun x y -> (x, y) );;
let f x = match x with
| (x,y) -> n := x; m := y
in f nm;;
*)


You are given a sorted array $$$a_1, a_2, \dots, a_n$$$ (for each index $$$i > 1$$$ condition $$$a_i \ge a_{i-1}$$$ holds) and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$max(i)$$$ be equal to the maximum in the $$$i$$$-th subarray, and $$$min(i)$$$ be equal to the minimum in the $$$i$$$-th subarray. The cost of division is equal to $$$\sum\limits_{i=1}^{k} (max(i) - min(i))$$$. For example, if $$$a = [2, 4, 5, 5, 8, 11, 19]$$$ and we divide it into $$$3$$$ subarrays in the following way: $$$[2, 4], [5, 5], [8, 11, 19]$$$, then the cost of division is equal to $$$(4 - 2) + (5 - 5) + (19 - 8) = 13$$$.Calculate the minimum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ 1 \le a_i \le 10^9$$$, $$$a_i \ge a_{i-1}$$$).

Print the minimum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays.

NoteIn the first test we can divide array $$$a$$$ in the following way: $$$[4, 8, 15, 16], [23], [42]$$$.

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

let solve n k a =
  let open Array in
  let d = init (n-1) (fun i -> a.(i+1) - a.(i)) in
  fast_sort compare d;
  let rec go sum i =
    if i >= n-1 then sum
    else go (sum + d.(i)) (i + 1)
  in a.(n-1) - a.(0) - go 0 (n-k)

let main () =
  let n = readInt () in
  let k = readInt () in
  let a = Array.init n (fun _ -> readInt ()) in
  Printf.printf "%d\n" (solve n k a)

let () = main ()


Vasya has got three integers $$$n$$$, $$$m$$$ and $$$k$$$. He'd like to find three integer points $$$(x_1, y_1)$$$, $$$(x_2, y_2)$$$, $$$(x_3, y_3)$$$, such that $$$0 \le x_1, x_2, x_3 \le n$$$, $$$0 \le y_1, y_2, y_3 \le m$$$ and the area of the triangle formed by these points is equal to $$$\frac{nm}{k}$$$.Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them.

If there are no such points, print "NO". Otherwise print "YES" in the first line. The next three lines should contain integers $$$x_i, y_i$$$ — coordinates of the points, one point per line. If there are multiple solutions, print any of them. You can print each letter in any case (upper or lower).

NoteIn the first example area of the triangle should be equal to $$$\frac{nm}{k} = 4$$$. The triangle mentioned in the output is pictured below:   In the second example there is no triangle with area $$$\frac{nm}{k} = \frac{16}{7}$$$.

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

let repm from_ to_ ?(stride=1) m_init fbod =
	let i,f,m = ref ~|from_,ref true,ref m_init in
	while !i <= ~|to_ && !f do
		match fbod !m (~~| !i) with
		| `Break -> f := false
		| `Break_m m' -> (f := false; m := m')
		| `Ok m' -> (i := !i +$ 1; m := m')
	done; !m

let () =
	let n,m,k = get_3_i64 0 in
	(
		(* (0,0),(p,q),(r,s) -> 2S = |ps-qr| ∈ Z *)
		if 2L*n*m mod k <> 0L then printf "NO\n"
		else (
			printf "YES\n0 0\n";
			let x,y = (
				let n,m,k = ref (2L*n),ref m,ref k in
				while !k <> 1L do
					let g = gcd !n !k in if g > 1L then (
						n := !n / g;
						k := !k / g);
					let g = gcd !m !k in if g > 1L then (
						m := !m / g;
						k := !k / g)
				done; (!n,!m)
			) in
			if x > n && x mod 2L = 0L && y * 2L <= m then (
				printf "%Ld 0\n0 %Ld\n" (x/2L) (y*2L)
			) else printf "%Ld 0\n0 %Ld\n" x y
		)
	)

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

let repm from_ to_ ?(stride=1) m_init fbod =
	let i,f,m = ref ~|from_,ref true,ref m_init in
	while !i <= ~|to_ && !f do
		match fbod !m (~~| !i) with
		| `Break -> f := false
		| `Break_m m' -> (f := false; m := m')
		| `Ok m' -> (i := !i +$ 1; m := m')
	done; !m

let () =
	let n,m,k = get_3_i64 0 in
	(
		(* (0,0),(p,q),(r,s) -> 2S = |ps-qr|  Z *)
		if 2L*n*m mod k <> 0L then printf "NO\n"
		else (
			printf "YES\n0 0\n";
			let x,y = (
				let n,m,k = ref (2L*n),ref m,ref k in
				while !k <> 1L do
					let g = gcd !n !k in if g > 1L then (
						n := !n / g;
						k := !k / g);
					let g = gcd !m !k in if g > 1L then (
						m := !m / g;
						k := !k / g)
				done; (!n,!m)
			) in
			if x > n && x mod 2L = 0L && y * 2L <= m then (
				printf "%Ld 0\n0 %Ld\n" (x/2L) (y*2L)
			) else printf "%Ld 0\n0 %Ld\n" x y
		)
	)


Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following.Iahub wants to draw n distinct segments [li, ri] on the OX axis. He can draw each segment with either red or blue. The drawing is good if and only if the following requirement is met: for each point x of the OX axis consider all the segments that contains point x; suppose, that rx red segments and bx blue segments contain point x; for each point x inequality |rx - bx| ≤ 1 must be satisfied.A segment [l, r] contains a point x if and only if l ≤ x ≤ r.Iahub gives you the starting and ending points of all the segments. You have to find any good drawing for him.

The first line of input contains integer n (1 ≤ n ≤ 105) — the number of segments. The i-th of the next n lines contains two integers li and ri (0 ≤ li ≤ ri ≤ 109) — the borders of the i-th segment. It's guaranteed that all the segments are distinct.

If there is no good drawing for a given test, output a single integer -1. Otherwise output n integers; each integer must be 0 or 1. The i-th number denotes the color of the i-th segment (0 is red and 1 is blue). If there are multiple good drawings you can output any of them.

open Printf
open Scanf

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

  let seg = Array.make nn 0 in
  let nbr = Array.make nn 0 in

  let h = Hashtbl.create 10 in
  let add_to_h x e =
    let li = try Hashtbl.find h x with Not_found -> [] in
    Hashtbl.replace h x (e::li)
  in

  for i=0 to n-1 do
    let l = read_int() in
    let r = read_int() + 1 in
    let le = 2*i in
    let re = 2*i+1 in
    seg.(le) <- re;
    seg.(re) <- le;

    add_to_h l le;
    add_to_h r re;
  done;

  let allpoints = Hashtbl.fold (fun k _ ac -> k::ac) h [] in
  let allpoints = List.sort compare allpoints in

  let allends =
    List.fold_left (
      fun ac x ->
	let pts = Hashtbl.find h x in
	pts @ ac
    ) [] allpoints
  in

  let rec loop = function [] -> ()
    | (a::(b::rest)) ->
      nbr.(a) <- b;
      nbr.(b) <- a;
      loop rest
    | _ -> failwith "odd length list"
  in

  loop allends;

  let label = Array.make nn (-1) in

(*
  let rec label_cycle i bit =
    if label.(i) < 0 then (
      label.(i) <- bit;
      if bit=0 then label_cycle nbr.(i) 1
      else label_cycle seg.(i) 0
    )
  in
*)

  let rec label_cycle i =
    if label.(i) < 0 then (
      label.(i) <- 0;
      label.(nbr.(i)) <- 1;
      label_cycle seg.(nbr.(i))
    )
  in

  for i=0 to nn-1 do
    if label.(i) < 0 then label_cycle i
  done;

  for i=0 to n-1 do
    if i>0 then printf " ";
    printf "%d" label.(2*i);
  done;

  print_newline();