Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.

The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array.  The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.

Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).

let read format f = Scanf.bscanf Scanf.Scanning.stdib format f

let () =
  let n = read "%d\n" (fun x -> x) in
  let nowhere = -1 in
  let lefts = Array.make n nowhere in
  let rights = Array.make n nowhere in
  for i = 1 to n do
    let a = read "%d " (fun x -> x - 1) in
    if lefts.(a) = nowhere then lefts.(a) <- i;
    rights.(a) <- n - i + 1
  done;
  let left = ref (Int64.of_int 0) in
  let right = ref (Int64.of_int 0) in
  let m = read "%d\n" (fun x -> x) in
  for i = 1 to m do
    let q = read " %d" (fun x -> x - 1) in
    left := Int64.add !left (Int64.of_int lefts.(q));
    right := Int64.add !right (Int64.of_int rights.(q))
  done;
  Printf.printf "%Ld %Ld\n" !left !right

let get_tbl n =
  let tbl = Hashtbl.create 100000 in
  let rec loop count =
    if count > n then tbl
    else
      begin
	Hashtbl.add tbl (Scanf.scanf " %d" (fun x -> x)) (Int64.of_int(count));
	loop (count+1)
      end
  in
  loop 1

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

let solve tbl len queries =
  let accm_func ans q=
    let nth = Hashtbl.find tbl q in
    ((Int64.add (fst ans) nth),
      (Int64.sub (Int64.add (snd ans) (Int64.of_int(len+1))) nth))
  in
  List.fold_left accm_func (Int64.zero, Int64.zero) queries

let _ =
  let n = Scanf.scanf " %d" (fun x -> x) in
  let tbl = get_tbl n in
  let m = Scanf.scanf " %d" (fun x -> x) in
  let queries = get_int_list m in
  let ans = solve tbl n queries in
  Printf.printf "%Ld %Ld\n" (fst ans) (snd ans)

let read format f = Scanf.bscanf Scanf.Scanning.stdib format f

let () =
  let n = read "%d\n" (fun x -> x) in
  let nowhere = -1 in
  let lefts = Array.make n nowhere in
  let rights = Array.make n nowhere in
  for i = 1 to n do
    let a = read "%d " (fun x -> x - 1) in
    if lefts.(a) = nowhere then lefts.(a) <- i;
    rights.(a) <- n - i + 1
  done;
  let left = ref 0 in
  let right = ref 0 in
  let m = read "%d\n" (fun x -> x) in
  for i = 1 to m do
    let q = read " %d" (fun x -> x - 1) in
    left := !left + lefts.(q);
    right := !right + rights.(q)
  done;
  Printf.printf "%d %d\n" !left !right

let get_tbl n =
  let tbl = Hashtbl.create 100000 in
  let rec loop count =
    if count > n then tbl
    else
      begin
	Hashtbl.add tbl (Scanf.scanf " %d" (fun x -> x)) (Int32.of_int(count));
	loop (count+1)
      end
  in
  loop 1

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

let solve tbl len queries =
  let accm_func ans q=
    let nth = Hashtbl.find tbl q in
    ((Int32.add (fst ans) nth),
      (Int32.sub (Int32.add (snd ans) (Int32.of_int(len+1))) nth))
  in
  List.fold_left accm_func (Int32.zero, Int32.zero) queries

let _ =
  let n = Scanf.scanf " %d" (fun x -> x) in
  let tbl = get_tbl n in
  let m = Scanf.scanf " %d" (fun x -> x) in
  let queries = get_int_list m in
  let ans = solve tbl n queries in
  Printf.printf "%ld %ld\n" (fst ans) (snd ans)

let get_tbl n =
  let tbl = Hashtbl.create 100000 in
  let rec loop count =
    if count > n then tbl
    else
      begin
	Hashtbl.add tbl (Scanf.scanf " %d" (fun x -> x)) count;
	loop (count+1)
      end
  in
  loop 1

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

let solve tbl len queries =
  let accm_func ans q=
    let nth = Hashtbl.find tbl q in
    ((fst ans)+nth, (snd ans)+len-nth+1)
  in
  List.fold_left accm_func (0, 0) queries

let _ =
  let n = Scanf.scanf " %d" (fun x -> x) in
  let tbl = get_tbl n in
  let m = Scanf.scanf " %d" (fun x -> x) in
  let queries = get_int_list m in
  let ans = solve tbl n queries in
  Printf.printf "%d %d\n" (fst ans) (snd ans)


You are given a string s of length n, consisting of first k lowercase English letters.We define a c-repeat of some string q as a string, consisting of c copies of the string q. For example, string "acbacbacbacb" is a 4-repeat of the string "acb".Let's say that string a contains string b as a subsequence, if string b can be obtained from a by erasing some symbols.Let p be a string that represents some permutation of the first k lowercase English letters. We define function d(p) as the smallest integer such that a d(p)-repeat of the string p contains string s as a subsequence.There are m operations of one of two types that can be applied to string s:  Replace all characters at positions from li to ri by a character ci.  For the given p, that is a permutation of first k lowercase English letters, find the value of function d(p). All operations are performed sequentially, in the order they appear in the input. Your task is to determine the values of function d(p) for all operations of the second type.

The first line contains three positive integers n, m and k (1 ≤ n ≤ 200 000, 1 ≤ m ≤ 20000, 1 ≤ k ≤ 10) — the length of the string s, the number of operations and the size of the alphabet respectively. The second line contains the string s itself. Each of the following lines m contains a description of some operation:    Operation of the first type starts with 1 followed by a triple li, ri and ci, that denotes replacement of all characters at positions from li to ri by character ci (1 ≤ li ≤ ri ≤ n, ci is one of the first k lowercase English letters).  Operation of the second type starts with 2 followed by a permutation of the first k lowercase English letters.

For each query of the second type the value of function d(p).

7 4 3
abacaba
1 3 5 b
2 abc
1 4 4 c
2 cba

NoteAfter the first operation the string s will be abbbbba.In the second operation the answer is 6-repeat of abc: ABcaBcaBcaBcaBcAbc.After the third operation the string s will be abbcbba.In the fourth operation the answer is 5-repeat of cba: cbAcBacBaCBacBA.Uppercase letters means the occurrences of symbols from the string s.

(*    Added sentenials to the left and right end of the list.
      Their (l,r,c) would be (-1,0,0) on the left and
      (n,n+1,0) on the right.

      The histogram table keeps characters 0...k.  In other
      words an additional character 0 in order to simplify
      the cases in the code.
*)

module Pset = Set.Make (struct type t = int*int*int let compare = compare end)
(*                                    (l,r+1,character)                     *)

(* a string s is represented as a set of these triples.  For example if
   the string is "abbbbaacce" then it is:
                  0123456789
   (-1,0,k) (0,1,a) (1,5,b) (5,7,a) (7,9,c) (9,10,e) (10,11,k)

   The histogram is a (k+1) by (k+1) matrix of counts.  It's the
   number of times each such transition occurs in the string.
*)

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 l2n c = (int_of_char c) - (int_of_char 'a')

let split2 set e put_tie_left =
  let (a,x,b) = Pset.split e set in
  if not x then (a,b) else
    if put_tie_left then (Pset.add e a, b) else (a, Pset.add e b)

let pred set e =
  (* e is in the set.  Return it's predecessor.  It must be there *)
  let (l,_,_) = Pset.split e set in
  Pset.max_elt l

let succ set e =
  let (_,_,r) = Pset.split e set in
  Pset.min_elt r

let inc hist i j d =
  hist.(i).(j) <- hist.(i).(j) + d

let update str n l r c hist =
  (* Update the str (of length n) with a new block of chars c from l
     to r-1.  (Note this is different from the problem statement.)
     Return str, the updated version of the string.  the histogram is
     updated in place.  *)

  let first = (* the first one we're going to replace *)
    let (partl, _, _) = Pset.split (l,n+2,0) str in
    Pset.max_elt partl
  in

  let last =  (* the last one we're going to replace *)
    let (partl, _, _) = Pset.split (r,-2,0) str in
    Pset.max_elt partl
  in

  let (left_part,_,_) = Pset.split first str in
  let (_,_,right_part) = Pset.split last str in

  let list_of_range str a b =
    let (_,partr) = split2 str a false in
    let (partl,_) = split2 partr b true in
    List.rev (Pset.fold (fun e ac -> e::ac) partl [])
  in

  let before_first = pred str first in
  let after_last = succ str last in
  let rem_t = list_of_range str before_first after_last in

  let rec rem_scan (l0,r0,c0) li =
    match li with
      | [] -> failwith "scan called with empty list"
      | (l,r,c)::[] -> inc hist c0 c (-1)
      | (l,r,c)::tail ->
	inc hist c0 c (-1);
	inc hist c c (-(r-l-1));
	rem_scan (l,r,c) tail
  in

  rem_scan (List.hd rem_t) (List.tl rem_t);
  (* removes all the obsolete transitions *)

  let (l0,r0,c0) = first in
  let (l1,r1,c1) = last in

  let lphantom = if l0 < l then [(l0,l,c0)] else [] in
  let rphantom = if r1 > r then [(r,r1,c1)] else [] in
  let new_middle = lphantom @ [(l,r,c)] @ rphantom in

  let rec add_scan (l0,r0,c0) li =
    match li with
      | [] -> failwith "scan called with empty list"
      | (l,r,c)::[] -> inc hist c0 c 1
      | (l,r,c)::tail ->
	inc hist c0 c 1;
	inc hist c c (r-l-1);
	add_scan (l,r,c) tail
  in

  add_scan before_first (new_middle @ [after_last]);

  let newstr = Pset.union left_part right_part in
  List.fold_left (fun ac e -> Pset.add e ac) newstr new_middle

open Printf
open Scanf

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 k = read_int () in
  let s = read_string () in

  let rec find_changes s n i ac = if i=n then List.rev (n::ac) else
      if s.[i-1] <> s.[i] then find_changes s n (i+1) (i::ac)
      else find_changes s n (i+1) ac
  in

  let changes = Array.of_list (find_changes s n 1 []) in
(*
  printf "changes = ";
  for i=0 to -1+ Array.length changes do
    printf "%d " changes.(i)
  done;
  print_newline();
*)
  let str = fold 0 (-2 + Array.length changes) (
    fun i ac -> Pset.add (changes.(i), changes.(i+1), l2n s.[changes.(i)]) ac
  ) (Pset.singleton (0, changes.(0), l2n s.[0])) in

  let str = Pset.add (-1,0,k) str in
  let str = Pset.add (n,n+1,k) str in

  let hist = Array.make_matrix (k+1) (k+1) 0 in
  for i=0 to n-2 do
    inc hist (l2n s.[i]) (l2n s.[i+1]) 1
  done;
  inc hist k (l2n s.[0]) 1;
  inc hist (l2n s.[n-1]) k 1;

  let rec loop i str = if i=m then () else (
      match read_int() with
	| 1 ->
	  let l = -1 + read_int () in
	  let r = read_int () in
	  let c = l2n (read_string()).[0] in
	  let str = update str n l r c hist in
	  loop (i+1) str
	| 2 ->
	  let p = read_string() in
	  let p = Array.init k (fun i -> l2n p.[i]) in
	  let inv = Array.make k 0 in
	  for i=0 to k-1 do
	    inv.(p.(i)) <- i
	  done;
	  let cycles = sum 0 (k-1) (fun i -> sum 0 (k-1) (fun j ->
	      if inv.(i) < inv.(j) then 0 else hist.(i).(j)
	  )) in
	  printf "%d\n" (cycles+1);
	  loop (i+1) str
	| _ -> failwith "bad input"
  ) in

  loop 0 str

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

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

let split2 set e put_tie_left =
  let (a,x,b) = Pset.split e set in
  if not x then (a,b) else
    if put_tie_left then (Pset.add e a, b) else (a, Pset.add e b)

let pred set e =
  let (l,_,_) = Pset.split e set in
  Pset.max_elt l

let succ set e =
  let (_,_,r) = Pset.split e set in
  Pset.min_elt r

let inc h i j d =
    h.(i).(j) <- h.(i).(j) + d

let update str n l r c hist =
  let first = (* the first one we're going to replace *)
    let (partl, _, _) = Pset.split (l,n+2,0) str in
    Pset.max_elt partl
  in

  let last =  (* the last one we're going to replace *)
    let (partl, _, _) = Pset.split (r,-2,0) str in
    Pset.max_elt partl
  in

  let (left_part,_,_) = Pset.split first str in
  let (_,_,right_part) = Pset.split last str in

  let list_of_range str a b =
    let (_,partr) = split2 str a false in
    let (partl,_) = split2 partr b true in
    List.rev (Pset.fold (fun e ac -> e::ac) partl [])
  in

  let before_first = pred str first in
  let after_last = succ str last in
  let rem_t = list_of_range str before_first after_last in

  let rec rem_scan (l0,r0,c0) li =
    match li with
      | [] -> failwith "scan called with empty list"
      | (l,r,c)::[] -> inc hist c0 c (-1)
      | (l,r,c)::tail ->
	inc hist c0 c (-1);
	inc hist c c (-(r-l-1));
	rem_scan (l,r,c) tail
  in

  rem_scan (List.hd rem_t) (List.tl rem_t);

  let (l0,r0,c0) = first in
  let (l1,r1,c1) = last in

  let lphantom = if l0 < l then [(l0,l,c0)] else [] in
  let rphantom = if r1 > r then [(r,r1,c1)] else [] in
  let new_middle = lphantom @ [(l,r,c)] @ rphantom in

  let rec add_scan (l0,r0,c0) li =
    match li with
      | [] -> failwith "scan called with empty list"
      | (l,r,c)::[] -> inc hist c0 c 1
      | (l,r,c)::tail ->
	inc hist c0 c 1;
	inc hist c c (r-l-1);
	add_scan (l,r,c) tail
  in

  add_scan before_first (new_middle @ [after_last]);

  let newstr = Pset.union left_part right_part in
  List.fold_left (fun ac e -> Pset.add e ac) newstr new_middle

open Printf
open Scanf

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

let () =
  let n = read_int () in
  let m = read_int () in
  let k = read_int () in
  let s = read_conv_str () in

  let str = Pset.singleton (-1,0,k) in
  let str = Pset.add (n,n+1,k) str in

  let str = fold 0 (n-1) (
    fun i ac -> Pset.add (i, i+1, s.(i)) ac
  ) str in

  let hist = Array.make_matrix (k+1) (k+1) 0 in
  for i=0 to n-2 do
    inc hist s.(i) s.(i+1) 1
  done;

  ignore (fold 0 (m-1) (fun _ str ->
    match read_int() with
      | 1 ->
	let l = -1 + read_int () in
	let r = read_int () in
	let c = (read_conv_str()).(0) in
	update str n l r c hist
      | 2 ->
	let p = read_conv_str() in
	let cycles = sum 0 (k-1) (fun i -> sum 0 i (fun j -> hist.(p.(i)).(p.(j)))) in
	printf "%d\n" (cycles+1);
	str
      | _ -> failwith "bad input"
  ) str)


You have decided to watch the best moments of some movie. There are two buttons on your player:   Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie.  Skip exactly x minutes of the movie (x is some fixed positive integer). If the player is now at the t-th minute of the movie, then as a result of pressing this button, it proceeds to the minute (t + x). Initially the movie is turned on in the player on the first minute, and you want to watch exactly n best moments of the movie, the i-th best moment starts at the li-th minute and ends at the ri-th minute (more formally, the i-th best moment consists of minutes: li, li + 1, ..., ri). Determine, what is the minimum number of minutes of the movie you have to watch if you want to watch all the best moments?

The first line contains two space-separated integers n, x (1 ≤ n ≤ 50, 1 ≤ x ≤ 105) — the number of the best moments of the movie and the value of x for the second button. The following n lines contain the descriptions of the best moments of the movie, the i-th line of the description contains two integers separated by a space li, ri (1 ≤ li ≤ ri ≤ 105). It is guaranteed that for all integers i from 2 to n the following condition holds: ri - 1 < li.

Output a single number — the answer to the problem.

NoteIn the first sample, the player was initially standing on the first minute. As the minutes from the 1-st to the 4-th one don't contain interesting moments, we press the second button. Now we can not press the second button and skip 3 more minutes, because some of them contain interesting moments. Therefore, we watch the movie from the 4-th to the 6-th minute, after that the current time is 7. Similarly, we again skip 3 minutes and then watch from the 10-th to the 12-th minute of the movie. In total, we watch 6 minutes of the movie.In the second sample, the movie is very interesting, so you'll have to watch all 100000 minutes of the movie.

let () = Scanf.scanf "%d %d\n" (fun n x ->
  let rec aux a t i =
    if i = n then a
    else begin
      let l, r = Scanf.scanf "%d %d\n" (fun l r -> (l, r)) in
      let b = (l - t) mod x in
      let a = a + b + r - l + 1 in
      aux a (succ r) (succ i)
    end
  in
  Printf.printf "%d\n" (aux 0 1 0)
)

let rec watch curr skip watched lst =
  let is_skippable curr skip range =
    match (curr, skip, range) with
      c, s, [l; r;] when c + s <= l -> true
    | _ -> false
  in
  match lst with
    [] -> watched
  | _ ->
     let next = List.hd lst in
     let right = List.nth next 1
     in
     if is_skippable curr skip next then
           watch (curr + skip) skip watched lst
         else
           let minutes = right - curr + 1
           in
           watch (right + 1) skip (watched + minutes) (List.tl lst)
;;

let words s = Str.split (Str.regexp " ") s;;

let rec make_ranges lines =
  let rec inner lines rv =
    let range s = List.map int_of_string (words s) in
    match lines with
      [] -> rv
    | (l::ls) -> inner ls (List.append rv [range l])
  in
  inner lines []
;;

let rec read_lines n =
  let rec inner m rv =
    match m with
      0 -> rv
    | k -> inner (k - 1) (List.append rv [read_line ()])
  in
  inner n []
;;

let () =
  let nk_line = read_line () in
  let [nline; skip] = List.map int_of_string (words nk_line) in
  let scenes = make_ranges (read_lines nline)  in
  Printf.printf "%d\n" (watch 1 skip 0 scenes)
;;

module A = Array;;
module C = Char;;
module L = List;;
module S = String;;

let pf = Printf.printf;;
let sf = Scanf.scanf;;
let ssf = Scanf.sscanf;;

let (|>) x f = f x;;
let (@@) f x = f x;;
let id x = x;;
let id2 x y = (x, y);;
let id3 x y z = (x, y, z);;

exception Error of string

let inf = 1000000000;;
let eps = 1e-11;;

let _ =
  let (n, x) = sf "%d %d\n" id2 in
  let now = ref 0 in
  let res = ref 0 in
  for i = 1 to n do
    let (l, r) = sf "%d %d\n" id2 in
    res := !res + (r - !now) - (l - !now - 1) / x * x;
    now := r
  done;
  pf "%d\n" !res
;;


Shubham has an array $$$a$$$ of size $$$n$$$, and wants to select exactly $$$x$$$ elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct.Tell him whether he can do so.

The first line of the input contains a single integer $$$t$$$ $$$(1\le t \le 100)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ $$$(1 \le x \le n \le 1000)$$$ — the length of the array and the number of elements you need to choose. The next line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 1000)$$$ — elements of the array.

For each test case, print "Yes" or "No" depending on whether it is possible to choose $$$x$$$ elements such that their sum is odd. You may print every letter in any case you want.

NoteFor $$$1$$$st case: We must select element $$$999$$$, and the sum is odd.For $$$2$$$nd case: We must select element $$$1000$$$, so overall sum is not odd.For $$$3$$$rd case: We can select element $$$51$$$.For $$$4$$$th case: We must select both elements $$$50$$$ and $$$51$$$  — so overall sum is odd.For $$$5$$$th case: We must select all elements  — but overall sum is not odd.

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

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))
let () =
  let cases = read_int () in

  for case = 1 to cases do
    let (n,x) = read_pair() in
    let a = Array.init n read_int in
    let total = sum 0 (n-1) (fun i -> a.(i)) in

    let allodd = forall 0 (n-1) (fun i -> a.(i) mod 2 = 1) in
    let alleven = forall 0 (n-1) (fun i -> a.(i) mod 2 = 0) in

    let answer =
      if x = n then total mod 2 = 1
      else if allodd then x mod 2 = 1
      else if alleven then false
      else true
    in
    if answer then printf "Yes\n" else printf "No\n"
  done


Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.Petya has two strings a and b of the same length n. The strings consist only of lucky digits. Petya can perform operations of two types:   replace any one digit from string a by its opposite (i.e., replace 4 by 7 and 7 by 4);  swap any pair of digits in string a. Petya is interested in the minimum number of operations that are needed to make string a equal to string b. Help him with the task.

The first and the second line contains strings a and b, correspondingly. Strings a and b have equal lengths and contain only lucky digits. The strings are not empty, their length does not exceed 105.

Print on the single line the single number — the minimum number of operations needed to convert string a into string b.

NoteIn the first sample it is enough simply to swap the first and the second digit.In the second sample we should replace the second digit with its opposite.In the third number we should replace all three digits with their opposites.

(* codeforces 104.  Danny Sleator *)
let read_int () = Scanf.bscanf Scanf.Scanning.stdib " %d " (fun x -> x)
let read_string () = Scanf.bscanf Scanf.Scanning.stdib " %s " (fun x -> x)

let () =
  let a = read_string() in
  let b = read_string() in
  let n = String.length a in
  let rec count i a47 a74 = if i=n then (a47,a74) else
    match (a.[i],b.[i]) with
      | ('4','7') -> count (i+1) (a47+1) a74
      | ('7','4') -> count (i+1) a47 (a74+1)
      | _ -> count (i+1) a47 a74
  in
  let (c47,c74) = count 0 0 0 in
    Printf.printf "%d\n" (max c47 c74)


Peter got a new snow blower as a New Year present. Of course, Peter decided to try it immediately. After reading the instructions he realized that it does not work like regular snow blowing machines. In order to make it work, you need to tie it to some point that it does not cover, and then switch it on. As a result it will go along a circle around this point and will remove all the snow from its path.Formally, we assume that Peter's machine is a polygon on a plane. Then, after the machine is switched on, it will make a circle around the point to which Peter tied it (this point lies strictly outside the polygon). That is, each of the points lying within or on the border of the polygon will move along the circular trajectory, with the center of the circle at the point to which Peter tied his machine.Peter decided to tie his car to point P and now he is wondering what is the area of the region that will be cleared from snow. Help him.

The first line of the input contains three integers — the number of vertices of the polygon n (), and coordinates of point P. Each of the next n lines contains two integers — coordinates of the vertices of the polygon in the clockwise or counterclockwise order. It is guaranteed that no three consecutive vertices lie on a common straight line. All the numbers in the input are integers that do not exceed 1 000 000 in their absolute value.

Print a single real value number — the area of the region that will be cleared. Your 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 .

NoteIn the first sample snow will be removed from that area:

let read_int () = Scanf.scanf " %d" (fun x -> x)
let read_point () = Scanf.scanf " %d %d" (fun x y -> float x, float y)

let n = read_int ()
let p = read_point ()
let first = read_point ()
let prev = ref (0., 0.)
let () = prev := first
let minimum = ref infinity
let maximum = ref 0.
let pi = 3.14159265

let on_segment (x1, y1) (x, y) (x2, y2) =
  (x -. x1) *. (x -. x2) <= 0. &&  (y -. y1) *. (y -. y2) <= 0.

let min_and_max p1 p2 =
  let d (x, y) = sqrt ((fst p -. x)**2. +. (snd p -. y)**2.) in
  let rzut_p (x1, y1) (x2, y2) =
    let skal (x1, y1) (x2, y2) (x3, y3) =
      (x2 -. x1) *. (x3 -. x1) +. (y2 -. y1) *. (y3 -. y1)
    in
    let s = skal (x1, y1) p (x2, y2) /. skal (x1, y1) (x2, y2) (x2, y2) in
    ((x1 +. (x2 -. x1) *. s), (y1 +. (y2 -. y1) *. s))
  in
  let rzut = rzut_p p1 p2 in
  let min = if on_segment p1 rzut p2 then d rzut else min (d p1) (d p2) in
  (min, max (d p1) (d p2) )

let print_point (x, y) =
  print_float x;
  print_string " ";
  print_float y;
  print_newline()

let add cur =
  let mini, maxi = min_and_max !prev cur in
  (if mini < !minimum then minimum := mini else ());
  (if maxi > !maximum then maximum := maxi else ());
  prev := cur
;;

let () =
  for i = 1 to n - 1 do
    let cur = read_point () in
    add cur
  done;
  add first

let () =
  (pi *. !maximum ** 2. -. pi *. !minimum ** 2.) |> print_float;
  print_newline ()

open Printf
open Scanf

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

let long x = Int64.of_int x

let cross (x1,y1) (x2,y2) = (x1*.y2) -. (y1*.x2)
let ( -- ) (x1,y1) (x2,y2) = (x1-.x2, y1-.y2)
let len (x,y) = sqrt(x*.x +. y*.y)
let dot (x1,y1) (x2,y2) = x1*.x2 +. y1*.y2
let mul c (x,y) = (c*.x, c*.y)
let sq x = x *. x

let dist p q r = (* the distance from point r to the line from point p to point q *)
  let a = q -- p in
  let b = r -- p in
  let an = mul (1.0 /. (len a)) a in
  let v = mul (dot an b) an in
  if len v <= len a && (dot v a) >= 0.0 then len (b -- v) else 1e15

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

let pi = 2.0 *. asin 1.0

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

let () =
  let n = read_int () in
  let p = read_pair () in
  let poly = Array.init n (fun _ -> read_pair()) in

  let inner = minf 0 (n-1) (fun i->
    min (dist2 p poly.(i)) (sq (dist poly.(i) poly.((i+1) mod n) p))
  ) in
  let outer = maxf 0 (n-1) (fun i-> dist2 p poly.(i)) in

  printf "%.8f\n" (pi *. (outer -. inner))

open Printf
open Scanf

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

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

let pi = 2.0 *. asin 1.0

let dist (a,b) (c,d) =
  let x = float (a-c) in
  let y = float (b-d) in
  sqrt ((x*.x) +. (y*.y))

let () =
  let n = read_int () in
  let p = read_pair () in
  let poly = Array.init n (fun _ -> read_pair()) in

  let inner = minf 0 (n-1) (fun i-> dist p poly.(i)) in
  let outer = maxf 0 (n-1) (fun i-> dist p poly.(i)) in

  printf "%.8f\n" (pi *. (outer *. outer -. inner *. inner))

open Printf
open Scanf

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

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

let pi = 2.0 *. asin 1.0

let dist (a,b) (c,d) =
  let x = float (a-c) in
  let y = float (b-d) in
  sqrt ((x*.x) +. (y*.y))

let () =
  let n = read_int () in
  let p = read_pair () in
  let poly = Array.init n (fun _ -> read_pair()) in

  let inner = minf 0 (n-1) (fun i-> dist p poly.(i)) in
  let outer = maxf 0 (n-1) (fun i-> dist p poly.(i)) in

  printf "%.8f\n" (pi *. (outer -. inner) *. (outer +. inner))

open Printf
open Scanf

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

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

let pi = 2.0 *. asin 1.0

let dist2 (a,b) (c,d) =
  let x = long (a-c) in
  let y = long (b-d) in
  ((x**x) ++ (y**y))

let () =
  let n = read_int () in
  let p = read_pair () in
  let poly = Array.init n (fun _ -> read_pair()) in

  let inner = minf 0 (n-1) (fun i-> dist2 p poly.(i)) in
  let outer = maxf 0 (n-1) (fun i-> dist2 p poly.(i)) in

  printf "%.8f\n" (pi *. Int64.to_float (outer -- inner))


Sagheer is playing a game with his best friend Soliman. He brought a tree with n nodes numbered from 1 to n and rooted at node 1. The i-th node has ai apples. This tree has a special property: the lengths of all paths from the root to any leaf have the same parity (i.e. all paths have even length or all paths have odd length).Sagheer and Soliman will take turns to play. Soliman will make the first move. The player who can't make a move loses.In each move, the current player will pick a single node, take a non-empty subset of apples from it and do one of the following two things:  eat the apples, if the node is a leaf.  move the apples to one of the children, if the node is non-leaf. Before Soliman comes to start playing, Sagheer will make exactly one change to the tree. He will pick two different nodes u and v and swap the apples of u with the apples of v.Can you help Sagheer count the number of ways to make the swap (i.e. to choose u and v) after which he will win the game if both players play optimally? (u, v) and (v, u) are considered to be the same pair.

The first line will contain one integer n (2 ≤ n ≤ 105) — the number of nodes in the apple tree. The second line will contain n integers a1, a2, ..., an (1 ≤ ai ≤ 107) — the number of apples on each node of the tree. The third line will contain n - 1 integers p2, p3, ..., pn (1 ≤ pi ≤ n) — the parent of each node of the tree. Node i has parent pi (for 2 ≤ i ≤ n). Node 1 is the root of the tree. It is guaranteed that the input describes a valid tree, and the lengths of all paths from the root to any leaf will have the same parity.

On a single line, print the number of different pairs of nodes (u, v), u ≠ v such that if they start playing after swapping the apples of both nodes, Sagheer will win the game. (u, v) and (v, u) are considered to be the same pair.

NoteIn the first sample, Sagheer can only win if he swapped node 1 with node 3. In this case, both leaves will have 2 apples. If Soliman makes a move in a leaf node, Sagheer can make the same move in the other leaf. If Soliman moved some apples from a root to a leaf, Sagheer will eat those moved apples. Eventually, Soliman will not find a move.In the second sample, There is no swap that will make Sagheer win the game.Note that Sagheer must make the swap even if he can win with the initial tree.

(* keywords: impartial game, nimber

   Label each node as "in" or "out".  The leaves are "in".  in/out alternates
   as you go up the tree from the leaves.  This is consistent because of
   the "all leaf paths even or odd" property of the tree.

   The nimber is computed by xoring the "in" nodes, and ignoring the
   "out" ones.  This works because you can easily verify that if the
   nimber of the tree is 0 then any move makes it non-zero.  Also if
   the nimber of a tree is non-zero then just treat it like a game of
   nim among the "in" nodes and make a move that returns it to 0.

   If the nimber is 0, then Sagheer must make a swap that keeps it 0.
   If the nimber is non-zero then he must make a swap that makes it 0.

   In the first case any in-in swap and any out-out swap is counted.
   In the 2nd case none of these are counted.

   Let N be the nimber of the initial game.
   For swapping an in-node u and out-node v, it is allowed if
   a.(u) xor a.(v) = N.  These can be counted using hashing in O(n) time.
*)
(* started coding 6:10  done 6:46 *)

let ( ** ) a b = Int64.mul a b
let ( ++ ) a b = Int64.add a b
let ( -- ) a b = Int64.sub a b
let ( // ) a b = Int64.div a b
let ( %% ) a b = Int64.rem a b
let long x = Int64.of_int x
let short x = Int64.to_int x

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

let choose2 k =
  let k = long k in
  (k ** (k -- 1L)) // 2L

open Printf
open Scanf

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

let () =
  let n = read_int () in
  let a = Array.init n read_int in
  let isleaf = Array.make n true in
  let p = Array.init n (fun i ->
    if i=0 then 0 else
      let parent = -1 + read_int() in
      isleaf.(parent) <- false;
      parent
  ) in
  (* nodes are numbered 0, 1....n-1 with 0 the root. p.(i) is the parent of i *)

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

  let rec dfs i parity =
    if label.(i) < 0 then (
      label.(i) <- parity;
      dfs p.(i) (1-parity)
    )
  in

  for i=0 to n-1 do
    if isleaf.(i) then dfs i 0
  done;

  (* nodes with label.(i) = 0 are "in" the others are "out" *)

  let nimber = xorsum 0 (n-1) (fun i -> (1 - label.(i)) * a.(i)) in

  let n_in = sum 0 (n-1) (fun i -> if label.(i) = 0 then 1 else 0) in
  let n_out = n - n_in in

  let count1 = if nimber = 0 then (choose2 n_in) ++ (choose2 n_out) else 0L in

  let in_table = Hashtbl.create 10 in
  let get t = try Hashtbl.find in_table t with Not_found -> 0 in
  let increment t = Hashtbl.replace in_table t ((get t) + 1) in

  for i=0 to n-1 do
    if label.(i) = 0 then increment a.(i)
  done;

  let crossterm = sumlong 0 (n-1) (fun i ->
    long (if label.(i) = 0 then 0 else get (a.(i) lxor nimber))
  ) in

  printf "%Ld\n" (count1 ++ crossterm)

(* keywords: impartial game, nimber

   Label each node as "in" or "out".  The leaves are "in".  in/out alternates
   as you go up the tree from the leaves.  This is consistent because of
   the "all leaf paths even or odd" property of the tree.

   The nimber is computed by xoring the "in" nodes, and ignoring the
   "out" ones.  This works because you can easily verify that if the
   nimber of the tree is 0 then any move makes it non-zero.  Also if
   the nimber of a tree is non-zero then just treat it like a game of
   nim among the "in" nodes and make a move that returns it to 0.

   If the nimber is 0, then Sagheer must make a swap that keeps it 0.
   If the nimber is non-zero then he must make a swap that makes it 0.

   In the first case any in-in swap and any out-out swap is counted.
   In the 2nd case none of these are counted.

   Let N be the nimber of the initial game.
   For swapping an in-node u and out-node v, it is allowed if
   a.(u) xor a.(v) = N.  These can be counted using hashing in O(n) time.
*)
(* started coding 6:10  done 6:46 *)

let ( ** ) a b = Int64.mul a b
let ( ++ ) a b = Int64.add a b
let ( -- ) a b = Int64.sub a b
let ( // ) a b = Int64.div a b
let ( %% ) a b = Int64.rem a b
let long x = Int64.of_int x
let short x = Int64.to_int x

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

let choose2 k =
  let k = long k in
  (k ** (k ++ 1L)) // 2L

open Printf
open Scanf

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

let () =
  let n = read_int () in
  let a = Array.init n read_int in
  let isleaf = Array.make n true in
  let p = Array.init n (fun i ->
    if i=0 then 0 else
      let parent = -1 + read_int() in
      isleaf.(parent) <- false;
      parent
  ) in
  (* nodes are numbered 0, 1....n-1 with 0 the root. p.(i) is the parent of i *)

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

  let rec dfs i parity =
    if label.(i) < 0 then (
      label.(i) <- parity;
      dfs p.(i) (1-parity)
    )
  in

  for i=0 to n-1 do
    if isleaf.(i) then dfs i 0
  done;

  (* nodes with label.(i) = 0 are "in" the others are "out" *)

  let nimber = xorsum 0 (n-1) (fun i -> (1 - label.(i)) * a.(i)) in

  let n_in = sum 0 (n-1) (fun i -> if label.(i) = 0 then 1 else 0) in
  let n_out = n - n_in in

  let count1 = if nimber = 0 then (choose2 n_in) ++ (choose2 n_out) else 0L in

  let in_table = Hashtbl.create 10 in
  let get t = try Hashtbl.find in_table t with Not_found -> 0 in
  let increment t = Hashtbl.replace in_table t ((get t) + 1) in

  for i=0 to n-1 do
    if label.(i) = 0 then increment a.(i)
  done;

  let crossterm = sumlong 0 (n-1) (fun i ->
    long (if label.(i) = 0 then 0 else get (a.(i) lxor nimber))
  ) in

  printf "%Ld\n" (count1 ++ crossterm)


The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below.The playing field is a sequence of n non-negative integers ai numbered from 1 to n. The goal of the game is to make numbers a1, a2, ..., ak (i.e. some prefix of the sequence) equal to zero for some fixed k (k < n), and this should be done in the smallest possible number of moves.One move is choosing an integer i (1 ≤ i ≤ n) such that ai > 0 and an integer t (t ≥ 0) such that i + 2t ≤ n. After the values of i and t have been selected, the value of ai is decreased by 1, and the value of ai + 2t is increased by 1. For example, let n = 4 and a = (1, 0, 1, 2), then it is possible to make move i = 3, t = 0 and get a = (1, 0, 0, 3) or to make move i = 1, t = 1 and get a = (0, 0, 2, 2) (the only possible other move is i = 1, t = 0).You are given n and the initial sequence ai. The task is to calculate the minimum number of moves needed to make the first k elements of the original sequence equal to zero for each possible k (1 ≤ k < n).

The first input line contains a single integer n. The second line contains n integers ai (0 ≤ ai ≤ 104), separated by single spaces. The input limitations for getting 20 points are:    1 ≤ n ≤ 300  The input limitations for getting 50 points are:    1 ≤ n ≤ 2000  The input limitations for getting 100 points are:    1 ≤ n ≤ 105

Print exactly n - 1 lines: the k-th output line must contain the minimum number of moves needed to make the first k elements of the original sequence ai equal to zero. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams, or the %I64d specifier.

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0L in
  let () =
    for i = 0 to n - 1 do
      let k = Scanf.bscanf sb "%d " (fun s -> s) in
	a.(i) <- Int64.of_int k
    done
  in
  let res = ref 0L in
    for i = 0 to n - 2 do
      let p = ref 1 in
	while !p * 2 + i < n do
	  p := !p * 2;
	done;
	res := Int64.add !res a.(i);
	a.(i + !p) <- Int64.add a.(i + !p) a.(i);
	a.(i) <- 0L;
	Printf.printf "%Ld\n" !res;
    done


Vasya has recently got a job as a cashier at a local store. His day at work is $$$L$$$ minutes long. Vasya has already memorized $$$n$$$ regular customers, the $$$i$$$-th of which comes after $$$t_{i}$$$ minutes after the beginning of the day, and his service consumes $$$l_{i}$$$ minutes. It is guaranteed that no customer will arrive while Vasya is servicing another customer. Vasya is a bit lazy, so he likes taking smoke breaks for $$$a$$$ minutes each. Those breaks may go one after another, but Vasya must be present at work during all the time periods he must serve regular customers, otherwise one of them may alert his boss. What is the maximum number of breaks Vasya can take during the day?

Output one integer  — the maximum number of breaks.

NoteIn the first sample Vasya can take $$$3$$$ breaks starting after $$$2$$$, $$$5$$$ and $$$8$$$ minutes after the beginning of the day.In the second sample Vasya can take $$$2$$$ breaks starting after $$$0$$$ and $$$2$$$ minutes after the beginning of the day.In the third sample Vasya can't take any breaks.

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

let n,l,a = Scanf.sscanf (read_line ()) "%i %i %i" (fun n l a -> n,l,a) in
let num = ref 0 in
let time = ref 0 in
for i = 0 to n-1 do
  let ti, li = Scanf.sscanf (read_line()) "%i %i" (fun ti li -> ti,li) in
  num := !num + ((ti - !time)/a);
  time := ti + li;
done;
print_int (!num + ((l - !time)/a))

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

(* module Imos = struct
	let make n = Array.make (i32 n +$ 2) 0L
	let add_destructive_closed l r a =
		try
		a.(l+$1) <- a.(l+$1) + 1L;
		a.(r+$2) <- a.(r+$2) - 1L
		with Invalid_argument _ -> ()
	let add_destructive_1orig_closed l r a =
		a.(l) <- a.(l) + 1L;
		a.(r+$1) <- a.(r+$1) - 1L
	let cumulate_destructive a = for i=1 to Array.length a -$ 2 do
		a.(i) <- a.(i) + a.(i-$1)
	done
end *)

let () =
	let n,l,a = get_3_i64 9 in
	let b = Array.init (i32 n) (fun _ -> get_2_i64 0)
	in
	let p = ref 0L in
	let c = ref 0L in
	Array.iter (fun (t,l) ->
		(* printf "%Ld %Ld %Ld %Ld\n" !p t l !c; *)
		let d = t - !p in c += (d / a);
		p := t + l
	) b;
	printf "%Ld\n" (!c + (l- !p)/a)


Shohag has an integer sequence $$$a_1, a_2, \ldots, a_n$$$. He can perform the following operation any number of times (possibly, zero):  Select any positive integer $$$k$$$ (it can be different in different operations).  Choose any position in the sequence (possibly the beginning or end of the sequence, or in between any two elements) and insert $$$k$$$ into the sequence at this position.  This way, the sequence $$$a$$$ changes, and the next operation is performed on this changed sequence. For example, if $$$a=[3,3,4]$$$ and he selects $$$k = 2$$$, then after the operation he can obtain one of the sequences $$$[\underline{2},3,3,4]$$$, $$$[3,\underline{2},3,4]$$$, $$$[3,3,\underline{2},4]$$$, or $$$[3,3,4,\underline{2}]$$$.Shohag wants this sequence to satisfy the following condition: for each $$$1 \le i \le |a|$$$, $$$a_i \le i$$$. Here, $$$|a|$$$ denotes the size of $$$a$$$.Help him to find the minimum number of operations that he has to perform to achieve this goal. We can show that under the constraints of the problem it's always possible to achieve this goal in a finite number of operations.

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

For each test case, print a single integer  — the minimum number of operations needed to perform to achieve the goal mentioned in the statement.

NoteIn the first test case, we have to perform at least one operation, as $$$a_2=3>2$$$. We can perform the operation $$$[1, 3, 4] \rightarrow [1, \underline{2}, 3, 4]$$$ (the newly inserted element is underlined), now the condition is satisfied.In the second test case, Shohag can perform the following operations:$$$[1, 2, 5, 7, 4] \rightarrow [1, 2, \underline{3}, 5, 7, 4] \rightarrow [1, 2, 3, \underline{4}, 5, 7, 4] \rightarrow [1, 2, 3, 4, 5, \underline{3}, 7, 4]$$$.In the third test case, the sequence already satisfies the condition.

open Printf
open Scanf

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

let rec add_changes list idx acc =
  match list with
  |[] -> acc
  |h::t -> if h > idx then add_changes t (h+1) (acc + (h-idx)) else add_changes t (idx+1) (acc)

let () =
  let cases = read_int() in
  for cases = 1 to cases do
    let n = read_int() in
    let arr = Array.make n 0 in
    for n=0 to n-1 do
      let num = read_int() in
      Array.set arr n num
    done;
    let list = Array.to_list arr in
    printf ("%d\n") (add_changes list 1 0)
  done;

open Printf
open Scanf

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

let rec add_changes list idx acc =
  match list with
  |[] -> acc
  |h::t -> if acc + (h -1 -acc - idx ) < 0 then add_changes t (idx + 1) (acc) else add_changes t (idx + 1) (acc + (h -1 -acc - idx ))

let () =
  let cases = read_int() in
  for cases = 1 to cases do
    let n = read_int() in
    let arr = Array.make n 0 in
    for n=0 to n-1 do
      let num = read_int() in
      Array.set arr n num
    done;
    let list = Array.to_list arr in
    printf ("%d\n") (add_changes list 0 0)
  done;


During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants. Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula .After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.

The first line contains two integers n, k (1 ≤ n ≤ 2·105,  - 109 ≤ k ≤ 0). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 109) — ratings of the participants in the initial table.

Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.

NoteConsider the first test sample.  Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered. Thus, you should print 2, 3, 4.

let () =
  let (@@) f x = f x in
  let (%) f g x = f @@ g x in
  let (|>) x f = f x in
  let open List in
  let open Num in
  let split = Str.split @@ Str.regexp_string " " in
  read_line () |> split |> map int_of_string |> fun n_k ->
  let n = hd n_k and k = hd @@ tl n_k in
  read_line () |> split |> map int_of_string |> mapi (fun i a -> i + 1, a) |> fun ratings ->
  let rec loop rev_result acc i n = function
    | (_, ai) as r :: rs when acc -/ (Int ai) */ (Int n -/ Int i) */ (Int i -/ Int 1) </ Int k ->
      loop (r :: rev_result) acc i (n - 1) rs
    | (_, ai) :: rs -> loop rev_result (acc +/ (Int ai) */ (Int i -/ Int 1)) (i + 1) n rs
    | [] -> rev rev_result
  in
  loop [] (Int 0) 1 n ratings |> map (string_of_int % fst) |> iter print_endline

let () =
  let (@@) f x = f x in
  let (%) f g x = f @@ g x in
  let (|>) x f = f x in
  let open List in
  let open Num in
  let open Scanf in
  scanf "%d %d\n" @@ fun n k ->
  Array.init n (fun i -> scanf "%d " @@ fun a -> i + 1, a) |> Array.to_list |> fun ratings ->
  let rec loop rev_result acc i n = function
    | (_, ai) as r :: rs when acc -/ (Int ai) */ (Int n -/ Int i) */ (Int i -/ Int 1) </ Int k ->
      loop (r :: rev_result) acc i (n - 1) rs
    | (_, ai) :: rs -> loop rev_result (acc +/ (Int ai) */ (Int i -/ Int 1)) (i + 1) n rs
    | [] -> rev rev_result
  in
  loop [] (Int 0) 1 n ratings |> map (string_of_int % fst) |> iter print_endline

let () =
  let (@@) f x = f x in
  let (%) f g x = f @@ g x in
  let (|>) x f = f x in
  let (|*>) (a, b) f = f a b in
  let open List in
  let split = Str.split @@ Str.regexp_string " " in
  read_line () |> split |> map int_of_string |> fun n_k ->
  let n = hd n_k and k = hd @@ tl n_k in
  read_line () |> split |> map int_of_string |> mapi (fun i a -> i + 1, a) |> fun ratings ->
  let d ratings (i, ai) =
     (0, ratings) |*> fold_left (fun s (j, aj) -> s + if j < i then aj * (j - 1) - (n - i) * ai else 0)
  in
  let extract_next ratings =
    let rec loop rev_head = function
      | r :: rs when d ratings r < k -> (r, rev_append rev_head rs)
      | r :: rs -> loop (r :: rev_head) rs
      | [] -> raise Not_found
    in
    loop [] ratings
  in
  let rec loop rev_result rs =
    try let r, rs = extract_next rs in loop (r :: rev_result) rs
    with Not_found -> rev rev_result
  in
  loop [] ratings |> map (string_of_int % fst) |> iter print_endline

let () =
  let (@@) f x = f x in
  let (%) f g x = f @@ g x in
  let (|>) x f = f x in
  let (|*>) (a, b) f = f a b in
  let open List in
  let open Int64 in
  let split = Str.split @@ Str.regexp_string " " in
  read_line () |> split |> map int_of_string |> fun n_k ->
  let n = hd n_k and k = hd @@ tl n_k in
  read_line () |> split |> map int_of_string |> mapi (fun i a -> i + 1, a) |> fun ratings ->
  let d ratings (i, ai) =
     (0L, ratings) |*> fold_left (fun s (j, aj) ->
       add s @@
         if j < i then sub (mul (of_int aj) (sub (of_int j) 1L)) @@ mul (sub (of_int n) @@ of_int i) (of_int ai)
         else 0L)
  in
  let extract_next ratings =
    let rec loop rev_head = function
      | r :: rs when d ratings r < (of_int k) -> (r, rev_append rev_head rs)
      | r :: rs -> loop (r :: rev_head) rs
      | [] -> raise Not_found
    in
    loop [] ratings
  in
  let rec loop rev_result rs =
    try let r, rs = extract_next rs in loop (r :: rev_result) rs
    with Not_found -> rev rev_result
  in
  loop [] ratings |> map (string_of_int % fst) |> iter print_endline


Valera loves his garden, where n fruit trees grow.This year he will enjoy a great harvest! On the i-th tree bi fruit grow, they will ripen on a day number ai. Unfortunately, the fruit on the tree get withered, so they can only be collected on day ai and day ai + 1 (all fruits that are not collected in these two days, become unfit to eat).Valera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more than v fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well?

The first line contains two space-separated integers n and v (1 ≤ n, v ≤ 3000) — the number of fruit trees in the garden and the number of fruits that Valera can collect in a day.  Next n lines contain the description of trees in the garden. The i-th line contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ 3000) — the day the fruits ripen on the i-th tree and the number of fruits on the i-th tree.

Print a single integer — the maximum number of fruit that Valera can collect.

NoteIn the first sample, in order to obtain the optimal answer, you should act as follows.   On the first day collect 3 fruits from the 1-st tree.  On the second day collect 1 fruit from the 2-nd tree and 2 fruits from the 1-st tree.  On the third day collect the remaining fruits from the 2-nd tree.  In the second sample, you can only collect 60 fruits, the remaining fruit will simply wither.

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

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

let nn = 3001
let () =
  let n = read_int () in
  let v = read_int () in
  let fruit = Array.make (nn+1) 0 in
  for i=0 to n-1 do
    let a = read_int() in
    let b = read_int() in
    fruit.(a) <- fruit.(a) + b
  done;

  let ( ++ ) a b = Int64.add a b in

  let count = ref 0L in

  for t=1 to nn do
    let prev = fruit.(t-1) in
    let take_prev = min v prev in
    count := !count ++ (Int64.of_int take_prev);
    fruit.(t-1) <- fruit.(t-1) - take_prev;
    let v = v - take_prev in
    let current = fruit.(t) in
    let take_current = min v current in
    count := !count ++ (Int64.of_int take_current);
    fruit.(t) <- fruit.(t) - take_current;
  done;

  printf "%Ld\n" !count

let read_int()=Scanf.scanf "%d " (fun x->x);;
let n=read_int();;
let v=read_int();;
let tab=Array.make (n+1) 0;;
let vec=Array.make (n+1) 0;;
let mat=Array.make 3001 0;;
for i=1 to n do
   let x=read_int() and y=read_int() in (tab.(i)<-x;mat.(x)<-mat.(x)+y)
done;;
let r=ref 0;;
let nb=ref 0;;
for i=1 to 3000 do
   nb:= !nb+min (!r) v;
   let vv=v-min (!r) v in
   nb:= !nb+min vv mat.(i);
   r:= mat.(i)-min vv mat.(i)
done;;
print_int (!nb+min !r v);;


The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called "Testing Pants for Sadness".The test consists of n questions; the questions are to be answered strictly in the order in which they are given, from question 1 to question n. Question i contains ai answer variants, exactly one of them is correct. A click is regarded as selecting any answer in any question. The goal is to select the correct answer for each of the n questions. If Vaganych selects a wrong answer for some question, then all selected answers become unselected and the test starts from the very beginning, from question 1 again. But Vaganych remembers everything. The order of answers for each question and the order of questions remain unchanged, as well as the question and answers themselves.Vaganych is very smart and his memory is superb, yet he is unbelievably unlucky and knows nothing whatsoever about the test's theme. How many clicks will he have to perform in the worst case?

The first line contains a positive integer n (1 ≤ n ≤ 100). It is the number of questions in the test. The second line contains space-separated n positive integers ai (1 ≤ ai ≤ 109), the number of answer variants to question i.

Print a single number — the minimal number of clicks needed to pass the test it the worst-case scenario.  Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specificator.

NoteNote to the second sample. In the worst-case scenario you will need five clicks:   the first click selects the first variant to the first question, this answer turns out to be wrong.  the second click selects the second variant to the first question, it proves correct and we move on to the second question;  the third click selects the first variant to the second question, it is wrong and we go back to question 1;  the fourth click selects the second variant to the first question, it proves as correct as it was and we move on to the second question;  the fifth click selects the second variant to the second question, it proves correct, the test is finished.

(* Codeforces 103A - UnilShtan *)

open Filename;;

(* you can use either gr or rdln but not both *)
let use_input_txt = false;;
let fn = (Filename.dirname Filename.current_dir_name);;
let filename = Filename.concat "." "input.txt";;
let cin = if use_input_txt then Scanf.Scanning.open_in filename
	else Scanf.Scanning.stdin;;

let cout = open_out "output.txt";;
let gr () = Scanf.bscanf cin " %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 printlisti64 li = List.iter (fun i -> (print_string (Int64.to_string 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 -> List.rev acc
	| _ -> readlist (n -1) (gr() :: acc);;

let n = gr();;
let a = readlist n [];;

let rec count_shtan a k acc = match a with
	| [] -> acc
	| ai :: [] ->
		let acc1 = (Int64.add acc (Int64.mul (Int64.of_int ai) (Int64.of_int k))) in
		count_shtan [] (k+1) acc1
	| ai :: tl ->
		let acc1 = (Int64.add acc (Int64. mul (Int64.of_int (ai-1)) (Int64.of_int (k)))) in
		(
			(* print_string "acc1= ";                        *)
			(* print_string ((Int64.to_string acc1) ^ "\n"); *)
			count_shtan tl (k+1) acc1
			);;

let main() =
	begin
		let cnt = count_shtan a 1 Int64.zero in
		print_string ((Int64.to_string cnt) ^ "\n")
	end;;

main();;

(* Codeforces 103A - UnilShtan *)

open Filename;;

(* you can use either gr or rdln but not both *)
let use_input_txt = false;;
let fn = (Filename.dirname Filename.current_dir_name);;
let filename = Filename.concat "." "input.txt";;
let cin = if use_input_txt then Scanf.Scanning.open_in filename
	else Scanf.Scanning.stdin;;

let cout = open_out "output.txt";;
let gr () = Scanf.bscanf cin " %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 printlisti64 li = List.iter (fun i -> (print_string (Int64.to_string 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 n = gr();;
let a = readlist n [];;

let rec count_shtan a k acc = match a with
	| [] -> acc
	| ai :: [] ->
		let acc1 = (Int64.add acc (Int64. mul (Int64.of_int ai) (Int64.of_int k))) in
		count_shtan [] (k+1) acc1
	| ai :: tl ->
		let acc1 = (Int64.add acc (Int64. mul (Int64.of_int (ai-1)) (Int64.of_int (k)))) in
		count_shtan tl (k+1) acc1;;

let main() =
	begin
		let cnt = count_shtan a 1 Int64.zero in
		print_string ((Int64.to_string cnt) ^ "\n")
	end;;

main();;


$$$n$$$ students attended the first meeting of the Berland SU programming course ($$$n$$$ is even). All students will be divided into two groups. Each group will be attending exactly one lesson each week during one of the five working days (Monday, Tuesday, Wednesday, Thursday and Friday), and the days chosen for the groups must be different. Furthermore, both groups should contain the same number of students.Each student has filled a survey in which they told which days of the week are convenient for them to attend a lesson, and which are not. Your task is to determine if it is possible to choose two different week days to schedule the lessons for the group (the first group will attend the lesson on the first chosen day, the second group will attend the lesson on the second chosen day), and divide the students into two groups, so the groups have equal sizes, and for each student, the chosen lesson day for their group is convenient.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. Then the descriptions of $$$t$$$ testcases follow. The first line of each testcase contains one integer $$$n$$$ ($$$2 \le n \le 1\,000$$$) — the number of students. The $$$i$$$-th of the next $$$n$$$ lines contains $$$5$$$ integers, each of them is $$$0$$$ or $$$1$$$. If the $$$j$$$-th integer is $$$1$$$, then the $$$i$$$-th student can attend the lessons on the $$$j$$$-th day of the week. If the $$$j$$$-th integer is $$$0$$$, then the $$$i$$$-th student cannot attend the lessons on the $$$j$$$-th day of the week.  Additional constraints on the input: for each student, at least one of the days of the week is convenient, the total number of students over all testcases doesn't exceed $$$10^5$$$.

For each testcase print an answer. If it's possible to divide the students into two groups of equal sizes and choose different days for the groups so each student can attend the lesson in the chosen day of their group, print "YES" (without quotes). Otherwise, print "NO" (without quotes).

NoteIn the first testcase, there is a way to meet all the constraints. For example, the first group can consist of the first and the third students, they will attend the lessons on Thursday (the fourth day); the second group can consist of the second and the fourth students, and they will attend the lessons on Tuesday (the second day).In the second testcase, it is impossible to divide the students into groups so they attend the lessons on different days.


You are given a number $$$k$$$ and a string $$$s$$$ of length $$$n$$$, consisting of the characters '.' and '*'. You want to replace some of the '*' characters with 'x' characters so that the following conditions are met:   The first character '*' in the original string should be replaced with 'x';  The last character '*' in the original string should be replaced with 'x';  The distance between two neighboring replaced characters 'x' must not exceed $$$k$$$ (more formally, if you replaced characters at positions $$$i$$$ and $$$j$$$ ($$$i < j$$$) and at positions $$$[i+1, j-1]$$$ there is no "x" symbol, then $$$j-i$$$ must be no more than $$$k$$$). For example, if $$$n=7$$$, $$$s=$$$.**.*** and $$$k=3$$$, then the following strings will satisfy the conditions above:   .xx.*xx;  .x*.x*x;  .xx.xxx.  But, for example, the following strings will not meet the conditions:   .**.*xx (the first character '*' should be replaced with 'x');  .x*.xx* (the last character '*' should be replaced with 'x');  .x*.*xx (the distance between characters at positions $$$2$$$ and $$$6$$$ is greater than $$$k=3$$$). Given $$$n$$$, $$$k$$$, and $$$s$$$, find the minimum number of '*' characters that must be replaced with 'x' in order to meet the above conditions.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 500$$$). Then $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 50$$$). The second line of each test case contains a string $$$s$$$ of length $$$n$$$, consisting of the characters '.' and '*'. It is guaranteed that there is at least one '*' in the string $$$s$$$. It is guaranteed that the distance between any two neighboring '*' characters does not exceed $$$k$$$.

For each test case output the minimum number of '*' characters that must be replaced with 'x' characters in order to satisfy the conditions above.

(* https://codeforces.com/problemset/problem/1506/B *)

let trim str len =
    let rec seek i step =
        if str.[i] = '*'
        then i
        else seek (i+step) step in
    let first, last = (seek 0 1), (seek (len-1) ~-1) in
    if first = last
    then ""
    else String.sub str (first+1) (last-first-1)

let replace max_dist str len =
    let rec seek i step =
        if str.[i] = '*'
        then i
        else seek (i+step) step in
    let first, last = (seek 0 1), (seek (len-1) ~-1) in
    if first = last
    then 1
    else
        let sublen = last-first-1 in
        let sub = String.sub str (first+1) sublen in
        let rec helper start i last_seen count =
            if i = sublen
            then count
            else if i-start < max_dist
            then if sub.[i] = '*'
                then helper start (i+1) i count
                else helper start (i+1) last_seen count
            else if sub.[i] = '*'
                then helper i (i+1) i (count+1)
                else helper last_seen (i+1) last_seen (count+1) in
        2 + helper ~-1 0 ~-1 0

let solve_n n =
    let rec helper i =
        if i <> 0
        then (
            let [len; max_dist] =
                read_line ()
                |> Str.split (Str.regexp " ")
                |> List.map int_of_string in
            let str = read_line () in
            replace max_dist str len
            |> Printf.printf "%d\n";
            helper (i-1)
        ) in
    helper n

let () =
    let nb_cases = read_int () in
    solve_n nb_cases

(* https://codeforces.com/problemset/problem/1506/B *)

let trim str len =
    let rec seek i step =
        if str.[i] = '*'
        then i
        else seek (i+step) step in
    let first, last = (seek 0 1), (seek (len-1) ~-1) in
    if first = last
    then ""
    else String.sub str (first+1) (last-first-1)

let replace max_dist str len =
    let rec seek i step =
        if str.[i] = '*'
        then i
        else seek (i+step) step in
    let first, last = (seek 0 1), (seek (len-1) ~-1) in
    if first = last
    then 1
    else
        let sublen = last-first-1 in
        let sub = String.sub str (first+1) sublen in
        let rec helper start i last_seen count =
            if i = sublen
            then (if i-last_seen=max_dist then count+1 else count)
            else if i-start < max_dist
            then if sub.[i] = '*'
                then helper start (i+1) i count
                else helper start (i+1) last_seen count
            else if sub.[i] = '*'
                then helper i (i+1) i (count+1)
                else helper last_seen (i+1) last_seen (count+1) in
        2 + helper 0 0 ~-1 0

let solve_n n =
    let rec helper i =
        if i <> 0
        then (
            let [len; max_dist] =
                read_line ()
                |> Str.split (Str.regexp " ")
                |> List.map int_of_string in
            let str = read_line () in
            replace max_dist str len
            |> Printf.printf "%d\n";
            helper (i-1)
        ) in
    helper n

let () =
    let nb_cases = read_int () in
    solve_n nb_cases

(* https://codeforces.com/problemset/problem/1506/B *)

let trim str len =
    let rec seek i step =
        if str.[i] = '*'
        then i
        else seek (i+step) step in
    let first, last = (seek 0 1), (seek (len-1) ~-1) in
    if first = last
    then ""
    else String.sub str (first+1) (last-first-1)

let replace max_dist str len =
    let rec seek i step =
        if str.[i] = '*'
        then i
        else seek (i+step) step in
    let first, last = (seek 0 1), (seek (len-1) ~-1) in
    if first = last
    then 1
    else
        let sublen = last-first-1 in
        let sub = String.sub str (first+1) sublen in
        let rec helper start i last_seen count =
            if i = sublen
            then count
            else if i-start < max_dist
            then if sub.[i] = '*'
                then helper start (i+1) i count
                else helper start (i+1) last_seen count
            else if sub.[i] = '*'
                then helper i (i+1) i (count+1)
                else helper last_seen (i+1) last_seen (count+1) in
        2 + helper 0 0 0 0

let solve_n n =
    let rec helper i =
        if i <> 0
        then (
            let [len; max_dist] =
                read_line ()
                |> Str.split (Str.regexp " ")
                |> List.map int_of_string in
            let str = read_line () in
            replace max_dist str len
            |> Printf.printf "%d\n";
            helper (i-1)
        ) in
    helper n

let () =
    let nb_cases = read_int () in
    solve_n nb_cases

(* https://codeforces.com/contest/1506/problem/B *)

let replacement str max_distance =
    let len = String.length str in
    let rec seek_start i =
        if str.[i] = '*'
        then i
        else seek_start (i+1) in
    let rec seek_end i =
        if str.[i] = '*'
        then i
        else seek_end (i-1) in
    let first, last = (seek_start 0), (seek_end (len-1)) in
    if first = last
    then 1
    else 2 + (last-first-1) / max_distance

let solve_n n =
    let rec helper i =
        if i <> 0
        then (
            let [_; max_dist] =
                read_line ()
                |> Str.split (Str.regexp " ")
                |> List.map int_of_string in
            let str = read_line () in
            replacement str max_dist
            |> Printf.printf "%d\n";
            helper (i-1)
        ) in
    helper n

let () =
    let nb_cases = read_int () in
    solve_n nb_cases


By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated.In 2312 there was a startling discovery: a collider's activity is safe if and only if all numbers of activated colliders are pairwise relatively prime to each other (two numbers are relatively prime if their greatest common divisor equals 1)! If two colliders with relatively nonprime numbers are activated, it will cause a global collapse.Upon learning this, physicists rushed to turn the colliders on and off and carry out all sorts of experiments. To make sure than the scientists' quickness doesn't end with big trouble, the Large Hadron Colliders' Large Remote Control was created. You are commissioned to write the software for the remote (well, you do not expect anybody to operate it manually, do you?).Initially, all colliders are deactivated. Your program receives multiple requests of the form "activate/deactivate the i-th collider". The program should handle requests in the order of receiving them. The program should print the processed results in the format described below.To the request of "+ i" (that is, to activate the i-th collider), the program should print exactly one of the following responses:   "Success" if the activation was successful.  "Already on", if the i-th collider was already activated before the request.  "Conflict with j", if there is a conflict with the j-th collider (that is, the j-th collider is on, and numbers i and j are not relatively prime). In this case, the i-th collider shouldn't be activated. If a conflict occurs with several colliders simultaneously, you should print the number of any of them. The request of "- i" (that is, to deactivate the i-th collider), should receive one of the following responses from the program:   "Success", if the deactivation was successful.  "Already off", if the i-th collider was already deactivated before the request. You don't need to print quotes in the output of the responses to the requests.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the number of colliders and the number of requests, correspondingly. Next m lines contain numbers of requests, one per line, in the form of either "+ i" (without the quotes) — activate the i-th collider, or "- i" (without the quotes) — deactivate the i-th collider (1 ≤ i ≤ n).

Print m lines — the results of executing requests in the above given format. The requests should be processed in the order, in which they are given in the input. Don't forget that the responses to the requests should be printed without quotes.

Success
Conflict with 6
Success
Already off
Success
Success
Success
Success
Conflict with 10
Already on

NoteNote that in the sample the colliders don't turn on after the second and ninth requests. The ninth request could also receive response "Conflict with 3".

let main () =
    let n, m = Scanf.sscanf (read_line ()) "%d %d" (fun n m -> n, m) in
    let arr = Array.create (n + 1) [] in
    for i = 2 to n do
        if arr.(i) = [] then (
            let rec loop j =
                if j <= n then (
                    arr.(j) <- i :: arr.(j);
                    loop (j + i)
                )
            in
            loop i
        )
    done;

    let col  = Array.create (n + 1) false in
    let prim = Array.create (n + 1) 0 in

    let rec loop i =
        if i > 0 then (
            let (c, r) = Scanf.sscanf (read_line ()) "%c %d" (fun c r -> c, r) in
            if c = '+' then (
                if col.(r) then
                    print_endline "Already on"
                else
                    let k = List.fold_left (fun acc v -> if prim.(v) > 0 then prim.(v) else acc) 0 arr.(r) in
                    if k > 0 then Printf.printf "Conflict with %d\n" k else (
                        print_endline "Success";
                        col.(r) <- true;
                        List.iter (fun v -> prim.(v) <- r) arr.(r)
                    )
            ) else (
                if not col.(r) then print_endline "Already off" else
                let _ = print_endline "Success" in
                let _ = col.(r) <- false in
                List.iter (fun v -> prim.(v) <- 0) arr.(r)
            );
            loop (i - 1)
        )
    in
    loop m
;;
main()

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

exception Found of int

let _ =
  let n = 100000 in
  let prime = Array.make (n + 1) true in
  let d = Array.make (n + 1) 0 in
  let p = Array.make 10000 0 in
  let pk = ref 0 in
  let _ =
    for i = 2 to n do
      if prime.(i) then (
	p.(!pk) <- i;
	d.(i) <- !pk;
	incr pk;
	let j = ref (2 * i) in
          while !j <= n do
	    let jj = !j in
              prime.(jj) <- false;
	      d.(jj) <- !pk - 1;
              j := jj + i
          done
      )
    done;
  in
  let pk = !pk - 1 in
  let n = getnum () in
  let m = getnum () in
  let a = Array.make (n + 1) false in
  let h = Array.init 10000 (fun _ -> Hashtbl.create 1) in
    for i = 1 to m do
      let q = getnum () in
      let k = getnum () in
	match q with
	  | -5 -> (* + *)
	      if a.(k)
	      then Printf.printf "Already on\n"
	      else (
		try
		  (let r = ref k in
		     while !r > 1 do
		       let pn = d.(!r) in
		       let p = p.(pn) in
			 while !r mod p = 0 do
			   r := !r / p
			 done;
			 let ht = h.(pn) in
			   if Hashtbl.length ht <> 0 then (
			     Hashtbl.iter (fun c () -> raise (Found c)) ht
			   )
		     done);
		  a.(k) <- true;
		  (let r = ref k in
		     while !r > 1 do
		       let pn = d.(!r) in
		       let p = p.(pn) in
			 while !r mod p = 0 do
			   r := !r / p
			 done;
			 let ht = h.(pn) in
			   Hashtbl.replace ht k ()
		     done);
		    Printf.printf "Success\n"
		with
		  | Found c ->
		      Printf.printf "Conflict with %d\n" c
	      )
	  | 0 -> (* - *)
	      if not a.(k)
	      then Printf.printf "Already off\n"
	      else (
		a.(k) <- false;
		(let r = ref k in
		   while !r > 1 do
		     let pn = d.(!r) in
		     let p = p.(pn) in
		       while !r mod p = 0 do
			 r := !r / p
		       done;
		       let ht = h.(pn) in
			 Hashtbl.remove ht k
		   done);
		Printf.printf "Success\n"
	      )
	  | _ -> assert false
    done;

let rec gcd a b = if b = 0 then a else gcd b (a mod b)

let main () =
    let n, m = Scanf.sscanf (read_line ()) "%d %d" (fun n m -> n, m) in
    let col = Array.create (n + 1) false in
    let check col p =
        let rec loop i =
            if i * i > n then None else
            if col.(i) && gcd p i > 1 then Some i else loop (i + 1)
        in
        loop 2
    in
    for i = 1 to m do
        let (c, r) = Scanf.sscanf (read_line ()) "%c %d" (fun c r -> c, r) in
        if c = '+' then (
            if col.(r) then print_endline "Already on" else
            match check col r with
            | None -> print_endline "Success"; col.(r) <- true
            | Some k -> Printf.printf "Conflict with %d\n" k
        ) else
            if col.(r) = false then print_endline "Already off" else
            let _ = col.(r) <- false in
            print_endline "Success"
    done
;;
main()

let rec gcd a b = if b = 0 then a else gcd b (a mod b)

let main () =
    let n, m = Scanf.sscanf (read_line ()) "%d %d" (fun n m -> n, m) in
    let col = Array.create (n + 1) false in
    let check col p =
        let rec loop i =
            if i * i > n then None else
            if col.(i) && gcd p i > 1 then Some i else loop (i + 1)
        in
        loop 1
    in
    for i = 1 to m do
        let (c, r) = Scanf.sscanf (read_line ()) "%c %d" (fun c r -> c, r) in
        if c = '+' then (
            if col.(r) then print_endline "Already on" else
            match check col r with
            | None -> print_endline "Success"; col.(r) <- true
            | Some k -> Printf.printf "Conflict with %d\n" k
        ) else
            if col.(r) = false then print_endline "Already off" else
            let _ = col.(r) <- false in
            print_endline "Success"
    done
;;
main()


There are $$$n$$$ programmers that you want to split into several non-empty teams. The skill of the $$$i$$$-th programmer is $$$a_i$$$. You want to assemble the maximum number of teams from them. There is a restriction for each team: the number of programmers in the team multiplied by the minimum skill among all programmers in the team must be at least $$$x$$$.Each programmer should belong to at most one team. Some programmers may be left without a team.Calculate the maximum number of teams that you can assemble.

The first line contains the integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 10^5; 1 \le x \le 10^9$$$) — the number of programmers and the restriction of team skill respectively. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the skill of the $$$i$$$-th programmer. The sum of $$$n$$$ over all inputs does not exceed $$$10^5$$$.

For each test case print one integer — the maximum number of teams that you can assemble.

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 ( ** ) 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.stdin " %d " (fun x -> x)

let () =
  let cases = read_int() in
  for case = 1 to cases do
    let n = read_int() in
    let x = long(read_int()) in
    let a = Array.init n (fun i -> long(read_int())) in
    Array.sort compare a;
    let c = Array.make n 0 in  (* # teams we can make with ai...a(n-1) *)
    c.(n-1) <- if a.(n-1) >= x then 1 else 0;
    for j=n-2 downto 0 do
      let need = (x ++ a.(j) -- 1L) // a.(j) in
      let j' = (long j) ++ need in (* use j j+1... j'-1 *)
      c.(j) <-
	if j' > long n then 0
	else if j' = long n then 1
	else 1 + c.(short j');
    done;

    let answer = maxf 0 (n-1) (fun i -> c.(i)) in
    printf "%d\n" answer
  done


Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants.The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has $$$n$$$ hotels, where the $$$i$$$-th hotel is located in the city with coordinate $$$x_i$$$. Sonya is a smart girl, so she does not open two or more hotels in the same city.Sonya understands that her business needs to be expanded by opening new hotels, so she decides to build one more. She wants to make the minimum distance from this hotel to all others to be equal to $$$d$$$. The girl understands that there are many possible locations to construct such a hotel. Thus she wants to know the number of possible coordinates of the cities where she can build a new hotel. Because Sonya is lounging in a jacuzzi in one of her hotels, she is asking you to find the number of cities where she can build a new hotel so that the minimum distance from the original $$$n$$$ hotels to the new one is equal to $$$d$$$.

The first line contains two integers $$$n$$$ and $$$d$$$ ($$$1\leq n\leq 100$$$, $$$1\leq d\leq 10^9$$$) — the number of Sonya's hotels and the needed minimum distance from a new hotel to all others. The second line contains $$$n$$$ different integers in strictly increasing order $$$x_1, x_2, \ldots, x_n$$$ ($$$-10^9\leq x_i\leq 10^9$$$) — coordinates of Sonya's hotels.

Print the number of cities where Sonya can build a new hotel so that the minimum distance from this hotel to all others is equal to $$$d$$$.

NoteIn the first example, there are $$$6$$$ possible cities where Sonya can build a hotel. These cities have coordinates $$$-6$$$, $$$5$$$, $$$6$$$, $$$12$$$, $$$13$$$, and $$$19$$$.In the second example, there are $$$5$$$ possible cities where Sonya can build a hotel. These cities have coordinates $$$2$$$, $$$6$$$, $$$13$$$, $$$16$$$, and $$$21$$$.

open Printf open Scanf
module Int64 = struct
	include Int64
	(* int *)
	let (+$) = (+)
	let (-$) = (-)
	let (/$) = (/)
	let ( *$) = ( * )
	(* int64 *)
	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 labs p = if p < 0L then -1L*p else p
	(* let (~|) p = Int64.of_int p *)
	let (~|) p = Int64.to_int p

	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 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
end open Int64

let () =
  let n,d = get_2_i64 ()
  in let ar = input_i64_array n
  in
  let res = ref 0L
  in
  for i=0 to ~|n-$1 do
    let lef = ar.(i) - d in
      if (i>=1 && labs (lef - ar.(i-$1)) >= d) || i=0 then (
      (* printf "%Ld\n" lef; *)
      res+=1L;
    );
    let rig = ar.(i) + d in
      if i= ~|n-$1 ||
        (i<= ~|n-$2 && labs (rig - ar.(i+$1)) >= d && ar.(i+$1)-ar.(i)<>2L*d)
        then (
        (* printf "%Ld\n" rig; *)
        res+=1L
      );
  done;
  !res |> print_i64_endline

open Int64

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

let n,d = Scanf.sscanf (read_line ()) "%s %s" (fun n d -> of_string n,of_string d)  in
let hotel = read_line () |> split_on_char ' ' |> List.map of_string in
snd (List.fold_left (fun (old_x, tmp) x ->
    if sub x old_x > mul 2L d then (x, add tmp 2L)
    else if sub x old_x = mul 2L d then (x, add tmp 1L)
    else (x, tmp)) (List.hd hotel, 2L) (List.tl hotel))
|> to_string
|> print_endline

(* Codeforces 1004 A  Sonya and Hotels *)

(* 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 rdln() = input_line stdin;;
(* let spli s = Str.split (Str.regexp " ") s;; *)
		let printlisti li = List.iter (fun i -> (print_int i; print_string " ")) li;;
let printarri ai = Array.iter (fun i -> (print_int i; print_string " ")) ai;;
let debug = false;;

(* reading reversed list *)
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 printlists ls = List.iter (fun s -> (print_string s; print_string " ")) ls;;

let rec hotel_cnt d cnt l = match l with
	| [] -> cnt
	| h :: [] -> cnt+1
	| h :: nh :: tl ->
		let nl = nh :: tl in
		let mtwo = Int64.of_int 2 in
		let nhh = Int64.sub nh (Int64.mul mtwo d) in
		let icomp = Int64.compare h nhh in
		let ncnt =
			if icomp == 0 then cnt + 1
			else if icomp < 0 then cnt + 2
			else cnt in
		(* let _ = Printf.printf "h,nhh,cnt,ncnt= %Ld %Ld %d %d\n" h nhh cnt ncnt in *)
		hotel_cnt d ncnt nl;;

let rec to_i_64 l = match l with
| [] -> []
| h :: tl ->
	let ih = Int64.of_int h in
	ih :: to_i_64 tl;;

let main() =
	let n = gr () in
	let d = Int64.of_int (gr ()) in
	let a = readlist n [] in
	let ra = List.rev a in
	let iaa = to_i_64 ra in
	let cnt = hotel_cnt d 1 iaa in
	begin
		print_int cnt;
		print_string "\n"
	end;;

main();;

(* Codeforces 1004 A  Sonya and Hotels *)

(* 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 rdln() = input_line stdin;;
(* let spli s = Str.split (Str.regexp " ") s;; *)
		let printlisti li = List.iter (fun i -> (print_int i; print_string " ")) li;;
let printarri ai = Array.iter (fun i -> (print_int i; print_string " ")) ai;;
let debug = false;;

(* reading reversed list *)
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 printlists ls = List.iter (fun s -> (print_string s; print_string " ")) ls;;

let rec hotel_cnt d cnt l = match l with
	| [] -> cnt
	| h :: [] -> cnt+1
	| h :: nh :: tl ->
		let nl = nh :: tl in
		let mtwo = Int64.of_int 2 in
		let nhh = Int64.sub nh (Int64.mul mtwo d) in
		let icomp = Int64.compare h nhh in
		let ncnt =
			if icomp == 0 then cnt + 1
			else if icomp < 0 then cnt + 2
			else cnt in
		let _ = Printf.printf "h,nhh,cnt,ncnt= %Ld %Ld %d %d\n" h nhh cnt ncnt in
		hotel_cnt d ncnt nl;;

let rec to_i_64 l = match l with
| [] -> []
| h :: tl ->
	let ih = Int64.of_int h in
	ih :: to_i_64 tl;;

let main() =
	let n = gr () in
	let d = Int64.of_int (gr ()) in
	let a = readlist n [] in
	let ra = List.rev a in
	let iaa = to_i_64 ra in
	let cnt = hotel_cnt d 1 iaa in
	begin
		print_int cnt;
		print_string "\n"
	end;;

main();;

(* Codeforces 1004 A  Sonya and Hotels *)

(* 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 rdln() = input_line stdin;;
(* let spli s = Str.split (Str.regexp " ") s;; *)
		let printlisti li = List.iter (fun i -> (print_int i; print_string " ")) li;;
let printarri ai = Array.iter (fun i -> (print_int i; print_string " ")) ai;;
let debug = false;;

(* reading reversed list *)
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 printlists ls = List.iter (fun s -> (print_string s; print_string " ")) ls;;

let rec hotel_cnt d cnt l = match l with
	| [] -> cnt
	| h :: [] -> cnt+1
	| h :: nh :: tl ->
		let nl = nh :: tl in
		let ncnt =
			if h == nh - 2 * d then cnt + 1
			else if h < nh - 2 * d then cnt + 2
			else cnt in
		(*let _ = Printf.printf "h,n,cnt,ncnt= %d %d %d %d\n" h nh cnt ncnt in*)
		hotel_cnt d ncnt nl;;

let main() =
	let n = gr () in
	let d = gr () in
	let a = readlist n [] in
	let ra = List.rev a in
	let cnt = hotel_cnt d 1 ra in
	begin
		print_int cnt;
		print_string "\n"
	end;;

main();;

open Printf open Scanf
module Int64 = struct
	include Int64
	(* int *)
	let (+$) = (+)
	let (-$) = (-)
	let (/$) = (/)
	let ( *$) = ( * )
	(* int64 *)
	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 labs p = if p < 0L then -1L*p else p
	(* let (~|) p = Int64.of_int p *)
	let (~|) p = Int64.to_int p

	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 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
end open Int64

let () =
  let n,d = get_2_i64 ()
  in let ar = input_i64_array n
  in
  let res = ref 0L
  in
  for i=0 to ~|n-$1 do
    let lef = ar.(i) - d in if i>=1 && lef>ar.(i-$1) then res+=1L;
    let rig = ar.(i) + d in if i<= ~|n-$2 && rig<ar.(i+$1) && ar.(i+$1)-ar.(i)<>2L*d then res+=1L;
  done;
  !res |> print_i64_endline

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

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

let n,d = Scanf.sscanf (read_line ()) "%i %i" (fun n d -> n,d)  in
let hotel = read_line () |> split_on_char ' ' |> List.map int_of_string in
print_int @@ snd (List.fold_left (fun (old_x, tmp) x ->
    if x - old_x > 2 * d then (x,tmp + 2)
    else if x - old_x = 2 * d then (x, tmp+1)
    else (x, tmp)) (List.hd hotel, 2) (List.tl hotel));
print_newline ();