While Vasya finished eating his piece of pizza, the lesson has already started. For being late for the lesson, the teacher suggested Vasya to solve one interesting problem. Vasya has an array a and integer x. He should find the number of different ordered pairs of indexes (i, j) such that ai ≤ aj and there are exactly k integers y such that ai ≤ y ≤ aj and y is divisible by x.In this problem it is meant that pair (i, j) is equal to (j, i) only if i is equal to j. For example pair (1, 2) is not the same as (2, 1).

The first line contains 3 integers n, x, k (1 ≤ n ≤ 105, 1 ≤ x ≤ 109, 0 ≤ k ≤ 109), where n is the size of the array a and x and k are numbers from the statement. The second line contains n integers ai (1 ≤ ai ≤ 109) — the elements of the array a.

Print one integer — the answer to the problem.

NoteIn first sample there are only three suitable pairs of indexes — (1, 2), (2, 3), (3, 4).In second sample there are four suitable pairs of indexes(1, 1), (2, 2), (3, 3), (4, 4).In third sample every pair (i, j) is suitable, so the answer is 5 * 5 = 25.

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 read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)

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

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

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

  let divisors_up_to ai = ai/x in

  if k=0 then (
    let h0 = Hashtbl.create 10 in
    let h1 = Hashtbl.create 10 in

    for i=0 to n-1 do
      if a.(i) mod x <> 0 then (
	increment h0 (divisors_up_to a.(i));
	increment h1 a.(i);
      )
    done;

    let ordered = Hashtbl.fold (fun _ count0 ac ->
      ac ++ ((long count0) ** (long (count0 - 1))) // 2L
    ) h0 0L in

    let correction = Hashtbl.fold (fun _ c2 ac ->
      let c2 = long c2 in
      ac ++ c2 ** c2 -- (c2 ** (c2 -- 1L))//2L
    ) h1 0L in

    printf "%Ld\n" (ordered ++ correction)

  ) else (
    let h0 = Hashtbl.create 10 in
    let h1 = Hashtbl.create 10 in

  (* let d(a.(i)) be the number of numbers in 1, 2, ..., a.(i) divisible by x.
     This table stores key value pairs (k,v) where v = the number of a.(i) such
     that d.(a.(i)) = k.
  *)

    for i=0 to n-1 do
      increment h0 (divisors_up_to a.(i));
      increment h1 (divisors_up_to (a.(i)-1))
    done;

  (* think k >= 2 and solve it and then check k=0 or 1 later *)

    let answer = Hashtbl.fold (fun d0 count0 ac ->
      let count1 = try Hashtbl.find h1 (d0-k) with Not_found -> 0 in
      ac ++ ((long count0) ** (long count1))
    ) h0 0L in

    printf "%Ld\n" answer
  )

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 read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)

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

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

  Array.sort compare a;

  let same_as_previous i =
  (* i > 0 *)
    a.(i-1) = a.(i) || (a.(i-1) mod x <> 0 && a.(i) mod x <> 0 && a.(i-1)/x = a.(i)/x)
  in

  let rec compress i c ac = if i=n then (a.(i-1),c)::ac else (
    if same_as_previous i then compress (i+1) (c+1) ac
    else compress (i+1) 1 ((a.(i-1),c)::ac)
  )
  in

  let clist = List.rev (compress 1 1 []) in
  let nn = List.length clist in
  let b = Array.make nn 0 in
  let bcount = Array.make nn 0L in
  List.iteri (fun i (v,c) -> b.(i) <- v; bcount.(i) <- long c) clist;

  (*
  for i=0 to nn-1 do
    printf "b.(%d) = %d  bcount.(%d) = %Ld\n" i b.(i) i bcount.(i)
  done;
  *)

  let count_divisible_by a b x =
  (* number of a <= y <=b divisible by x *)
    let a' = a + (x - (a mod x)) mod x in (* next number >= a to be divisible by x *)
    let b' = b - (b mod x) in (* first number <= b to be divisible by x *)
    if b' < a' then 0 else (b'+x-a') / x
  in

  let rec scan i j ac = if j = nn then ac else (
  (* i <= j *)
    let c = count_divisible_by b.(i) b.(j) x in
    if c = k then (
(*      printf "i=%d  j=%d\n" i j; *)
      let blah = bcount.(i) ** bcount.(j) in
      let ac = if i = j then ac ++ blah else ac ++ blah in
      scan i (j+1) ac
    ) else if c < k then scan i (j+1) ac
      else scan (i+1) (max j (i+1)) ac
  ) in

  let answer = scan 0 0 0L in

  printf "%Ld\n" answer

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 read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)

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

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

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

  let divisors_up_to ai = ai/x in

  if k=0 then (
    let h0 = Hashtbl.create 10 in
    let h1 = Hashtbl.create 10 in

    for i=0 to n-1 do
      if a.(i) mod x <> 0 then (
	increment h0 (divisors_up_to a.(i));
	increment h1 a.(i);
      )
    done;

    let ordered = Hashtbl.fold (fun _ count0 ac ->
      ac ++ ((long count0) ** (long (count0 - 1))) // 2L
    ) h0 0L in

    let correction = Hashtbl.fold (fun _ c2 ac ->
      let c2 = long c2 in
      c2 ** c2 -- (c2 ** (c2 -- 1L))//2L
    ) h1 0L in

    printf "%Ld\n" (ordered ++ correction)

  ) else (
    let h0 = Hashtbl.create 10 in
    let h1 = Hashtbl.create 10 in

  (* let d(a.(i)) be the number of numbers in 1, 2, ..., a.(i) divisible by x.
     This table stores key value pairs (k,v) where v = the number of a.(i) such
     that d.(a.(i)) = k.
  *)

    for i=0 to n-1 do
      increment h0 (divisors_up_to a.(i));
      increment h1 (divisors_up_to (a.(i)-1))
    done;

  (* think k >= 2 and solve it and then check k=0 or 1 later *)

    let answer = Hashtbl.fold (fun d0 count0 ac ->
      let count1 = try Hashtbl.find h1 (d0-k) with Not_found -> 0 in
      ac ++ ((long count0) ** (long count1))
    ) h0 0L in

    printf "%Ld\n" answer
  )

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 read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)

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

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

  let h0 = Hashtbl.create 10 in
  let h1 = Hashtbl.create 10 in

  (* let d(a.(i)) be the number of numbers in 1, 2, ..., a.(i) divisible by x.
     This table stores key value pairs (k,v) where v = the number of a.(i) such
     that d.(a.(i)) = k.
  *)

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

  let divisors_up_to ai = ai/x in

  for i=0 to n-1 do
    increment h0 (divisors_up_to a.(i));
    increment h1 (divisors_up_to (a.(i)-1))
  done;

  (* think k >= 2 and solve it and then check k=0 or 1 later *)

  let answer = Hashtbl.fold (fun d0 count0 ac ->
    let count1 = try Hashtbl.find h1 (d0-k) with Not_found -> 0 in
    ac ++ ((long count0) ** (long count1))
  ) h0 0L in

  printf "%Ld\n" answer

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 read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)

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

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

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

  let divisors_up_to ai = ai/x in

  if k=0 then (
    let h0 = Hashtbl.create 10 in
    let h1 = Hashtbl.create 10 in

    for i=0 to n-1 do
      if a.(i) mod x <> 0 then (
	increment h0 (divisors_up_to a.(i));
	increment h1 a.(i);
      )
    done;

    let ordered = Hashtbl.fold (fun _ count0 ac ->
      ac ++ ((long count0) ** (long (count0 - 1))) // 2L
    ) h0 0L in

    let correction = sum 0 (n-1) (fun i ->
      if a.(i) mod x = 0 then 0L else
	let c2 = long (Hashtbl.find h1 a.(i)) in
	c2 ** c2 -- (c2 ** (c2 -- 1L))//2L
    ) in

    printf "%Ld\n" (ordered ++ correction)

  ) else (
    let h0 = Hashtbl.create 10 in
    let h1 = Hashtbl.create 10 in

  (* let d(a.(i)) be the number of numbers in 1, 2, ..., a.(i) divisible by x.
     This table stores key value pairs (k,v) where v = the number of a.(i) such
     that d.(a.(i)) = k.
  *)

    for i=0 to n-1 do
      increment h0 (divisors_up_to a.(i));
      increment h1 (divisors_up_to (a.(i)-1))
    done;

  (* think k >= 2 and solve it and then check k=0 or 1 later *)

    let answer = Hashtbl.fold (fun d0 count0 ac ->
      let count1 = try Hashtbl.find h1 (d0-k) with Not_found -> 0 in
      ac ++ ((long count0) ** (long count1))
    ) h0 0L in

    printf "%Ld\n" answer
  )


A team of furry rescue rangers was sitting idle in their hollow tree when suddenly they received a signal of distress. In a few moments they were ready, and the dirigible of the rescue chipmunks hit the road.We assume that the action takes place on a Cartesian plane. The headquarters of the rescuers is located at point (x1, y1), and the distress signal came from the point (x2, y2).Due to Gadget's engineering talent, the rescuers' dirigible can instantly change its current velocity and direction of movement at any moment and as many times as needed. The only limitation is: the speed of the aircraft relative to the air can not exceed  meters per second.Of course, Gadget is a true rescuer and wants to reach the destination as soon as possible. The matter is complicated by the fact that the wind is blowing in the air and it affects the movement of the dirigible. According to the weather forecast, the wind will be defined by the vector (vx, vy) for the nearest t seconds, and then will change to (wx, wy). These vectors give both the direction and velocity of the wind. Formally, if a dirigible is located at the point (x, y), while its own velocity relative to the air is equal to zero and the wind (ux, uy) is blowing, then after  seconds the new position of the dirigible will be .Gadget is busy piloting the aircraft, so she asked Chip to calculate how long will it take them to reach the destination if they fly optimally. He coped with the task easily, but Dale is convinced that Chip has given the random value, aiming only not to lose the face in front of Gadget. Dale has asked you to find the right answer.It is guaranteed that the speed of the wind at any moment of time is strictly less than the maximum possible speed of the airship relative to the air.

The first line of the input contains four integers x1, y1, x2, y2 (|x1|,  |y1|,  |x2|,  |y2| ≤ 10 000) — the coordinates of the rescuers' headquarters and the point, where signal of the distress came from, respectively.  The second line contains two integers  and t (0 < v, t ≤ 1000), which are denoting the maximum speed of the chipmunk dirigible relative to the air and the moment of time when the wind changes according to the weather forecast, respectively.  Next follow one per line two pairs of integer (vx, vy) and (wx, wy), describing the wind for the first t seconds and the wind that will blow at all the remaining time, respectively. It is guaranteed that  and .

Print a single real value — the minimum time the rescuers need to get to point (x2, y2). You answer will be considered correct if its absolute or relative error does not exceed 10 - 6.  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 .

(* 1st observation is that you're going to be flying in a constant
   direction for each part of the flight.  You can see this as
   follows.  If you're going to be flying for t units of time from
   point a to point b with the wind pushing you at velocity w, then we
   can split the components of the final displacement vector as
   follows.  We first fly for t units with the wind.  Then fly at your
   favorite velocity (no wind) for t units of time in some direction.
   Clearly in this case you'll want to fly in a constant direction to
   minimize your time.

   So one thing you need is to know how long it will take to get from
   point a to point b with wind vector w and your own maximum velocity
   v.  To do this involves computing the intersection point of a
   circle and a line.  I did this using binary search cause I didn't
   have the geometric primitives handy.

   Now we see if we can get there before the wind changes.  If
   possible we just do it.  Otherwise we do a ternary search over the
   angles of the first part of the flight that lasts time t.  We can
   compute its cost by flying t in that direction and then use the
   previous function to see how long it will take to get home from
   there.
*)
open Printf
open Scanf

let pi = 2.0 *. asin 1.0

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

let read2_float () = bscanf Scanning.stdib " %f %f " (fun x y -> (x,y))

let sq x = x *. x
let len2 (x,y) = (sq x) +. (sq y)
let len pt = sqrt (len2 pt)

let ( ++ ) (a,b) (c,d) = (a+.c, b+.d)
let ( -- ) (a,b) (c,d) = (a-.c, b-.d)
let ( ** ) c (x,y) = (c*.x, c*.y)

let () =
  let (x1,y1) = read2_float () in
  let (x2,y2) = read2_float () in
  let (v,t) = read2_float () in
  let (vx,vy) = read2_float () in
  let (wx,wy) = read2_float () in

  let time_to_reach v w g =
    (* assuming we're at the origin and have a max velocity v
       offset by velocity w how long does it take for us
       to get to point g ?  *)

    let toofar m =
      len2 (w -- (m ** g)) > sq v
    in

    let rec bsearch lo hi i =
      let m = (lo +. hi) /. 2.0 in
      if i=70 then m else
	if toofar m then bsearch lo m (i+1) else bsearch m hi (i+1)
    in

    let rec findhi hi = if toofar hi then hi else findhi (2.0 *. hi) in
    let s = bsearch 0.0 (findhi 1.0) 0 in
    let vel = len (s ** g) in
    (len g) /. vel
  in

  let answer =
    if (x1,y1) = (x2,y2) then 0.0 else
      let t0 = time_to_reach v (vx,vy) ((x2,y2) -- (x1,y1)) in
      if t0 <= t then t0 else (
	let (x1,y1) = (x1,y1) ++ (t ** (vx,vy)) in
	let angle i = (2.0 *. pi) *. ((float i) /. 10.0)in
	let angle_time alpha =
	  let p1 = (x1,y1) ++ ((t *. v) ** (cos alpha, sin alpha)) in
	  time_to_reach v (wx,wy) ((x2,y2)--p1)
	in
	let (_,i) = minf 0 9 (fun i -> (angle_time (angle i), i)) in
	let alpha_lo = angle (i-1) in
	let alpha_hi = angle (i+1) in

	let rec tsearch lo tlo hi thi i = if i=100 then (tlo +.thi) /. 2.0 else
	    let m1 = (2.0 *. lo +. hi) /. 3.0 in
	    let m2 = (lo +. 2.0 *. hi) /. 3.0 in
	    let tm1 = angle_time m1 in
	    let tm2 = angle_time m2 in
	    if tm1 < tm2
	    then tsearch lo tlo m2 tm2 (i+1)
	    else tsearch m1 tm1 hi thi (i+1)
	in
	t +. tsearch alpha_lo (angle_time alpha_lo) alpha_hi (angle_time alpha_hi) 0
      )
  in

  printf "%.8f\n" answer


Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties:  the upper half of matrix c (rows with numbers from 1 to x) exactly matches b;  the lower half of matrix c (rows with numbers from x + 1 to 2x) is symmetric to the upper one; the symmetry line is the line that separates two halves (the line that goes in the middle, between rows x and x + 1). Sereja has an n × m matrix a. He wants to find such matrix b, that it can be transformed into matrix a, if we'll perform on it several (possibly zero) mirrorings. What minimum number of rows can such matrix contain?

The first line contains two integers, n and m (1 ≤ n, m ≤ 100). Each of the next n lines contains m integers — the elements of matrix a. The i-th line contains integers ai1, ai2, ..., aim (0 ≤ aij ≤ 1) — the i-th row of the matrix a.

In the single line, print the answer to the problem — the minimum number of rows of matrix b.

NoteIn the first test sample the answer is a 2 × 3 matrix b:001110If we perform a mirroring operation with this matrix, we get the matrix a that is given in the input:001110110001

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

let is_mirror mat i j=
   if i mod 2=1 then false
   else
      begin
      let b=ref true in
      for k=1 to i/2 do
         for l=1 to j do
            b:= !b&&(mat.(k).(l)=mat.(i+1-k).(l))
         done
      done;
      !b
      end;;

let mat=Array.make_matrix (n+1) (m+1) 0;;

for i=1 to n do
   for j=1 to m do
      mat.(i).(j)<-Scanf.scanf " %d" (fun x->x)
   done
done;;

let sol=ref n;;

while is_mirror mat !sol m do
   sol:= !sol/2
done;;

print_int !sol;;


Recently, Pari and Arya did some research about NP-Hard problems and they found the minimum vertex cover problem very interesting.Suppose the graph G is given. Subset A of its vertices is called a vertex cover of this graph, if for each edge uv there is at least one endpoint of it in this set, i.e.  or  (or both).Pari and Arya have won a great undirected graph as an award in a team contest. Now they have to split it in two parts, but both of them want their parts of the graph to be a vertex cover.They have agreed to give you their graph and you need to find two disjoint subsets of its vertices A and B, such that both A and B are vertex cover or claim it's impossible. Each vertex should be given to no more than one of the friends (or you can even keep it for yourself).

The first line of the input contains two integers n and m (2 ≤ n ≤ 100 000, 1 ≤ m ≤ 100 000) — the number of vertices and the number of edges in the prize graph, respectively. Each of the next m lines contains a pair of integers ui and vi (1  ≤  ui,  vi  ≤  n), denoting an undirected edge between ui and vi. It's guaranteed the graph won't contain any self-loops or multiple edges.

If it's impossible to split the graph between Pari and Arya as they expect, print "-1" (without quotes). If there are two disjoint sets of vertices, such that both sets are vertex cover, print their descriptions. Each description must contain two lines. The first line contains a single integer k denoting the number of vertices in that vertex cover, and the second line contains k integers — the indices of vertices. Note that because of m ≥ 1, vertex cover cannot be empty.

NoteIn the first sample, you can give the vertex number 2 to Arya and vertices numbered 1 and 3 to Pari and keep vertex number 4 for yourself (or give it someone, if you wish).In the second sample, there is no way to satisfy both Pari and Arya.

exception GameOver

type owner = Nobody | Pari | Arya

let () =
  match read_line () |> Str.(split (regexp " ")) |> List.map int_of_string with
  | [n; m] -> (
    let adj = Array.make n [] in
    for i = 1 to m do
      match read_line () |> Str.(split (regexp " ")) |> List.map int_of_string with
      | [u; v] ->
         let u = u-1
         and v = v-1 in
         adj.(u) <- v :: adj.(u);
         adj.(v) <- u :: adj.(v)
      | _ -> assert false
    done;

    let own = Array.make n Nobody in
    let rec give who v =
      let other =
        match who with
        | Pari -> Arya
        | Arya -> Pari
        | Nobody -> assert false
      in
      if own.(v) == Nobody then (
        own.(v) <- who;
        List.iter (give other) adj.(v)
      )
      else if own.(v) == other then (
         raise GameOver
      )
    and print who =
      print_int (Array.fold_left (fun count x -> if x == who then count + 1 else count) 0 own);
      print_newline ();
      for i = 0 to n - 1 do
        if own.(i) == who then (
          print_int (i+1);
          print_char ' ';
        )
      done;
      print_newline ();
    in
    try
      for v = 0 to n - 1 do
        if own.(v) == Nobody then
          give Pari v;
      done;
      print Pari;
      print Arya
    with
      GameOver -> print_endline "-1"
  )
  | _ -> assert false

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_pair () = bscanf Scanning.stdib " %d %d " (fun x y -> (x,y))

let () =
  let (n,m) = read_pair () in

  let g = Array.make n [] in

  let add_edge u v =
    g.(u) <- v::g.(u);
    g.(v) <- u::g.(v)
  in

  for i=1 to m do
    let (u,v) = read_pair() in
    add_edge (u-1) (v-1)
  done;

  let color = Array.make n 0 in
  let bipartite = ref true in
  let visited = Array.make n false in

  let rec dfs u c =
    if visited.(u) then (
      if color.(u) <> c then bipartite := false
    ) else (
      visited.(u) <- true;
      color.(u) <- c;
      List.iter (fun v ->
	dfs v (1-c)
      ) g.(u)
    )
  in

  for u=0 to n-1 do
    if not visited.(u) then dfs u 0
  done;

  let color1 = sum 0 (n-1) (fun u -> color.(u)) in
  let color0 = n-color1 in

  if !bipartite then (

    printf "%d\n" color0;
    for i=0 to n-1 do
      if color.(i) = 0 then printf "%d " (i+1)
    done;
    print_newline();

    printf "%d\n" color1;
    for i=0 to n-1 do
      if color.(i) = 1 then printf "%d " (i+1)
    done;
    print_newline()
  ) else (
    printf "-1\n"
  )

exception GameOver

type owner = Nobody | Pari | Arya

let () =
  match read_line () |> Str.(split (regexp " ")) |> List.map int_of_string with
  | [n; m] -> (
    let adj = Array.make n [] in
    for i = 1 to m do
      match read_line () |> Str.(split (regexp " ")) |> List.map int_of_string with
      | [u; v] ->
         let u = u-1
         and v = v-1 in
         adj.(u) <- v :: adj.(u);
         adj.(v) <- u :: adj.(v)
      | _ -> assert false
    done;

    let own = Array.make n Nobody in
    let rec give who v =
      let other =
        match who with
        | Pari -> Arya
        | Arya -> Pari
        | Nobody -> assert false
      in
      if own.(v) == Nobody then (
        own.(v) <- who;
        List.iter (give other) adj.(v)
      )
      else if own.(v) == other then (
         raise GameOver
      )
    and print who =
      print_int (Array.fold_left (fun count x -> if x == who then count + 1 else count) 0 own);
      print_newline ();
      for i = 0 to n - 1 do
        if own.(i) == who then (
          print_int (i+1);
          print_char ' ';
        )
      done;
      print_newline ();
    in
    try
      give Pari 0;
      print Pari;
      print Arya
    with
    | GameOver -> print_endline "-1"
  )
  | _ -> assert false


There are n boys and m girls studying in the class. They should stand in a line so that boys and girls alternated there as much as possible. Let's assume that positions in the line are indexed from left to right by numbers from 1 to n + m. Then the number of integers i (1 ≤ i < n + m) such that positions with indexes i and i + 1 contain children of different genders (position i has a girl and position i + 1 has a boy or vice versa) must be as large as possible. Help the children and tell them how to form the line.

The single line of the input contains two integers n and m (1 ≤ n, m ≤ 100), separated by a space.

Print a line of n + m characters. Print on the i-th position of the line character "B", if the i-th position of your arrangement should have a boy and "G", if it should have a girl.  Of course, the number of characters "B" should equal n and the number of characters "G" should equal m. If there are multiple optimal solutions, print any of them.

NoteIn the first sample another possible answer is BGBGBG. In the second sample answer BBGBGB is also optimal.

(* it said I submitted this before, so I will change it *)

let chan = Scanf.Scanning.from_channel (open_in "input.txt")
let read_int () = Scanf.bscanf chan " %d " (fun x -> x)

let ochan = open_out "output.txt"
let print_string s = Printf.fprintf ochan "%s" s

let () =
  let n = read_int() in
  let m = read_int() in
  let (g1,g2) = if n>m then ("B","G") else ("G","B") in
  let (n,m) = (max n m, min n m) in
  let rec loop i j = if (i,j) = (0,0) then () else
    if i>j then (print_string g1; loop (i-1) j)
    else (print_string g2; loop i (j-1))
  in
    loop n m;
    print_string "\n"

let chan = Scanf.Scanning.from_channel (open_in "input.txt")
let read_int () = Scanf.bscanf chan " %d " (fun x -> x)

let print_stirng s = Printf.fprintf (open_out "output.txt") "%s\n" s

let () =
  let n = read_int() in
  let m = read_int() in
  let (g1,g2) = if n>m then ("B","G") else ("G","B") in
  let (n,m) = (max n m, min n m) in
  let rec loop i j = if (i,j) = (0,0) then () else
    if i>j then (print_string g1; loop (i-1) j)
    else (print_string g2; loop i (j-1))
  in
    loop n m;
    print_string "\n"


Sergey Semyonovich is a mayor of a county city N and he used to spend his days and nights in thoughts of further improvements of Nkers' lives. Unfortunately for him, anything and everything has been done already, and there are no more possible improvements he can think of during the day (he now prefers to sleep at night). However, his assistants have found a solution and they now draw an imaginary city on a paper sheet and suggest the mayor can propose its improvements.Right now he has a map of some imaginary city with $$$n$$$ subway stations. Some stations are directly connected with tunnels in such a way that the whole map is a tree (assistants were short on time and enthusiasm). It means that there exists exactly one simple path between each pair of station. We call a path simple if it uses each tunnel no more than once.One of Sergey Semyonovich's favorite quality objectives is the sum of all pairwise distances between every pair of stations. The distance between two stations is the minimum possible number of tunnels on a path between them.Sergey Semyonovich decided to add new tunnels to the subway map. In particular, he connected any two stations $$$u$$$ and $$$v$$$ that were not connected with a direct tunnel but share a common neighbor, i.e. there exists such a station $$$w$$$ that the original map has a tunnel between $$$u$$$ and $$$w$$$ and a tunnel between $$$w$$$ and $$$v$$$. You are given a task to compute the sum of pairwise distances between all pairs of stations in the new map.

The first line of the input contains a single integer $$$n$$$ ($$$2 \leq n \leq 200\,000$$$) — the number of subway stations in the imaginary city drawn by mayor's assistants. Each of the following $$$n - 1$$$ lines contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \leq u_i, v_i \leq n$$$, $$$u_i \ne v_i$$$), meaning the station with these indices are connected with a direct tunnel. It is guaranteed that these $$$n$$$ stations and $$$n - 1$$$ tunnels form a tree.

Print one integer that is equal to the sum of distances between all pairs of stations after Sergey Semyonovich draws new tunnels between all pairs of stations that share a common neighbor in the original map.

NoteIn the first sample, in the new map all pairs of stations share a direct connection, so the sum of distances is $$$6$$$.In the second sample, the new map has a direct tunnel between all pairs of stations except for the pair $$$(1, 4)$$$. For these two stations the distance is $$$2$$$.

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

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

let rec dfs g v p =
  let neighbors = List.filter (fun x -> x <> p) g.(v) in
  let dp = List.map (fun w -> dfs g w v) neighbors in
  let evens = List.fold_left (fun a (b,_,_,_) -> a ++ b) 0L dp in
  let odds = List.fold_left (fun a (_,b,_,_) -> a ++ b) 0L dp in
  let sz = evens ++ odds in
  let sd = sz ++ List.fold_left (fun a (_,_,b,_) -> a ++ b) 0L dp in
  let ans =  List.fold_left (fun x (e,o,s,a) -> x ++ a ++ (e++o++s)**(sz ++ 1L --e--o)) 0L dp in
  (* Printf.printf "v = %d\nEvens:%Ld Odds:%Ld Sd:%Ld Ans:%Ld\n" v (odds++1L) evens  sd ans; *)
  (odds ++ 1L, evens, sd, ans)

let () =
  let n = read_int () in
  let edges = Array.init (n-1)
      (fun _ -> let v = read_int () and w = read_int () in (v,w)) in
  let add_edge graph (v,w) = (graph.(v) <- w :: graph.(v);
                              graph.(w) <- v :: graph.(w);) in
  let graph = Array.make (n+1) [] in
  Array.iter (add_edge graph) edges;
  let (evens, odds, _, ans) = dfs graph 1 0 in
  let res = (ans ++ evens**odds) // 2L in
  Printf.printf "%Ld\n" res


Jamie is preparing a Codeforces round. He has got an idea for a problem, but does not know how to solve it. Help him write a solution to the following problem:Find k integers such that the sum of two to the power of each number equals to the number n and the largest integer in the answer is as small as possible. As there may be multiple answers, you are asked to output the lexicographically largest one. To be more clear, consider all integer sequence with length k (a1, a2, ..., ak) with . Give a value  to each sequence. Among all sequence(s) that have the minimum y value, output the one that is the lexicographically largest.For definitions of powers and lexicographical order see notes.

The first line consists of two integers n and k (1 ≤ n ≤ 1018, 1 ≤ k ≤ 105) — the required sum and the length of the sequence.

Output "No" (without quotes) in a single line if there does not exist such sequence. Otherwise, output "Yes" (without quotes) in the first line, and k numbers separated by space in the second line — the required sequence. It is guaranteed that the integers in the answer sequence fit the range [ - 1018, 1018].

NoteSample 1:23 + 23 + 22 + 21 + 20 = 8 + 8 + 4 + 2 + 1 = 23Answers like (3, 3, 2, 0, 1) or (0, 1, 2, 3, 3) are not lexicographically largest.Answers like (4, 1, 1, 1, 0) do not have the minimum y value.Sample 2:It can be shown there does not exist a sequence with length 2.Sample 3:Powers of 2:If x > 0, then 2x = 2·2·2·...·2 (x times).If x = 0, then 2x = 1.If x < 0, then .Lexicographical order:Given two different sequences of the same length, (a1, a2, ... , ak) and (b1, b2, ... , bk), the first one is smaller than the second one for the lexicographical order, if and only if ai < bi, for the first i where ai and bi differ.

open Printf
open Scanf

let ( land ) a b = Int64.logand a b
let ( lsr ) a b = Int64.shift_right_logical a b

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

let () =
  let n = read_long() in
  let k = read_int() in

  let rec make_list n c ac = if n=0L then ac else
      let ac = if n land 1L = 1L then ((1,c)::ac) else ac in
      make_list (n lsr 1) (c+1) ac
  in

  (* the list nl is (count, value) pairs, where count is the number of
     copies of the value.  Initially all counts are 1.  Values are
     always in strictly decreasing order *)

  let nl = make_list n 0 [] in
  let len = List.length nl in

  if k < len then printf "No\n" else (
    printf "Yes\n";

    let d = k - len in

    let compress nl =
      match nl with
	| [] -> failwith "can't happen"
	| [_] -> nl
	| (c1,v1)::((c2,v2)::tail) ->
	  if v1 = v2 then (c1+c2,v1)::tail else nl
    in

    let rec expand_smallest nl d =
      if d = 0 then nl else (
	let (c,v) = List.hd nl in
	if c <> 1 then failwith "c should be 1";
	expand_smallest ((1,v-1)::((1,v-1)::(List.tl nl))) (d-1)
      )
    in

    let rec pass nl d =
      if d=0 then nl else (
	let (c,v) = List.hd nl in
	if d >= c then (
	  let nl = (2*c, v-1)::(List.tl nl) in
	  let nl = compress nl in
	  let d = d-c in
	  pass nl d
	) else (
	(* now we grow the last one as much as possible *)
	  let nl = List.rev nl in
	  let nl = if List.length nl = 1 then (
	    (* special case for the list has one element *)
	    let (c,v) = List.hd nl in
	    (1,v)::[((c-1),v)]
	  ) else nl
	  in
	  List.rev (expand_smallest nl d)
	)
      )
    in

    let nl = pass nl d in
    List.iter (fun (c,v) ->
      for i=1 to c do printf "%d " v done
    ) nl;
    print_newline()
  )


According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time n snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top.Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower.  However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.Write a program that models the behavior of Ankh-Morpork residents.

The first line contains single integer n (1 ≤ n ≤ 100 000) — the total number of snacks. The second line contains n integers, the i-th of them equals the size of the snack which fell on the i-th day. Sizes are distinct integers from 1 to n.

Print n lines. On the i-th of them print the sizes of the snacks which the residents placed on the top of the Snacktower on the i-th day in the order they will do that. If no snack is placed on some day, leave the corresponding line empty.

NoteIn the example a snack of size 3 fell on the first day, and the residents immediately placed it. On the second day a snack of size 1 fell, and the residents weren't able to place it because they were missing the snack of size 2. On the third day a snack of size 2 fell, and the residents immediately placed it. Right after that they placed the snack of size 1 which had fallen before.

module IntSet = Set.Make(
                    struct
                      let compare = Pervasives.compare
                      type t = int
                  end) ;;

let n = Scanf.scanf "%d\n" (fun x -> x) ;;
let x = Array.init n (fun _ -> Scanf.scanf "%d%_c" (fun x -> x)) ;;

(* the smallest item on the tower *)
let smallest = ref (n + 1)
(* the rest of the items *)
and queue = ref IntSet.empty ;;

(* loop over items/days
 * if this is the next item in the tower, place it on
 * and place all additional items in the remaining queue
 * otherwise, insert this item into the remaining queue *)
for i = 0 to n - 1 do
  if x.(i) == !smallest - 1 then begin
      (* place this item on the tower *)
      print_int x.(i);
      (* update smallest *)
      smallest := x.(i);
      (* use up remaining *)
      while not (IntSet.is_empty !queue) && IntSet.max_elt !queue == !smallest - 1 do
        print_char ' ';
        let e = IntSet.max_elt !queue in
        print_int e;
        queue := IntSet.remove e !queue;
        smallest := e
      done
    end
  else queue := IntSet.add x.(i) !queue;

  print_newline ()
done ;;


You are given an array $$$a$$$ consisting of $$$n$$$ positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by $$$2$$$) or determine that there is no such subset.Both the given array and required subset may contain equal values.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$), number of test cases to solve. Descriptions of $$$t$$$ test cases follow. A description of each test case consists of two lines. The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 100$$$), length of array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 100$$$), elements of $$$a$$$. The given array $$$a$$$ can contain equal values (duplicates).

For each test case output $$$-1$$$ if there is no such subset of elements. Otherwise output positive integer $$$k$$$, number of elements in the required subset. Then output $$$k$$$ distinct integers ($$$1 \leq p_i \leq n$$$), indexes of the chosen elements. If there are multiple solutions output any of them.

NoteThere are three test cases in the example.In the first test case, you can choose the subset consisting of only the second element. Its sum is $$$4$$$ and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.

let scan_int () = Scanf.scanf " %d" (fun x -> x);;
let scan_int_array_of_size n = Array.init n (fun _ -> scan_int());;

let t = scan_int ();;
for x = 1 to t do
	let n = scan_int () in
	let tab = scan_int_array_of_size n in
	let p = ref (-1) and i1 = ref (-1) and i2 = ref (-1) in
	for i = 0 to n-1 do
		if tab.(i) mod 2 = 0 then p := i+1
		else if !i1 = -1 then i1 := i+1 else i2 := i+1
	done;
	if !p <> -1 then (print_int 1; print_newline (); print_int !p; print_newline ())
	else if !i2 <> -1 then (print_int 2; print_newline (); print_int !i1; print_string " "; print_int !i2; print_newline ())
	else (print_int (-1); print_newline ())
done;;


The name of one small but proud corporation consists of n lowercase English letters. The Corporation has decided to try rebranding — an active marketing strategy, that includes a set of measures to change either the brand (both for the company and the goods it produces) or its components: the name, the logo, the slogan. They decided to start with the name.For this purpose the corporation has consecutively hired m designers. Once a company hires the i-th designer, he immediately contributes to the creation of a new corporation name as follows: he takes the newest version of the name and replaces all the letters xi by yi, and all the letters yi by xi. This results in the new version. It is possible that some of these letters do no occur in the string. It may also happen that xi coincides with yi. The version of the name received after the work of the last designer becomes the new name of the corporation.Manager Arkady has recently got a job in this company, but is already soaked in the spirit of teamwork and is very worried about the success of the rebranding. Naturally, he can't wait to find out what is the new name the Corporation will receive.Satisfy Arkady's curiosity and tell him the final version of the name.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 200 000) — the length of the initial name and the number of designers hired, respectively. The second line consists of n lowercase English letters and represents the original name of the corporation. Next m lines contain the descriptions of the designers' actions: the i-th of them contains two space-separated lowercase English letters xi and yi.

11 6
abacabadaba
a b
b c
a d
e g
f a
b b

NoteIn the second sample the name of the corporation consecutively changes as follows:

open Printf
open Scanf

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

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

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

  let s = read_string () in
  let s = Array.init n (fun i -> l2n s.[i]) in

  let p = Array.init 26 (fun i -> i) in

  let swaps = Array.init m (fun _ ->
    let i = l2n (read_string()).[0] in
    let j = l2n (read_string()).[0] in
    (i,j)
  ) in

  for i=m-1 downto 0 do
    let (i,j) = swaps.(i) in
    let (a,b) = (p.(i), p.(j)) in
    p.(i) <- b;
    p.(j) <- a;
  done;

  for i=0 to n-1 do
    printf "%c" (n2l p.(s.(i)))
  done;
  print_newline()


In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum.For example, for n = 4 the sum is equal to  - 1 - 2 + 3 - 4 =  - 4, because 1, 2 and 4 are 20, 21 and 22 respectively.Calculate the answer for t values of n.

The first line of the input contains a single integer t (1 ≤ t ≤ 100) — the number of values of n to be processed. Each of next t lines contains a single integer n (1 ≤ n ≤ 109).

Print the requested sum for each of t integers n given in the input.

NoteThe answer for the first sample is explained in the statement.

open Big_int;;

let (</) x y = compare_big_int x y < 0;;
let (+/) = add_big_int;;
let (-/) = sub_big_int;;
let ( */ ) = mult_big_int;;
let ( // ) = div_big_int;;

let dwa = big_int_of_int 2;;
let jeden = unit_big_int;;
let zero = zero_big_int;;

let rec potegi a x n =
if n </ x then a
else potegi (a+/x) ((big_int_of_int 2)*/x) n;;

let wynik n = Printf.printf "%s\n" ( string_of_big_int ( n */ (n +/ jeden) //dwa -/
  dwa */(potegi zero jeden n) ) );;

let rec licz n a =
if n = 0 then a
else licz (n-1) ( wynik ( big_int_of_int ( read_int () ) ) );;

let funkcja x = licz x (Printf.printf "");;

let test x = licz 0 (Printf.printf " 5");;

funkcja ( read_int () );;

open Big_int

let (+|) = add_big_int
let (-|) = sub_big_int
let ( *| ) = mult_big_int
let (/|) = div_big_int
let bmod = mod_big_int
let (=|) = eq_big_int
let (/=|) a b = not (a =| b)
let (>|) = gt_big_int
let (<|) = lt_big_int
let (>=|) = ge_big_int
let (<=|) = le_big_int

let n0 = zero_big_int
let n1 = unit_big_int
let n2 = big_int_of_int 2

let _ =
  let sb = Scanf.Scanning.stdib in
  let t = Scanf.bscanf sb "%d " (fun s -> s) in
    for ca = 1 to t do
      let n = Scanf.bscanf sb "%d " (fun s -> s) in
      let p =
	let p = ref 0 in
	let n = ref n in
	  while !n > 1 do
	    incr p;
	    n := !n / 2;
	  done;
	  !p
      in
      let nn = big_int_of_int n in
      let res = nn *| (nn +| n1) /| n2 in
      let res = res -| power_int_positive_int 2 (p + 2) +| n2 in
	Printf.printf "%s\n" (string_of_big_int res)
    done

let rec potegi a x n =
if n < x then a
else potegi (a+x) (2*x) n;;

let wynik n = n*(n+1)/2 - (potegi 0 1 n);;
let rec licz n =
if n > 0 then licz (n-1)
else Printf.printf "\n";
Printf.printf "%d\n" ( Scanf.bscanf Scanf.Scanning.stdin "%d" wynik );;

let rec potegi a x n =
if n < x then a
else potegi (a+x) (2*x) n;;

let wynik n = n*(n+1)/2 - (potegi 0 1 n);;
let rec licz n =
if n = 0 then Printf.printf "\n"
else
Printf.printf "%d\n" ( Scanf.bscanf Scanf.Scanning.stdin "%d" wynik ); licz(n-1);;

let rec potegi a x n =
if n < x then a
else potegi (a+x) (2*x) n;;

let wynik n = Printf.printf "%d\n" ( n*(n+1)/2 - (potegi 0 1 n) );;

let rec licz n a =
if n = 1 then a
else licz (n-1) ( wynik ( read_int () ) );;

let funkcja x = licz x (Printf.printf "");;

let test x = licz 0 (Printf.printf " 5");;

 funkcja ( read_int () );;

let rec potegi a x n =
if n < x then a
else potegi (a+x) (2*x) n;;

let wynik n = n*(n+1)/2 - (potegi 0 1 n);;

Printf.printf "%d" ( Scanf.bscanf Scanf.Scanning.stdin "%d" wynik );;

let rec potegi a x n =
if n < x then a
else potegi (a+x) (2*x) n;;

let wynik n = Printf.printf "%d\n" ( n*(n+1)/2 - (potegi 0 1 n) );;

let rec licz n a =
if n = 0 then a
else licz (n-1)
(Scanf.bscanf Scanf.Scanning.stdin "%d\n" wynik );;

let funkcja x = licz x (Printf.printf "");;

let test x = licz 0 (Printf.printf " 5");;

 test ( read_int () );;

let rec potegi a x n =
if n < x then a
else potegi (a+x) (2*x) n;;

let wynik n = Printf.printf "%d\n" ( n*(n+1)/2 - (potegi 0 1 n) );;

let rec licz n a =
if n = 0 then a
else licz (n-1)
(Scanf.bscanf Scanf.Scanning.stdin "%d" wynik );;

let funkcja x = licz x (Printf.printf "");;

Scanf.bscanf Scanf.Scanning.stdin "%d" licz;;

let rec potegi a x n =
if n < x then a
else potegi (a+x) (2*x) n;;

let wynik n = Printf.printf "%d\n" ( n*(n+1)/2 - (potegi 0 1 n) );;

let rec licz n a =
if n <= 0 then a
else licz (n-1)
(Scanf.bscanf Scanf.Scanning.stdin "%d" wynik );;

let funkcja x = licz x (Printf.printf "5");;

let test x = licz 0 (Printf.printf " 5");;

Scanf.bscanf Scanf.Scanning.stdin "%d" test;;


The Little Elephant loves trees very much, he especially loves root trees.He's got a tree consisting of n nodes (the nodes are numbered from 1 to n), with root at node number 1. Each node of the tree contains some list of numbers which initially is empty. The Little Elephant wants to apply m operations. On the i-th operation (1 ≤ i ≤ m) he first adds number i to lists of all nodes of a subtree with the root in node number ai, and then he adds number i to lists of all nodes of the subtree with root in node bi.After applying all operations the Little Elephant wants to count for each node i number ci — the number of integers j (1 ≤ j ≤ n; j ≠ i), such that the lists of the i-th and the j-th nodes contain at least one common number.Help the Little Elephant, count numbers ci for him.

The first line contains two integers n and m (1 ≤ n, m ≤ 105) — the number of the tree nodes and the number of operations.  Each of the following n - 1 lines contains two space-separated integers, ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi), that mean that there is an edge between nodes number ui and vi.  Each of the following m lines contains two space-separated integers, ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi), that stand for the indexes of the nodes in the i-th operation. It is guaranteed that the given graph is an undirected tree.

In a single line print n space-separated integers — c1, c2, ..., cn.

(* this is customized splay tree code for storing a set of disjoint intervals *)

type tree = Empty
  | Node of tree * (int * int) * tree * (int * int)
(*          left       item      right  (total length * depth *)
type direction = Left | Right
type path = Item of tree * direction

let size tree = match tree with Empty -> 0 | Node(_, _, _, (size,_)) -> size
let depth tree = match tree with Empty -> 0 | Node(_, _, _, (_,depth)) -> depth

let getroot = function
  | Node(left, k, right, _) -> (left, k, right)
  | _ -> failwith "called getroot on Empty"

let newNode (l, (lo,hi), r) = Node(l, (lo,hi), r,
				   ((size l) + (size r) + (hi-lo+1),
				    1 + max (depth l) (depth r)))

let splay t p =
  (* The following splay function takes as input the currently splayed
     tree (so far) t, and a path list.  It takes two steps up, and calls
     itself recursively.  *)
  let rec rsplay = function
    | (t,[]) -> t
    | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::(Item(Node(_, cK, cR, _), Left)::tail)) ->
	rsplay (newNode(tL,tK,newNode(tR,bK,newNode(bR,cK,cR))), tail)

    | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::(Item(Node(cL, cK,_,_), Right)::tail)) ->
        rsplay (newNode(newNode(newNode(cL,cK,bL), bK, tL),tK,tR), tail)

    | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::tail) ->
	rsplay (newNode(tL,tK,newNode(tR,bK,bR)), tail)

    | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::tail) ->
	rsplay (newNode(newNode(bL,bK,tL),tK,tR), tail)

    | (_,_) -> failwith "Splay_failed (Should not happen)"
  in

  let rec build_path t path =
    match t with
      | Empty -> failwith "failed build_path"
      | Node(left, (lo,hi), right, _) ->
	  if p < lo && left<>Empty then build_path left (Item(t, Left)::path)
	  else if p > hi && right<>Empty then build_path right (Item(t, Right)::path)
	  else (t,path)
  in

    if t=Empty then Empty else
      rsplay (build_path t [])

let splaydeep t =
  let rec find_deepest = function
    | Node(Empty, (lo,_), Empty, _) -> lo
    | Node(left, _, right, _) ->
	find_deepest (if depth left >= depth right then left else right)
    | Empty -> failwith "find_deepest called with Empty"

  in
    if t=Empty then t else splay t (find_deepest t)

let split_l t l =
  (* split the list of segments in two.  Find the leftmost segment
     whose left endpoint is >= l.  That is the right part of my split. *)
  if t=Empty then (Empty,Empty) else
    let (left, (lo,hi), right) = getroot (splay t l) in
    let put_on_left =
      if lo <= l && l <= hi then lo < l
      else if l < lo then false else true
    in
      if put_on_left
      then (newNode(left, (lo,hi), Empty), right)
      else (left, newNode(Empty,(lo,hi),right))

let split_r t r =
  (* split the list of segments in two.  Find the rightmost segment
     whose right endpoint is <= r.  That is the left part of my split. *)
  if t=Empty then (Empty,Empty) else
    let (left, (lo,hi), right) = getroot (splay t r) in
    let put_on_left =
      if lo <= r && r <= hi then r = hi
      else if r < lo then false else true
    in
      if put_on_left
      then (newNode(left, (lo,hi), Empty), right)
      else (left, newNode(Empty,(lo,hi),right))

let insert t (l,r) =
  (* Insert a new interval that is either contained in,
     is disjoint from, or fully contains some other intervals *)
  if t=Empty then newNode (Empty,(l,r),Empty) else
    let t = splay t l in
    let (left, (lo,hi), right) = getroot t in
      if lo <= l && r <= hi then t else  (* new interval contained *)
	let (s1,s23) = split_l t l in
	let (s2,s3) = split_r s23 r in
	  newNode(s1,(l,r),s3)

(**************************************************************************)

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

let () =
  let n = read_int() in
  let m = read_int() in
  let edges = Array.make n [] in
  let () = for i=0 to n-2 do
    let (u,v) = read_pair() in
      edges.(u) <- v::edges.(u);
      edges.(v) <- u::edges.(v)
  done in
  let update = Array.make n [] in
  let () = for i=0 to m-1 do
    let (u,v) = read_pair() in
      update.(u) <- v::update.(u);
      update.(v) <- u::update.(v)
  done in

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

  let rec dfspre c u = if pre.(u) >= 0 then c else (
    pre.(u) <- c;
    List.fold_left dfspre (c+1) edges.(u)
  ) in

  let _ = dfspre 0 0 in

  let () = for i=0 to n-1 do
    edges.(i) <- List.filter (fun e -> pre.(e) > pre.(i)) edges.(i)
      (* Edge from parent to child increases pre.()
	 keep edges from parent to child *)
  done in

  let mpre = Array.make n (-1) in  (* max preorder number in the subtree rooted here *)

  let rec dfsmpre c u =
    let c = List.fold_left dfsmpre c edges.(u) in
      mpre.(u) <- max c pre.(u);
      mpre.(u)
  in

  let _ = dfsmpre 0 0 in

  let count = Array.make n 0 in  (* our answer *)

  let rec solve u t = (* u is a node, t is a tree of intervals inherited from the parent of u *)
    let nt = if update.(u) = [] then t else insert t (pre.(u), mpre.(u)) in
    let nt = List.fold_left (
      fun t v -> insert t (pre.(v), mpre.(v))
    ) nt update.(u)
    in

(*
    let rec logint i ac = if i=0 then ac else logint (i/2) (1::ac) in
    let nt = List.fold_left (fun t _ -> splaydeep t) nt (logint (List.length edges.(u)) []) in
*)

    let nt = List.fold_left (fun t _ -> splaydeep t) nt edges.(u) in
      List.iter (fun v -> solve v nt) edges.(u);
      count.(u) <- size nt;
  in

    solve 0 Empty;

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

(* this is customized splay tree code for storing a set of disjoint intervals *)

type tree = Empty
  | Node of tree * (int * int) * tree * (int * int)
(*          left       item      right  (total length * depth *)
type direction = Left | Right
type path = Item of tree * direction

let size tree = match tree with Empty -> 0 | Node(_, _, _, (size,_)) -> size
let depth tree = match tree with Empty -> 0 | Node(_, _, _, (_,depth)) -> depth

let getroot = function
  | Node(left, k, right, _) -> (left, k, right)
  | _ -> failwith "called getroot on Empty"

let newNode (l, (lo,hi), r) = Node(l, (lo,hi), r,
				   ((size l) + (size r) + (hi-lo+1),
				    1 + max (depth l) (depth r)))

let splay t p =
  (* The following splay function takes as input the currently splayed
     tree (so far) t, and a path list.  It takes two steps up, and calls
     itself recursively.  *)
  let rec rsplay = function
    | (t,[]) -> t
    | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::(Item(Node(_, cK, cR, _), Left)::tail)) ->
	rsplay (newNode(tL,tK,newNode(tR,bK,newNode(bR,cK,cR))), tail)

    | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::(Item(Node(cL, cK,_,_), Right)::tail)) ->
        rsplay (newNode(newNode(newNode(cL,cK,bL), bK, tL),tK,tR), tail)

    | (Node(tL,tK,tR,_), Item(Node(_, bK, bR,_), Left)::tail) ->
	rsplay (newNode(tL,tK,newNode(tR,bK,bR)), tail)

    | (Node(tL,tK,tR,_), Item(Node(bL, bK, _,_), Right)::tail) ->
	rsplay (newNode(newNode(bL,bK,tL),tK,tR), tail)

    | (_,_) -> failwith "Splay_failed (Should not happen)"
  in

  let rec build_path t path =
    match t with
      | Empty -> failwith "failed build_path"
      | Node(left, (lo,hi), right, _) ->
	  if p < lo && left<>Empty then build_path left (Item(t, Left)::path)
	  else if p > hi && right<>Empty then build_path right (Item(t, Right)::path)
	  else (t,path)
  in

    if t=Empty then Empty else
      rsplay (build_path t [])

let splaydeep t =
  let rec find_deepest = function
    | Node(Empty, (lo,_), Empty, _) -> lo
    | Node(left, _, right, _) ->
	find_deepest (if depth left >= depth right then left else right)
    | Empty -> failwith "find_deepest called with Empty"

  in
    if t=Empty then t else splay t (find_deepest t)

let split_l t l =
  (* split the list of segments in two.  Find the leftmost segment
     whose left endpoint is >= l.  That is the right part of my split. *)
  if t=Empty then (Empty,Empty) else
    let (left, (lo,hi), right) = getroot (splay t l) in
    let put_on_left =
      if lo <= l && l <= hi then lo < l
      else if l < lo then false else true
    in
      if put_on_left
      then (newNode(left, (lo,hi), Empty), right)
      else (left, newNode(Empty,(lo,hi),right))

let split_r t r =
  (* split the list of segments in two.  Find the rightmost segment
     whose right endpoint is <= r.  That is the left part of my split. *)
  if t=Empty then (Empty,Empty) else
    let (left, (lo,hi), right) = getroot (splay t r) in
    let put_on_left =
      if lo <= r && r <= hi then r = hi
      else if r < lo then false else true
    in
      if put_on_left
      then (newNode(left, (lo,hi), Empty), right)
      else (left, newNode(Empty,(lo,hi),right))

let insert t (l,r) =
  (* Insert a new interval that is either contained in,
     is disjoint from, or fully contains some other intervals *)
  if t=Empty then newNode (Empty,(l,r),Empty) else
    let t = splay t l in
    let (left, (lo,hi), right) = getroot t in
      if lo <= l && r <= hi then t else  (* new interval contained *)
	let (s1,s23) = split_l t l in
	let (s2,s3) = split_r s23 r in
	  newNode(s1,(l,r),s3)

(**************************************************************************)

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

let () =
  let n = read_int() in
  let m = read_int() in
  let edges = Array.make n [] in
  let () = for i=0 to n-2 do
    let (u,v) = read_pair() in
      edges.(u) <- v::edges.(u);
      edges.(v) <- u::edges.(v)
  done in
  let update = Array.make n [] in
  let () = for i=0 to m-1 do
    let (u,v) = read_pair() in
      update.(u) <- v::update.(u);
      update.(v) <- u::update.(v)
  done in

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

  let rec dfspre c u = if pre.(u) >= 0 then c else (
    pre.(u) <- c;
    List.fold_left dfspre (c+1) edges.(u)
  ) in

  let _ = dfspre 0 0 in

  let () = for i=0 to n-1 do
    edges.(i) <- List.filter (fun e -> pre.(e) > pre.(i)) edges.(i)
      (* Edge from parent to child increases pre.()
	 keep edges from parent to child *)
  done in

  let mpre = Array.make n (-1) in  (* max preorder number in the subtree rooted here *)

  let rec dfsmpre c u =
    let c = List.fold_left dfsmpre c edges.(u) in
      mpre.(u) <- max c pre.(u);
      mpre.(u)
  in

  let _ = dfsmpre 0 0 in

  let count = Array.make n 0 in  (* our answer *)

  let rec solve u t = (* u is a node, t is a tree of intervals inherited from the parent of u *)
    let nt = if update.(u) = [] then t else insert t (pre.(u), mpre.(u)) in
    let nt = List.fold_left (
      fun t v -> insert t (pre.(v), mpre.(v))
    ) nt update.(u)
    in

    let rec logint i ac = if i=0 then ac else logint (i/2) (1::ac) in
    let nt = List.fold_left (fun t _ -> splaydeep t) nt (logint (List.length edges.(u)) []) in

(*    let nt = List.fold_left (fun t _ -> splaydeep t) nt edges.(u) in *)
      List.iter (fun v -> solve v nt) edges.(u);
      count.(u) <- size nt;
  in

    solve 0 Empty;

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


Little X has met the following problem recently. Let's define f(x) as the sum of digits in decimal representation of number x (for example, f(1234) = 1 + 2 + 3 + 4). You are to calculate Of course Little X has solved this problem quickly, has locked it, and then has tried to hack others. He has seen the following C++ code:     ans = solve(l, r) % a;    if (ans <= 0)      ans += a; This code will fail only on the test with . You are given number a, help Little X to find a proper test for hack.

The first line contains a single integer a (1 ≤ a ≤ 1018).

Print two integers: l, r (1 ≤ l ≤ r < 10200) — the required test data. Leading zeros aren't allowed. It's guaranteed that the solution exists.

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

let rec dig n = if n>0L then (n %% 10L)::(dig (n//10L)) else []
(* produces a list of the digits of n, from lowest to highest *)
let f n = List.fold_left (++) 0L (dig n)

open Printf
open Scanf

let read_long () = bscanf Scanning.stdib " %Ld " (fun x -> x)

let solve m =

  let compute_sum n =
  (* compute the sum of the digits of all the numbers from 1 to n. *)
    let sumd d = d ** (d++1L) // 2L in
    let rec loop n ac digs =
      match digs with []-> ac
	| d::digs ->
	  let ac = (ac ++ m -- (f n)) %% m in
	  let ac = (((ac ** 2L) %% m) ** 5L) %% m in  (* multiply by 10 modulo m *)
	  let ac = (ac ++ n ** 45L ++ (d++1L) ** (f n) ++ (sumd d)) %% m in  (* n is not as big as m *)
	  loop ((10L ** n) ++ d) ac digs
    in
    if n=0L then 0L else loop 0L 0L (List.rev (dig n))
  in

  let dig_of_m = long (List.length (dig m)) in
  let delta = max (m // (dig_of_m ** 9L)) 1L in

  let rec find_hi cur v =
    let cur = cur++delta in
    let v' = compute_sum cur in
    if v' < v then cur else find_hi cur v'
  in

  let rec bsearch lo vlo hi vhi =
    (* compute_sum lo = vlo > compute_sum hi = vhi *)
    if lo ++ 1L = hi then hi else
      let mid = (lo ++ hi) // 2L in
      let vmid = compute_sum mid in
      if vmid > vlo then bsearch mid vmid hi vhi
      else if vmid < vlo then bsearch lo vlo mid vmid
      else failwith "binary search failed"
  in
  let hi = find_hi 1L 1L in
  let lo = hi -- delta in
  let st = bsearch lo (compute_sum lo) hi (compute_sum hi) in

  let rec find_match i sumi j sumj =
    if i >= j then find_match i sumi (j++1L) ((sumj ++ (f (j++1L))) %% m) (* neede for small values of m *)
    else if sumi = sumj then (i,j)
    else if sumi < sumj
    then find_match (i++1L) ((sumi ++ (f (i++1L))) %% m) j sumj
    else find_match i sumi (j++1L) ((sumj ++ (f (j++1L))) %% m)
  in

  find_match 0L 0L st (compute_sum st)

let () =
  let (i,j) = solve (read_long()) in
  printf "%Ld %Ld\n" (i++1L) j


You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the tableabcdedfghijk we obtain the table:acdefghjk A table is called good if its rows are ordered from top to bottom lexicographically, i.e. each row is lexicographically no larger than the following one. Determine the minimum number of operations of removing a column needed to make a given table good.

The first line contains two integers  — n and m (1 ≤ n, m ≤ 100). Next n lines contain m small English letters each — the characters of the table.

Print a single number — the minimum number of columns that you need to remove in order to make the table good.

NoteIn the first sample the table is already good.In the second sample you may remove the first and third column.In the third sample you have to remove all the columns (note that the table where all rows are empty is considered good by definition).Let strings s and t have equal length. Then, s is lexicographically larger than t if they are not equal and the character following the largest common prefix of s and t (the prefix may be empty) in s is alphabetically larger than the corresponding character of t.

let s = read_line ();;
let sx = List.map int_of_string (Str.split (Str.regexp " +") s);;
let n = List.hd sx;;
let m = List.hd (List.tl sx);;

let a = Array.make n "";;

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

let rec proc (e: bool array) = function
| j when j = m -> 0
| j ->
	let e' = Array.copy e in
	(*print_newline(Array.iter (fun x -> print_string (if x then "true  " else "false ")) e);*)
	let rec aux = function
	| i when i = n -> proc e' (j+1)
	| i ->
		if (e.(i) && a.(i).[j] < a.(i-1).[j]) then
			1 + proc e (j+1)
		else
			(e'.(i) <- e'.(i) && a.(i).[j] = a.(i-1).[j];
			aux (i+1)) in
	aux 1;;

print_newline (print_int (proc (Array.make n true) 0));;
(*print_newline (print_int (Array.fold_left (fun a x -> if x then 0 else 1) 0 e));;*)

exception Invalid_input

type status =
  | Stable
  | Safe

let (|>) x f = f x

let rec make_list = fun len f ->
  if len = 0 then
    []
  else
    f () :: make_list (len - 1) f

let rec prepend_list_to_list_of_list = fun li acc ->
  match li, acc with
  | h1 :: t1, h2 :: t2 -> (h1 :: h2) :: (prepend_list_to_list_of_list t1 t2)
  | _ -> acc

let string_to_list = fun s ->
  let len = String.length s in
  let rec do_string_to_list = fun s i ->
    if i < len then
      s.[i] :: do_string_to_list s (i + 1)
    else
      []
  in
  do_string_to_list s 0

let read_input = fun n m ->
  let rec do_read_input = fun i acc ->
    if i < n then
      let current_line =
        read_line ()
        |> string_to_list
      in
      prepend_list_to_list_of_list current_line acc
      |> do_read_input (i + 1)
    else
      acc
  in
  make_list m (fun () -> [])
  |> do_read_input 0

let process_one_column = fun status chars ->
  let rec need_to_remove = fun s_list c_list ->
    match s_list, c_list with
    | h1 :: (m1 :: t1 as p1), h2 :: (m2 :: t2 as p2) ->
      if h1 = Stable && h2 < m2 then
        true
      else
        need_to_remove p1 p2
    | _ ->
      false
  in
  if need_to_remove status chars then
    status, true
  else
    let rec get_new_status = fun s_list c_list ->
      match s_list, c_list with
      | h1 :: (m1 :: t1 as p1), h2 :: (m2 :: t2 as p2) ->
        let new_s =
          if h1 = Safe || m2 < h2 then
            Safe
          else
            Stable
        in
        new_s :: get_new_status p1 p2
      | hd :: [], _ ->
        [hd]
      | _ ->
        raise Invalid_input
    in
    (get_new_status status chars), false

let process_all_columns = fun n input ->
  let initial = make_list n (fun () -> Stable) in
  let rec do_process = fun status count input ->
    match input with
    | hd :: tl ->
      let new_status, removed = process_one_column status hd in
      let new_count = if removed then count + 1 else count in
      do_process new_status new_count tl
    | _ ->
      count
  in
  do_process initial 0 input

let () =
  let (n, m) =
    read_line ()
    |> Str.split (Str.regexp " +")
    |> List.map int_of_string
    |> fun li ->
        match li with
        | a :: [b] -> (a, b)
        | _ -> raise Invalid_input
  in
  let input = read_input n m in
  process_all_columns n input
  |> print_int
  |> print_newline

let s = read_line ();;
let sx = List.map int_of_string (Str.split (Str.regexp " +") s);;
let n = List.hd sx;;
let m = List.hd (List.tl sx);;

let a = Array.make n "";;

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

let rec proc (e: bool array) = function
| j when j = m -> 0
| j ->
	let e' = Array.copy e in

	let rec aux = function
	| i when i = n -> proc e' (j+1)
	| i ->
		if (e.(i) && a.(i).[j] < a.(i-1).[j]) then
			1 + proc e (j+1)
		else
			(e'.(i) <- a.(i).[j] = a.(i-1).[j];
			aux (i+1)) in
	aux 1;;

print_newline (print_int (proc (Array.make n true) 0));;
(*print_newline (print_int (Array.fold_left (fun a x -> if x then 0 else 1) 0 e));;*)

exception Invalid_input

type status =
  | Stable
  | Safe

let (|>) x f = f x

let rec make_list = fun len f ->
  if len = 0 then
    []
  else
    f () :: make_list (len - 1) f

let rec prepend_list_to_list_of_list = fun li acc ->
  match li, acc with
  | h1 :: t1, h2 :: t2 -> (h1 :: h2) :: (prepend_list_to_list_of_list t1 t2)
  | _ -> acc

let string_to_list = fun s ->
  let len = String.length s in
  let rec do_string_to_list = fun s i ->
    if i < len then
      s.[i] :: do_string_to_list s (i + 1)
    else
      []
  in
  do_string_to_list s 0

let read_input = fun n m ->
  let rec do_read_input = fun i acc ->
    if i < n then
      let current_line =
        read_line ()
        |> string_to_list
      in
      prepend_list_to_list_of_list current_line acc
      |> do_read_input (i + 1)
    else
      acc
  in
  make_list m (fun () -> [])
  |> do_read_input 0

let process_one_column = fun status chars ->
  let rec need_to_remove = fun s_list c_list ->
    match s_list, c_list with
    | h1 :: (m1 :: t1 as p1), h2 :: (m2 :: t2 as p2) ->
      if h1 = Stable && h2 < m2 then
        true
      else
        need_to_remove p1 p2
    | _ ->
      false
  in
  if need_to_remove status chars then
    status, true
  else
    let rec get_new_status = fun s_list c_list ->
      match s_list, c_list with
      | h1 :: (m1 :: t1 as p1), h2 :: (m2 :: t2 as p2) ->
        let new_s =
          if h1 = Safe || m2 < h2 then
            Safe
          else
            Stable
        in
        new_s :: get_new_status p1 p2
      | _ ->
        []
    in
    (get_new_status status chars), false

let process_all_columns = fun n input ->
  let initial = make_list n (fun () -> Stable) in
  let rec do_process = fun status count input ->
    match input with
    | hd :: tl ->
      let new_status, removed = process_one_column status hd in
      let new_count = if removed then count + 1 else count in
      do_process new_status new_count tl
    | _ ->
      count
  in
  do_process initial 0 input

let () =
  let (n, m) =
    read_line ()
    |> Str.split (Str.regexp " +")
    |> List.map int_of_string
    |> fun li ->
        match li with
        | a :: [b] -> (a, b)
        | _ -> raise Invalid_input
  in
  let input = read_input n m in
  process_all_columns n input
  |> print_int
  |> print_newline

exception Invalid_input

type status =
  | Stable
  | Safe

let (|>) x f = f x

let rec make_list = fun len f ->
  if len = 0 then
    []
  else
    f () :: make_list (len - 1) f

let rec prepend_list_to_list_of_list = fun li acc ->
  match li, acc with
  | h1 :: t1, h2 :: t2 -> (h1 :: h2) :: (prepend_list_to_list_of_list t1 t2)
  | _ -> acc

let string_to_list = fun s ->
  let len = String.length s in
  let rec do_string_to_list = fun s i ->
    if i < len then
      s.[i] :: do_string_to_list s (i + 1)
    else
      []
  in
  do_string_to_list s 0

let read_input = fun n m ->
  let rec do_read_input = fun i acc ->
    if i < n then
      let current_line =
        read_line ()
        |> string_to_list
      in
      prepend_list_to_list_of_list current_line acc
      |> do_read_input (i + 1)
    else
      acc
  in
  make_list m (fun () -> [])
  |> do_read_input 0

let process_one_column = fun status chars ->
  let rec need_to_remove = fun s_list c_list ->
    match s_list, c_list with
    | h1 :: (m1 :: t1 as p1), h2 :: (m2 :: t2 as p2) ->
      if h1 = Stable && h2 < m2 then
        true
      else
        need_to_remove p1 p2
    | _ ->
      false
  in
  if need_to_remove status chars then
    status, true
  else
    let rec get_new_status = fun s_list c_list ->
      match s_list, c_list with
      | h1 :: (m1 :: t1 as p1), h2 :: (m2 :: t2 as p2) ->
        let new_s =
          if h1 = Stable && m2 < h2 then
            Safe
          else
            Stable
        in
        new_s :: get_new_status p1 p2
      | _ ->
        []
    in
    (get_new_status status chars), false

let process_all_columns = fun n input ->
  let initial = make_list n (fun () -> Stable) in
  let rec do_process = fun status count input ->
    match input with
    | hd :: tl ->
      let new_status, removed = process_one_column status hd in
      let new_count = if removed then count + 1 else count in
      do_process new_status new_count tl
    | _ ->
      count
  in
  do_process initial 0 input

let () =
  let (n, m) =
    read_line ()
    |> Str.split (Str.regexp " +")
    |> List.map int_of_string
    |> fun li ->
        match li with
        | a :: [b] -> (a, b)
        | _ -> raise Invalid_input
  in
  let input = read_input n m in
  process_all_columns n input
  |> print_int
  |> print_newline


Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the distance of at most d from it, where d is some positive number, common for all lanterns. Vanya wonders: what is the minimum light radius d should the lanterns have to light the whole street?

The first line contains two integers n, l (1 ≤ n ≤ 1000, 1 ≤ l ≤ 109) — the number of lanterns and the length of the street respectively.  The next line contains n integers ai (0 ≤ ai ≤ l). Multiple lanterns can be located at the same point. The lanterns may be located at the ends of the street.

Print the minimum light radius d, needed to light the whole street. The answer will be considered correct if its absolute or relative error doesn't exceed 10 - 9.

NoteConsider the second sample. At d = 2 the first lantern will light the segment [0, 4] of the street, and the second lantern will light segment [3, 5]. Thus, the whole street will be lit.

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

let input () =
    let n = read () in
    let length = float (read ()) in
    let rec loop list i =
        if i < n
        then
            let var = float (read ()) in
            loop (var :: list) (i + 1)
        else
            (length, list)
    in loop [] 0

let get_max head prev max =
    if prev = float (-1)
    then
        Pervasives.max head max
    else
        Pervasives.max ((head -. prev) /. (float 2)) max

let solve (length, list) =
    let lampposts = List.sort (Pervasives.compare) list in
    let d_start = 0.0 -. List.hd lampposts in
    let d_end = length -. List.hd (List.rev lampposts) in
    let d_min = Pervasives.max d_start d_end in

    let rec loop rest prev max =
        match rest with
        | (head :: tail) -> loop tail head (get_max head prev max)
        | [] -> Pervasives.max d_min max
    in loop lampposts (float (-1)) (float 0)

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

(* Codeforces 349 A Cinema Line done *)

(* you can use either gr or rdln but not both *)
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 grc () = Scanf.scanf " %c" (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;;

let rec readlist n acc = match n with
	| 0 -> acc
	| _ -> readlist (n -1) (gr() :: acc);;
let printlisti li = List.iter (fun i -> (print_int i; print_string " ")) li;;

let rec minrad l d len = match l with
| [] -> d
| h :: [] -> max d (float_of_int (len - h))
| h :: t ->
	let dd = (float_of_int ((List.hd t) - h)) /. 2.0 in
	let dd = max dd d in
	minrad t dd len;;

let main() =
	let n = gr() in
	let len = gr() in
	let ll = readlist n [] in
	let li = List.rev ll in
	let sol = List.sort_uniq compare li in
	let dinit = float_of_int (List.hd sol) in
	let rad = minrad sol dinit len in
	begin
		Printf.printf "%.2f\n" rad
	end;;

main();;

(* Codeforces 492B VaniaFonari *)

open List;;
open String;;
open Array;;
open Int64;;

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 Pervasives.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 printarri64 ai = Array.iter (fun i -> (print_string (Int64.to_string i); print_string " ")) ai;;

let rec readlist n acc = match n with
	| 0 -> acc
	| _ -> readlist (n - 1) (gr() :: acc);;

let miscomp a b = a - b;;

let rec maxdif dif l = match l with
| a :: b :: tl ->
	let d = b - a in
	let dd = if d>dif then d else dif in
	maxdif dd (b :: tl)
| _ -> dif;;

let main () =
	let n = gr () in
	let l = gr () in
	let aal : int list = readlist n [] in
	let aso : int list = List.sort miscomp (l :: aal) in
	let d0 = maxdif 0 (0 :: aso) in
	let f0 = ((float_of_int d0) /. 2.0) in
	let d1 = float_of_int (List.nth aso 0) in
	let d2 = float_of_int (l - (List.nth aso (n-1))) in
	let d = max f0 (max d1 d2) in
	begin
	  print_float d
	end;;

main();;

open Str

let print_tuple = fun tuple ->
  let (x, y) = tuple in
  Printf.printf "%d %d\n" x y

let rec print_list = fun l ->
  match l with
  | hd :: tl ->
    print_int hd;
    print_char ' ';
    print_list tl;
  | _ -> ()

let rec find_max_gap = fun l cur_max ->
  match l with
  | hd :: mid :: tl ->
    let diff = mid - hd in
    if diff < cur_max then
      find_max_gap (mid :: tl) cur_max
    else
      find_max_gap (mid :: tl) diff
  | _ -> cur_max

let rec get_last = fun l ->
  match l with
  | [x] ->
    Some x
  | _ :: tl ->
    get_last tl
  | _ -> None

exception Invalid_input

let find_max_gap_including_head_and_tail = fun l e ->
  match get_last l with
  | Some last ->
    List.hd (List.fast_sort (fun i j ->
      if i < j then
        1
      else
        -1
    ) ([(float_of_int (List.hd l)); (float_of_int (e - last)); (float_of_int (find_max_gap l 0)) /. 2.0])
    )
  | None -> raise Invalid_input

let () =
  let (num_of_lanterns, len_of_street) = (fun line ->
    match line with
    | hd :: tl -> (int_of_string hd, int_of_string (List.hd tl))
    | _ -> raise Invalid_input
  ) (Str.split (Str.regexp " +") (read_line ()))
  in
  let lanterns = List.fast_sort (fun i j ->
    i - j
  ) (List.map int_of_string (Str.split (Str.regexp " +") (read_line ())))
  in
  print_float (find_max_gap_including_head_and_tail lanterns len_of_street);
  print_newline ()

(* Codeforces 492B VaniaFonari *)

open List;;
open String;;
open Array;;
open Int64;;

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 Pervasives.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 printarri64 ai = Array.iter (fun i -> (print_string (Int64.to_string i); print_string " ")) ai;;

let rec readlist n acc = match n with
	| 0 -> acc
	| _ -> readlist (n - 1) (gr() :: acc);;

let miscomp a b = a - b;;

let rec maxdif dif l = match l with
| a :: b :: tl ->
	let d = b - a in
	let dd = if d>dif then d else dif in
	maxdif dd (b :: tl)
| _ -> dif;;

let main () =
	let n = gr () in
	let l = gr () in
	let aal : int list = readlist n [] in
	let aso : int list = List.sort miscomp (l :: aal) in
	let df = maxdif 0 (0 :: aso) in
	begin
	  print_float ((float_of_int df) /. 2.0)
	end;;

main();;


You are given four integers $$$n$$$, $$$c_0$$$, $$$c_1$$$ and $$$h$$$ and a binary string $$$s$$$ of length $$$n$$$.A binary string is a string consisting of characters $$$0$$$ and $$$1$$$.You can change any character of the string $$$s$$$ (the string should be still binary after the change). You should pay $$$h$$$ coins for each change.After some changes (possibly zero) you want to buy the string. To buy the string you should buy all its characters. To buy the character $$$0$$$ you should pay $$$c_0$$$ coins, to buy the character $$$1$$$ you should pay $$$c_1$$$ coins.Find the minimum number of coins needed to buy the string.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10$$$) — the number of test cases. Next $$$2t$$$ lines contain descriptions of test cases. The first line of the description of each test case contains four integers $$$n$$$, $$$c_{0}$$$, $$$c_{1}$$$, $$$h$$$ ($$$1 \leq n, c_{0}, c_{1}, h \leq 1000$$$). The second line of the description of each test case contains the binary string $$$s$$$ of length $$$n$$$.

For each test case print a single integer — the minimum number of coins needed to buy the string.

NoteIn the first test case, you can buy all characters and pay $$$3$$$ coins, because both characters $$$0$$$ and $$$1$$$ costs $$$1$$$ coin.In the second test case, you can firstly change $$$2$$$-nd and $$$4$$$-th symbols of the string from $$$1$$$ to $$$0$$$ and pay $$$2$$$ coins for that. Your string will be $$$00000$$$. After that, you can buy the string and pay $$$5 \cdot 10 = 50$$$ coins for that. The total number of coins paid will be $$$2 + 50 = 52$$$.

let line_of_ints () =
  ()
  |> read_line
  |> Str.split (Str.regexp " ")
  |> List.map (fun s -> s |> String.trim |> int_of_string)

let () =
  let [t] = line_of_ints () in
  for _ = 1 to t do
    let [n; c0; c1; h] = line_of_ints () in
    let s = read_line () in
    let (s0, s1) =
      let s0 = ref 0 in
      let s1 = ref 0 in
      String.iter
        (function
         | '0' -> incr s0
         | '1' -> incr s1)
        s;
      (!s0, !s1)
    in
    let answer =
      let c = ref max_int in
      for a0 = 0 to s0 do
        for a1 = 0 to s1 do
          c := min !c ((s0 - a0 + a1) * c0 + (s1 - a1 + a0) * c1 + (a0 + a1) * h)
        done
      done;
      !c
    in
    answer
    |> string_of_int
    |> print_endline
  done


The Berland University is preparing to celebrate the 256-th anniversary of its founding! A specially appointed Vice Rector for the celebration prepares to decorate the campus. In the center of the campus n ice sculptures were erected. The sculptures are arranged in a circle at equal distances from each other, so they form a regular n-gon. They are numbered in clockwise order with numbers from 1 to n.The site of the University has already conducted a voting that estimated each sculpture's characteristic of ti — the degree of the sculpture's attractiveness. The values of ti can be positive, negative or zero.When the university rector came to evaluate the work, he said that this might be not the perfect arrangement. He suggested to melt some of the sculptures so that:   the remaining sculptures form a regular polygon (the number of vertices should be between 3 and n),  the sum of the ti values of the remaining sculptures is maximized. Help the Vice Rector to analyze the criticism — find the maximum value of ti sum which can be obtained in this way. It is allowed not to melt any sculptures at all. The sculptures can not be moved.

The first input line contains an integer n (3 ≤ n ≤ 20000) — the initial number of sculptures. The second line contains a sequence of integers t1, t2, ..., tn, ti — the degree of the i-th sculpture's attractiveness ( - 1000 ≤ ti ≤ 1000). The numbers on the line are separated by spaces.

Print the required maximum sum of the sculptures' attractiveness.

NoteIn the first sample it is best to leave every second sculpture, that is, leave sculptures with attractivenesses: 2, 4, 5 и 3.

open Scanf
open Printf
let (|>) x f = f x
let id = fun x  -> x
(* zd4 *)
let n = scanf "%d\n" (fun n -> n)

let arr = Array.make n 0

let () =
  for i=0 to n-1 do
    arr.(i) <- scanf "%d " (fun x -> x)
  done
let ans = ref min_int

let eval1 vn len =
  for i=0 to len-1 do
    let old,new_sum = ref i,ref 0 in
    for j=1 to vn do
      new_sum := !new_sum + arr.(!old);
      old := !old+len
    done;
    if !new_sum > !ans  then ans := !new_sum
  done

let iter =
  for vn = 3 to n do
    if n mod vn = 0 then
      eval1 vn (n/vn)
    else ()
  done

let () = printf "%d\n" !ans
(*
let () = Array.iter (print_int) arr
let () = print_newline ()
  *)