Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One can use the i-th train route to go from capital of the country to city si (and vise versa), the length of this route is yi.Jzzhu doesn't want to waste the money of the country, so he is going to close some of the train routes. Please tell Jzzhu the maximum number of the train routes which can be closed under the following condition: the length of the shortest path from every city to the capital mustn't change.

The first line contains three integers n, m, k (2 ≤ n ≤ 105; 1 ≤ m ≤ 3·105; 1 ≤ k ≤ 105). Each of the next m lines contains three integers ui, vi, xi (1 ≤ ui, vi ≤ n; ui ≠ vi; 1 ≤ xi ≤ 109). Each of the next k lines contains two integers si and yi (2 ≤ si ≤ n; 1 ≤ yi ≤ 109). It is guaranteed that there is at least one way from every city to the capital. Note, that there can be multiple roads between two cities. Also, there can be multiple routes going to the same city from the capital.

Output a single integer representing the maximum number of the train routes which can be closed.

let scan_int () = Scanf.scanf " %d" (fun x -> x);;
let scan_string () = Scanf.scanf " %s" (fun x -> x);;
let psp () = print_string " ";; let pnl () = print_newline ();;
let b2i x = if x == true then 1 else 0;;
let dbg x = print_int(x); pnl();;

module PSet = struct
  type 'k set =
    | Empty
    | Node of 'k set * 'k * 'k set * int

  type 'k t =
    {
      cmp : 'k -> 'k -> int;
      set : 'k set;
    }

  let height = function
    | Node (_, _, _, h) -> h
    | Empty -> 0

  let make l k r = Node (l, k, r, max (height l) (height r) + 1)

  let bal l k r =
    let hl = height l in
    let hr = height r in
    if hl > hr + 2 then
      match l with
      | Node (ll, lk, lr, _) ->
          if height ll >= height lr then make ll lk (make lr k r)
          else
            (match lr with
            | Node (lrl, lrk, lrr, _) ->
                make (make ll lk lrl) lrk (make lrr k r)
            | Empty -> assert false)
      | Empty -> assert false
    else if hr > hl + 2 then
      match r with
      | Node (rl, rk, rr, _) ->
          if height rr >= height rl then make (make l k rl) rk rr
          else
            (match rl with
            | Node (rll, rlk, rlr, _) ->
                make (make l k rll) rlk (make rlr rk rr)
            | Empty -> assert false)
      | Empty -> assert false
    else Node (l, k, r, max hl hr + 1)

  let rec min_elt = function
    | Node (Empty, k, _, _) -> k
    | Node (l, _, _, _) -> min_elt l
    | Empty -> raise Not_found

  let rec remove_min_elt = function
    | Node (Empty, _, r, _) -> r
    | Node (l, k, r, _) -> bal (remove_min_elt l) k r
    | Empty -> invalid_arg "PSet.remove_min_elt"

  let merge t1 t2 =
    match t1, t2 with
    | Empty, _ -> t2
    | _, Empty -> t1
    | _ ->
        let k = min_elt t2 in
        bal t1 k (remove_min_elt t2)

  let create cmp = { cmp = cmp; set = Empty }
  let empty = { cmp = compare; set = Empty }

  let is_empty x =
    x.set = Empty

  let rec add_one cmp x = function
    | Node (l, k, r, h) ->
        let c = cmp x k in
        if c = 0 then Node (l, x, r, h)
        else if c < 0 then
          let nl = add_one cmp x l in
          bal nl k r
        else
          let nr = add_one cmp x r in
          bal l k nr
    | Empty -> Node (Empty, x, Empty, 1)

  let add x { cmp = cmp; set = set } =
    { cmp = cmp; set = add_one cmp x set }

  let rec join cmp l v r =
    match (l, r) with
      (Empty, _) -> add_one cmp v r
    | (_, Empty) -> add_one cmp v l
    | (Node(ll, lv, lr, lh), Node(rl, rv, rr, rh)) ->
        if lh > rh + 2 then bal ll lv (join cmp lr v r) else
        if rh > lh + 2 then bal (join cmp l v rl) rv rr else
        make l v r

  let split x { cmp = cmp; set = set } =
    let rec loop x = function
        Empty ->
          (Empty, false, Empty)
      | Node (l, v, r, _) ->
          let c = cmp x v in
          if c = 0 then (l, true, r)
          else if c < 0 then
            let (ll, pres, rl) = loop x l in (ll, pres, join cmp rl v r)
          else
            let (lr, pres, rr) = loop x r in (join cmp l v lr, pres, rr)
    in
    let setl, pres, setr = loop x set in
    { cmp = cmp; set = setl }, pres, { cmp = cmp; set = setr }

  let remove x { cmp = cmp; set = set } =
    let rec loop = function
      | Node (l, k, r, _) ->
          let c = cmp x k in
          if c = 0 then merge l r else
          if c < 0 then bal (loop l) k r else bal l k (loop r)
      | Empty -> Empty in
    { cmp = cmp; set = loop set }

  let mem x { cmp = cmp; set = set } =
    let rec loop = function
      | Node (l, k, r, _) ->
          let c = cmp x k in
          c = 0 || loop (if c < 0 then l else r)
      | Empty -> false in
    loop set

  let exists = mem

  let iter f { set = set } =
    let rec loop = function
      | Empty -> ()
      | Node (l, k, r, _) -> loop l; f k; loop r in
    loop set

  let fold f { cmp = cmp; set = set } acc =
    let rec loop acc = function
      | Empty -> acc
      | Node (l, k, r, _) ->
            loop (f k (loop acc l)) r in
    loop acc set

  let elements { set = set } =
    let rec loop acc = function
        Empty -> acc
      | Node(l, k, r, _) -> loop (k :: loop acc r) l in
    loop [] set
end;;

module type GRAPH_LABELS =
  sig
    type label
  end;;

(* Typ modułu implementującego grafy o wierzchołkach numerowanych od 0 do n-1. *)
module type GRAPH =
  sig
    (* Etykiety krawędzi. *)
    type label

    (* Typ grafów o wierzchołkach typu 'a. *)
    type graph

    (* Pusty graf. *)
    val init : int -> graph

    (* Rozmiar grafu *)
    val size : graph -> int

    (* Dodanie krawędzi skierowanej łączącej dwa wierzchołki. *)
    val insert_directed_edge : graph -> int -> int -> label -> unit

    (* Dodanie krawędzi nieskierowanej (dwukierunkowej) łączącej dwa wierzchołki. *)
    val insert_edge : graph -> int -> int -> label -> unit

    (* Lista incydencji danego wierzchołka. *)
    val neighbours :  graph -> int -> (int*label) list
  end;;

module Graph = functor (L : GRAPH_LABELS) ->
(struct
  (* Etykiety krawędzi. *)
  type label = L.label

  (* Typ grafów - tablica list sąsiedztwa. *)
  type graph = {n : int; e : (int*label) list array}

  (* Pusty graf. *)
  let init s = {n = s; e = Array.make s []}

  (* Rozmiar grafu. *)
  let size g = g.n

  (* Dodanie krawędzi skierowanej łączącej dwa wierzchołki. *)
  let insert_directed_edge g x y l =
    assert ((x<>y)  && (x >= 0) && (x < size g) && (y >= 0) && (y < size g));
    g.e.(x) <- (y,l)::g.e.(x)

  (* Dodanie krawędzi łączącej dwa (istniejące) wierzchołki. *)
  let insert_edge g x y l =
    insert_directed_edge g x y l;
    insert_directed_edge g y x l

  (* Lista incydencji danego wierzchołka. *)
  let neighbours g x =
    g.e.(x)
end : GRAPH with type label = L.label);;

module IntLabel =
  struct
    type label = int
  end;;

module G = Graph(IntLabel);;

open G;;
open PSet;;
let n = scan_int() and m = scan_int() and k = scan_int();;
let g = G.init n;;

let zbior = ref empty;;

for i = 1 to m do
  let a = scan_int() - 1 and b = scan_int() - 1 and c = scan_int() in
  (*dbg a; pnl(); dbg b; pnl(); pnl(); *)
  G.insert_edge g a b c;
done;;

for i = 1 to k do
  let a = scan_int() - 1 and b = scan_int() in
  zbior := add (Int64.of_int(b), 1, a) !zbior;
done;;

zbior := add (Int64.zero, 0, 0) !zbior;;
let dis = Array.make n Int64.max_int;;

let przydatne = ref 0;;

while is_empty !zbior = false do
  let (odl, czy, u) = min_elt (!zbior).set in
  zbior := {cmp = (!zbior).cmp; set = remove_min_elt (!zbior).set};
  if odl < dis.(u) then begin
    (* dbg (Int64.to_int odl); psp(); dbg czy; psp(); dbg u; pnl(); *)
    dis.(u) <- odl;
    if czy = 1 then incr przydatne;
    List.iter (fun (v, w) ->
      let waga = Int64.add odl (Int64.of_int(w)) in
      if waga < dis.(v) then begin
        zbior := add (waga, 0, v) !zbior;
      end;
    ) (neighbours g u);
  end;
done;;

print_int (k - !przydatne);;

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

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

let long x = Int64.of_int x

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

let n = read_int ()
let m = read_int ()
let k = read_int ()
let ne = m + k

let ss = Array.make (2*ne) 0
let ff = Array.make (2*ne) 0
let ww = Array.make (2*ne) 0L
let first = Array.make n (-1)
let next = Array.make (2*ne) 0
let reg_edge = Array.make (2*ne) false
let parent_edge = Array.make n (-1)
let start = 0

let () =
  for i=0 to m-1 do
    let vi = read_int() -1 in
    let ui = read_int() -1 in
    let xi = long (read_int()) in
    ss.(i) <- vi;
    ff.(i+ne) <- vi;
    ff.(i) <- ui;
    ss.(i+ne) <- ui;
    ww.(i) <- xi;
    ww.(i+ne) <- xi;
    reg_edge.(i) <- true;
    reg_edge.(i+ne) <- true;
  done;

  for i=m to ne-1 do
    let vi = read_int() -1 in
    let ui = start in
    let xi = long (read_int()) in
    ss.(i) <- vi;
    ff.(i+ne) <- vi;
    ff.(i) <- ui;
    ss.(i+ne) <- ui;
    ww.(i) <- xi;
    ww.(i+ne) <- xi;
  done;

  for i=0 to 2*ne-1 do
    next.(i) <- first.(ss.(i));
    first.(ss.(i)) <- i;
  done

let inf = 1_000_000_000_000_000_000L
let dist = Array.make n inf
let () = dist.(start) <- 0L

let rec dijkstra s = if Pset.is_empty s then () else
  let (d, v) = Pset.min_elt s in
  let s = Pset.remove (d, v) s in
  let rec loop e s = if e = -1 then s else
    let w = ff.(e) in
      (* processing edge v,w *)
      if dist.(w) = inf then (
	dist.(w) <- dist.(v) ++ ww.(e);
	parent_edge.(w) <- e;
	loop (next.(e)) (Pset.add (dist.(w), w) s)
      ) else if dist.(v) ++ ww.(e) < dist.(w) then (
	let s = Pset.remove (dist.(w), w) s in
	dist.(w) <- dist.(v) ++ ww.(e);
	parent_edge.(w) <- e;
	loop (next.(e)) (Pset.add (dist.(w), w) s)
      ) else if dist.(v) ++ ww.(e) = dist.(w) && reg_edge.(e) then (
	parent_edge.(w) <- e;
	loop (next.(e)) s
      ) else (
	loop (next.(e)) s
      )
  in
    dijkstra (loop first.(v) s)

let () = dijkstra (Pset.singleton (0L,start))

let ecount = ref 0

let () =
  for i=1 to n-1 do
    if parent_edge.(i) < 0 then failwith "graph not connected";
    if not (reg_edge.(parent_edge.(i))) then ecount := !ecount + 1
  done;

  Printf.printf "%d\n" (k - !ecount)

let scan_int () = Scanf.scanf " %d" (fun x -> x);;
let scan_string () = Scanf.scanf " %s" (fun x -> x);;
let psp () = print_string " ";; let pnl () = print_newline ();;
let b2i x = if x == true then 1 else 0;;
let dbg x = print_int(x); pnl();;

module PSet = struct
  type 'k set =
    | Empty
    | Node of 'k set * 'k * 'k set * int

  type 'k t =
    {
      cmp : 'k -> 'k -> int;
      set : 'k set;
    }

  let height = function
    | Node (_, _, _, h) -> h
    | Empty -> 0

  let make l k r = Node (l, k, r, max (height l) (height r) + 1)

  let bal l k r =
    let hl = height l in
    let hr = height r in
    if hl > hr + 2 then
      match l with
      | Node (ll, lk, lr, _) ->
          if height ll >= height lr then make ll lk (make lr k r)
          else
            (match lr with
            | Node (lrl, lrk, lrr, _) ->
                make (make ll lk lrl) lrk (make lrr k r)
            | Empty -> assert false)
      | Empty -> assert false
    else if hr > hl + 2 then
      match r with
      | Node (rl, rk, rr, _) ->
          if height rr >= height rl then make (make l k rl) rk rr
          else
            (match rl with
            | Node (rll, rlk, rlr, _) ->
                make (make l k rll) rlk (make rlr rk rr)
            | Empty -> assert false)
      | Empty -> assert false
    else Node (l, k, r, max hl hr + 1)

  let rec min_elt = function
    | Node (Empty, k, _, _) -> k
    | Node (l, _, _, _) -> min_elt l
    | Empty -> raise Not_found

  let rec remove_min_elt = function
    | Node (Empty, _, r, _) -> r
    | Node (l, k, r, _) -> bal (remove_min_elt l) k r
    | Empty -> invalid_arg "PSet.remove_min_elt"

  let merge t1 t2 =
    match t1, t2 with
    | Empty, _ -> t2
    | _, Empty -> t1
    | _ ->
        let k = min_elt t2 in
        bal t1 k (remove_min_elt t2)

  let create cmp = { cmp = cmp; set = Empty }
  let empty = { cmp = compare; set = Empty }

  let is_empty x =
    x.set = Empty

  let rec add_one cmp x = function
    | Node (l, k, r, h) ->
        let c = cmp x k in
        if c = 0 then Node (l, x, r, h)
        else if c < 0 then
          let nl = add_one cmp x l in
          bal nl k r
        else
          let nr = add_one cmp x r in
          bal l k nr
    | Empty -> Node (Empty, x, Empty, 1)

  let add x { cmp = cmp; set = set } =
    { cmp = cmp; set = add_one cmp x set }

  let rec join cmp l v r =
    match (l, r) with
      (Empty, _) -> add_one cmp v r
    | (_, Empty) -> add_one cmp v l
    | (Node(ll, lv, lr, lh), Node(rl, rv, rr, rh)) ->
        if lh > rh + 2 then bal ll lv (join cmp lr v r) else
        if rh > lh + 2 then bal (join cmp l v rl) rv rr else
        make l v r

  let split x { cmp = cmp; set = set } =
    let rec loop x = function
        Empty ->
          (Empty, false, Empty)
      | Node (l, v, r, _) ->
          let c = cmp x v in
          if c = 0 then (l, true, r)
          else if c < 0 then
            let (ll, pres, rl) = loop x l in (ll, pres, join cmp rl v r)
          else
            let (lr, pres, rr) = loop x r in (join cmp l v lr, pres, rr)
    in
    let setl, pres, setr = loop x set in
    { cmp = cmp; set = setl }, pres, { cmp = cmp; set = setr }

  let remove x { cmp = cmp; set = set } =
    let rec loop = function
      | Node (l, k, r, _) ->
          let c = cmp x k in
          if c = 0 then merge l r else
          if c < 0 then bal (loop l) k r else bal l k (loop r)
      | Empty -> Empty in
    { cmp = cmp; set = loop set }

  let mem x { cmp = cmp; set = set } =
    let rec loop = function
      | Node (l, k, r, _) ->
          let c = cmp x k in
          c = 0 || loop (if c < 0 then l else r)
      | Empty -> false in
    loop set

  let exists = mem

  let iter f { set = set } =
    let rec loop = function
      | Empty -> ()
      | Node (l, k, r, _) -> loop l; f k; loop r in
    loop set

  let fold f { cmp = cmp; set = set } acc =
    let rec loop acc = function
      | Empty -> acc
      | Node (l, k, r, _) ->
            loop (f k (loop acc l)) r in
    loop acc set

  let elements { set = set } =
    let rec loop acc = function
        Empty -> acc
      | Node(l, k, r, _) -> loop (k :: loop acc r) l in
    loop [] set
end;;

module type GRAPH_LABELS =
  sig
    type label
  end;;

(* Typ modułu implementującego grafy o wierzchołkach numerowanych od 0 do n-1. *)
module type GRAPH =
  sig
    (* Etykiety krawędzi. *)
    type label

    (* Typ grafów o wierzchołkach typu 'a. *)
    type graph

    (* Pusty graf. *)
    val init : int -> graph

    (* Rozmiar grafu *)
    val size : graph -> int

    (* Dodanie krawędzi skierowanej łączącej dwa wierzchołki. *)
    val insert_directed_edge : graph -> int -> int -> label -> unit

    (* Dodanie krawędzi nieskierowanej (dwukierunkowej) łączącej dwa wierzchołki. *)
    val insert_edge : graph -> int -> int -> label -> unit

    (* Lista incydencji danego wierzchołka. *)
    val neighbours :  graph -> int -> (int*label) list
  end;;

module Graph = functor (L : GRAPH_LABELS) ->
(struct
  (* Etykiety krawędzi. *)
  type label = L.label

  (* Typ grafów - tablica list sąsiedztwa. *)
  type graph = {n : int; e : (int*label) list array}

  (* Pusty graf. *)
  let init s = {n = s; e = Array.make s []}

  (* Rozmiar grafu. *)
  let size g = g.n

  (* Dodanie krawędzi skierowanej łączącej dwa wierzchołki. *)
  let insert_directed_edge g x y l =
    assert ((x<>y)  && (x >= 0) && (x < size g) && (y >= 0) && (y < size g));
    g.e.(x) <- (y,l)::g.e.(x)

  (* Dodanie krawędzi łączącej dwa (istniejące) wierzchołki. *)
  let insert_edge g x y l =
    insert_directed_edge g x y l;
    insert_directed_edge g y x l

  (* Lista incydencji danego wierzchołka. *)
  let neighbours g x =
    g.e.(x)
end : GRAPH with type label = L.label);;

module IntLabel =
  struct
    type label = int
  end;;

module G = Graph(IntLabel);;

open G;;
open PSet;;
let n = scan_int() and m = scan_int() and k = scan_int();;
let g = G.init n;;

let zbior = ref empty;;

for i = 1 to m do
  let a = scan_int() - 1 and b = scan_int() - 1 and c = scan_int() in
  (*dbg a; pnl(); dbg b; pnl(); pnl(); *)
  G.insert_edge g a b c;
done;;

for i = 1 to k do
  let a = scan_int() - 1 and b = scan_int() in
  zbior := add (Int64.of_int(b), 1, a) !zbior;
done;;

zbior := add (Int64.zero, 0, 0) !zbior;;
let dis = Array.make n Int64.max_int;;

let przydatne = ref 0;;

while is_empty !zbior = false do
  let (odl, czy, u) = min_elt (!zbior).set in
  zbior := {cmp = (!zbior).cmp; set = remove_min_elt (!zbior).set};
  if odl < dis.(u) then begin
    dis.(u) <- odl;
    if czy = 1 then incr przydatne;
    List.iter (fun (v, w) ->
      let waga = Int64.add odl (Int64.of_int(w)) in
      if waga < dis.(v) then begin
        dis.(v) <- waga;
        zbior := add (waga, 0, v) !zbior;
      end;
    ) (neighbours g u);
  end;
done;;

print_int (k - !przydatne);;

let scan_int () = Scanf.scanf " %d" (fun x -> x);;
let scan_string () = Scanf.scanf " %s" (fun x -> x);;
let psp () = print_string " ";; let pnl () = print_newline ();;
let b2i x = if x == true then 1 else 0;;
let dbg x = print_int(x); pnl();;

module PSet = struct
  type 'k set =
    | Empty
    | Node of 'k set * 'k * 'k set * int

  type 'k t =
    {
      cmp : 'k -> 'k -> int;
      set : 'k set;
    }

  let height = function
    | Node (_, _, _, h) -> h
    | Empty -> 0

  let make l k r = Node (l, k, r, max (height l) (height r) + 1)

  let bal l k r =
    let hl = height l in
    let hr = height r in
    if hl > hr + 2 then
      match l with
      | Node (ll, lk, lr, _) ->
          if height ll >= height lr then make ll lk (make lr k r)
          else
            (match lr with
            | Node (lrl, lrk, lrr, _) ->
                make (make ll lk lrl) lrk (make lrr k r)
            | Empty -> assert false)
      | Empty -> assert false
    else if hr > hl + 2 then
      match r with
      | Node (rl, rk, rr, _) ->
          if height rr >= height rl then make (make l k rl) rk rr
          else
            (match rl with
            | Node (rll, rlk, rlr, _) ->
                make (make l k rll) rlk (make rlr rk rr)
            | Empty -> assert false)
      | Empty -> assert false
    else Node (l, k, r, max hl hr + 1)

  let rec min_elt = function
    | Node (Empty, k, _, _) -> k
    | Node (l, _, _, _) -> min_elt l
    | Empty -> raise Not_found

  let rec remove_min_elt = function
    | Node (Empty, _, r, _) -> r
    | Node (l, k, r, _) -> bal (remove_min_elt l) k r
    | Empty -> invalid_arg "PSet.remove_min_elt"

  let merge t1 t2 =
    match t1, t2 with
    | Empty, _ -> t2
    | _, Empty -> t1
    | _ ->
        let k = min_elt t2 in
        bal t1 k (remove_min_elt t2)

  let create cmp = { cmp = cmp; set = Empty }
  let empty = { cmp = compare; set = Empty }

  let is_empty x =
    x.set = Empty

  let rec add_one cmp x = function
    | Node (l, k, r, h) ->
        let c = cmp x k in
        if c = 0 then Node (l, x, r, h)
        else if c < 0 then
          let nl = add_one cmp x l in
          bal nl k r
        else
          let nr = add_one cmp x r in
          bal l k nr
    | Empty -> Node (Empty, x, Empty, 1)

  let add x { cmp = cmp; set = set } =
    { cmp = cmp; set = add_one cmp x set }

  let rec join cmp l v r =
    match (l, r) with
      (Empty, _) -> add_one cmp v r
    | (_, Empty) -> add_one cmp v l
    | (Node(ll, lv, lr, lh), Node(rl, rv, rr, rh)) ->
        if lh > rh + 2 then bal ll lv (join cmp lr v r) else
        if rh > lh + 2 then bal (join cmp l v rl) rv rr else
        make l v r

  let split x { cmp = cmp; set = set } =
    let rec loop x = function
        Empty ->
          (Empty, false, Empty)
      | Node (l, v, r, _) ->
          let c = cmp x v in
          if c = 0 then (l, true, r)
          else if c < 0 then
            let (ll, pres, rl) = loop x l in (ll, pres, join cmp rl v r)
          else
            let (lr, pres, rr) = loop x r in (join cmp l v lr, pres, rr)
    in
    let setl, pres, setr = loop x set in
    { cmp = cmp; set = setl }, pres, { cmp = cmp; set = setr }

  let remove x { cmp = cmp; set = set } =
    let rec loop = function
      | Node (l, k, r, _) ->
          let c = cmp x k in
          if c = 0 then merge l r else
          if c < 0 then bal (loop l) k r else bal l k (loop r)
      | Empty -> Empty in
    { cmp = cmp; set = loop set }

  let mem x { cmp = cmp; set = set } =
    let rec loop = function
      | Node (l, k, r, _) ->
          let c = cmp x k in
          c = 0 || loop (if c < 0 then l else r)
      | Empty -> false in
    loop set

  let exists = mem

  let iter f { set = set } =
    let rec loop = function
      | Empty -> ()
      | Node (l, k, r, _) -> loop l; f k; loop r in
    loop set

  let fold f { cmp = cmp; set = set } acc =
    let rec loop acc = function
      | Empty -> acc
      | Node (l, k, r, _) ->
            loop (f k (loop acc l)) r in
    loop acc set

  let elements { set = set } =
    let rec loop acc = function
        Empty -> acc
      | Node(l, k, r, _) -> loop (k :: loop acc r) l in
    loop [] set
end;;

module type GRAPH_LABELS =
  sig
    type label
  end;;

(* Typ modułu implementującego grafy o wierzchołkach numerowanych od 0 do n-1. *)
module type GRAPH =
  sig
    (* Etykiety krawędzi. *)
    type label

    (* Typ grafów o wierzchołkach typu 'a. *)
    type graph

    (* Pusty graf. *)
    val init : int -> graph

    (* Rozmiar grafu *)
    val size : graph -> int

    (* Dodanie krawędzi skierowanej łączącej dwa wierzchołki. *)
    val insert_directed_edge : graph -> int -> int -> label -> unit

    (* Dodanie krawędzi nieskierowanej (dwukierunkowej) łączącej dwa wierzchołki. *)
    val insert_edge : graph -> int -> int -> label -> unit

    (* Lista incydencji danego wierzchołka. *)
    val neighbours :  graph -> int -> (int*label) list
  end;;

module Graph = functor (L : GRAPH_LABELS) ->
(struct
  (* Etykiety krawędzi. *)
  type label = L.label

  (* Typ grafów - tablica list sąsiedztwa. *)
  type graph = {n : int; e : (int*label) list array}

  (* Pusty graf. *)
  let init s = {n = s; e = Array.make s []}

  (* Rozmiar grafu. *)
  let size g = g.n

  (* Dodanie krawędzi skierowanej łączącej dwa wierzchołki. *)
  let insert_directed_edge g x y l =
    assert ((x<>y)  && (x >= 0) && (x < size g) && (y >= 0) && (y < size g));
    g.e.(x) <- (y,l)::g.e.(x)

  (* Dodanie krawędzi łączącej dwa (istniejące) wierzchołki. *)
  let insert_edge g x y l =
    insert_directed_edge g x y l;
    insert_directed_edge g y x l

  (* Lista incydencji danego wierzchołka. *)
  let neighbours g x =
    g.e.(x)
end : GRAPH with type label = L.label);;

module IntLabel =
  struct
    type label = int
  end;;

module G = Graph(IntLabel);;

open G;;
open PSet;;
let n = scan_int() and m = scan_int() and k = scan_int();;
let g = G.init n;;

let zbior = ref empty;;

for i = 1 to m do
  let a = scan_int() - 1 and b = scan_int() - 1 and c = scan_int() in
  (*dbg a; pnl(); dbg b; pnl(); pnl(); *)
  G.insert_edge g a b c;
done;;

for i = 1 to k do
  let a = scan_int() - 1 and b = scan_int() in
  zbior := add (Int64.of_int(b), 1, a) !zbior;
done;;

zbior := add (Int64.zero, 0, 0) !zbior;;
let dis = Array.make n Int64.max_int;;

let przydatne = ref 0;;

while is_empty !zbior = false do
  let (odl, czy, u) = min_elt (!zbior).set in
  zbior := {cmp = (!zbior).cmp; set = remove_min_elt (!zbior).set};
  if odl < dis.(u) then begin
    dis.(u) <- odl;
    if czy = 1 then incr przydatne;
    List.iter (fun (v, w) ->
      let waga = Int64.add odl (Int64.of_int(w)) in
      if waga < dis.(v) then begin
        zbior := remove (dis.(v), 0, v) !zbior;
        zbior := remove (dis.(v), 1, v) !zbior;
        dis.(v) <- waga;
        zbior := add (waga, 0, v) !zbior;
      end;
    ) (neighbours g u);
  end;
done;;

print_int (k - !przydatne);;


One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2·n there are exactly m numbers which binary representation contains exactly k digits one".The girl got interested in the task and she asked you to help her solve it. Sasha knows that you are afraid of large numbers, so she guaranteed that there is an answer that doesn't exceed 1018.

The first line contains two space-separated integers, m and k (0 ≤ m ≤ 1018; 1 ≤ k ≤ 64).

Print the required number n (1 ≤ n ≤ 1018). If there are multiple answers, print any of them.

open Printf
open Scanf

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

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

let ( lsl ) a i = Int64.shift_left a i
let ( lsr ) a i = Int64.shift_right a i
let ( land ) a b = Int64.logand a b

let init_binomial n m =
  (* compute an array b so that b.(p).(q) = (p choose q),
     where 0 <= p <= n and 0 <= q <= m. *)
  let b = Array.make_matrix (n+1) (m+1) 0L in
    for i=0 to n do for j=0 to min i m do
      b.(i).(j) <- if j=0 then 1L else b.(i-1).(j-1) ++ b.(i-1).(j)
    done done;
    b

let b = init_binomial 64 64

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

  let up_to n =
  (* count the number of numbers in 1...n-1 with k 1s in their rep. *)
  (* n>=1  k>=1 *)
    let rec loop i k ac = if i<0 then ac else
	if (1L lsl i) land n <> 0L then (
	  loop (i-1) (k-1) (ac ++ b.(i).(k))
	) else (
	  loop (i-1) k ac
	)
    in
    loop 63 k 0L
  in

  let eval n =
    (up_to ((n ++ n) ++ 1L)) -- (up_to (n++1L))
  in

  let rec upper_bound n =
    if eval n >= m then n else upper_bound (n++n)
  in

  let rec bsearch lo hi = (* eval lo < m, eval hi >= m *)
    if lo ++ 1L = hi then hi else
      let mid = (lo ++ hi) lsr 1 in
      if eval mid < m then bsearch mid hi else bsearch lo mid
  in

  printf "%Ld\n" (bsearch 0L (upper_bound 1L))


You are given two integers $$$n$$$ and $$$k$$$.Your task is to construct such a string $$$s$$$ of length $$$n$$$ that for each $$$i$$$ from $$$1$$$ to $$$k$$$ there is at least one $$$i$$$-th letter of the Latin alphabet in this string (the first letter is 'a', the second is 'b' and so on) and there are no other letters except these. You have to maximize the minimal frequency of some letter (the frequency of a letter is the number of occurrences of this letter in a string). If there are several possible answers, you can print any.You have to answer $$$t$$$ independent queries.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of queries. The next $$$t$$$ lines are contain queries, one per line. The $$$i$$$-th line contains two integers $$$n_i$$$ and $$$k_i$$$ ($$$1 \le n_i \le 100, 1 \le k_i \le min(n_i, 26)$$$) — the length of the string in the $$$i$$$-th query and the number of characters in the $$$i$$$-th query.

Print $$$t$$$ lines. In the $$$i$$$-th line print the answer to the $$$i$$$-th query: any string $$$s_i$$$ satisfying the conditions in the problem statement with constraints from the $$$i$$$-th query.

NoteIn the first example query the maximum possible minimal frequency is $$$2$$$, it can be easily seen that the better answer doesn't exist. Other examples of correct answers: "cbcabba", "ccbbaaa" (any permutation of given answers is also correct).In the second example query any permutation of first four letters is acceptable (the maximum minimal frequency is $$$1$$$).In the third example query any permutation of the given answer is acceptable (the maximum minimal frequency is $$$3$$$).

open Printf open Scanf
module Lib = struct
  let i32,i64,ist = Int64.(to_int,of_int,to_string)
  let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)
  let labs = Int64.abs
  let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)
  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 (%=) r v = r := !r % v
  let max_i64,min_i64 = Int64.(max_int,min_int)
  (* math *)
  let ceildiv p q = (p+q-1L) / q
  let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
  let lcm m n = m / gcd m n * n
  module Int64_infix = struct
    let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =
      let open Int64 in
      (logand),(logor),(logxor),lognot,
      (fun u v -> shift_left u (i32 v)),
      (fun u v -> shift_right u (i32 v)),
      (fun u v -> shift_right_logical u (i32 v))
  end
  let pow n k =
    let rec f a n = function
    | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)
    in f 1L n k
  (* input *)
  let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v)) let iia = input_i64_array
  let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v) let gi = get_i64
  let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v) let g2 = get_2_i64
  let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w) let g3 = get_3_i64
  let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x) let g4 = get_4_i64
  let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64
  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)
  (* utils *)
  external id : 'a -> 'a = "%identity"
  let ( *< ) f g x = f (g x)
  let ( *> ) f g x = g (f x)
  let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)
  let alen a = i64 @@ Array.length a
  let llen l = i64 @@  List.length l
  let string_of_list ?(separator=" ") f ls = ls |> List.map f |> String.concat separator
  let string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
  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 fail _ = failwith "fail"
  let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]
  let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev
  let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten
  let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a
  let binary_search ng ok f = let d = if ng < ok then 1L else -1L in
    let rec f0 ng ok =
      if labs (ok - ng) <= 1L then ok
      else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
    in f0 (ng-1L*d) (ok+1L*d)
  let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)
  let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >  v)
  let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)
  let rec fix f x = f (fix f) x
  let fix_memo ?(size=10000) f x =
    let tb = Hashtbl.create ~random:true size in
    let rec f0 x =
      try Hashtbl.find tb x with
      | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)
    in f0 x
  (* imperative *)
  let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done
  let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done
  let repm f t ?(stride=1L) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m
  let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done
  let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done
  let repim f t ?(stride=1) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m
  let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v
  let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v
  let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v
  let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v
  (* output *)
  let print_list_mle f ls = string_of_list f ls |> print_endline
  let print_array_mle f a = string_of_array f a |> print_endline
  let print_list f ls = ls |> List.iter (fun v -> printf "%s " @@ f v); print_newline ()
  let print_array f a = a |> Array.iter (fun v -> printf "%s " @@ f v); print_newline ()
  (* debug *)
  let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)
  let dump_i64_list ls = print_list ist ls
  let dump_i64_array a = print_array ist a
end open Lib open Array

let () =
  let t = gi  0 in
  rep 1L t @@ fun _ ->
    let n,k = g2 0 in
    let d = n / k in
    let r = n - d * k in
    repi 1 (i32 k-$1) (fun i->
      let c = (int_of_char 'a' +$  i-$1) |> char_of_int in

      rep 1L d (fun _ -> printf "%c" c)
    );let c = (int_of_char 'a' +$  i32 k-$1) |> char_of_int in

    rep 1L (d+r) (fun _ -> printf "%c" c); print_endline ""


While Duff was resting in the beach, she accidentally found a strange array b0, b1, ..., bl - 1 consisting of l positive integers. This array was strange because it was extremely long, but there was another (maybe shorter) array, a0, ..., an - 1 that b can be build from a with formula: bi = ai mod n where a mod b denoted the remainder of dividing a by b.  Duff is so curious, she wants to know the number of subsequences of b like bi1, bi2, ..., bix (0 ≤ i1 < i2 < ... < ix < l), such that:   1 ≤ x ≤ k  For each 1 ≤ j ≤ x - 1,   For each 1 ≤ j ≤ x - 1, bij ≤ bij + 1. i.e this subsequence is non-decreasing. Since this number can be very large, she want to know it modulo 109 + 7.Duff is not a programmer, and Malek is unavailable at the moment. So she asked for your help. Please tell her this number.

The first line of input contains three integers, n, l and k (1 ≤ n, k, n × k ≤ 106 and 1 ≤ l ≤ 1018). The second line contains n space separated integers, a0, a1, ..., an - 1 (1 ≤ ai ≤ 109 for each 0 ≤ i ≤ n - 1).

Print the answer modulo 1 000 000 007 in one line.

NoteIn the first sample case, . So all such sequences are: , , , , , , , ,  and .

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let mm = 1000000007 in
  let mmm = Int64.of_int mm in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let l = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
  in
  let m = l /| (Int64.of_int n) in
  let n' = Int64.to_int (Int64.rem l (Int64.of_int n)) in
  let a' = Array.sub a 0 n' in
  let b = Array.copy a in
  let () = Array.sort compare b in
  let b' = Array.copy a' in
  let () = Array.sort compare b' in
  let bs a x =
    let l = ref (-1) in
    let r = ref (Array.length a) in
      while !l < !r - 1 do
	let m = (!l + !r) lsr 1 in
	  if a.(m) <= x
	  then l := m
	  else r := m
      done;
      !r
  in
  let d = Array.make_matrix n (k + 1) 1 in
  (*let cc = Array.init n (fun i -> bs b a.(i)) in*)
  let _ =
    for j = 1 to k do
      let p = ref 0 in
	for i = 0 to n - 1 do
	  while !p < n && b.(!p) <= b.(i) do
	    incr p;
	  done;
	  d.(i).(j) <-
	    if i = 0
	    then d.(!p - 1).(j - 1)
	    else
	      Int32.to_int
		(Int32.rem
		   (Int32.add
		      (Int32.of_int d.(i - 1).(j))
		      (Int32.of_int d.(!p - 1).(j - 1)))
		   (Int32.of_int mm));
	  (*Printf.printf "zxc %d %d %d\n" i j d.(i).(j)*)
	done
    done;
  in
  let res = ref 0L in
    for i = 0 to n' - 1 do
      let c = bs b a.(i) in
	(*Printf.printf "asd %d %d %d\n" i a.(i) c;*)
	for kk = 1 to k do
	  let k = kk - 1 in
	    if Int64.of_int k <= m then (
	      res :=
		Int64.rem
		  (!res +|
		       (*Int64.of_int bmk.(k) *| *)
			   Int64.of_int d.(c - 1).(k)) mmm;
	      (*Printf.printf "qwe %d %Ld %d\n" k !res bmk.(k)*)
	    )
	done;
    done;
    for kk = 1 to k do
      let k = kk in
	if Int64.of_int k <= m then (
	  res :=
	    Int64.rem
	      (!res +|
		   Int64.rem (m -| Int64.of_int (k - 1)) mmm *|
		       Int64.of_int d.(n - 1).(k)) mmm;
	  (*Printf.printf "qwe %d %Ld %d\n" k !res bmk.(k)*)
	)
    done;
    Printf.printf "%Ld\n" !res

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

let m = 1_000_000_007

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

let ll a = Int64.of_int a

let add a b = Int64.to_int (((ll a) ++ (ll b)) %% (ll m))

let () =
  let n = read_int () in
  let l = Int64.of_string (read_string ()) in
  let k = read_int () in
  let a = Array.init n (fun _ -> read_int ()) in
  let sorted = Array.init n (fun i -> (a.(i), i)) in
  Array.sort (fun a b -> (fst a) - (fst b)) sorted;

  let f = Array.make_matrix (k+1) n 0 in
  for j = 0 to n-1 do
    f.(1).(j) <- 1
  done;

  for i = 2 to k do
    let sum = ref 0 in
    let l = ref 0 in
    while !l < n do
      let r = ref !l in
      while !r < n && (fst sorted.(!r)) = (fst sorted.(!l)) do
        sum := add !sum f.(i-1).(snd sorted.(!r));
        r := !r + 1
      done;
      while !l < !r do
        f.(i).(snd sorted.(!l)) <- !sum;
        l := !l + 1
      done;
    done;
  done;

  let ans = ref 0 in
  for i = 1 to k do
    for j = 0 to n-1 do
      let len = ((ll (i-1)) ** (ll n)) ++ (ll (j+1)) in
      let ways = (l -- len ++ (ll n)) // (ll n) %% (ll m) in
      let llf = ll f.(i).(j) in
      let total = (ways ** llf) %% (ll m) in
      if len <= l then ans := add !ans (Int64.to_int total)
    done;
  done;

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

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let mm = 1000000007 in
  let mmm = Int64.of_int mm in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let l = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
  in
  let inv = Array.make 1000001 1 in
  let _ =
    for i = 2 to 1000000 do
      inv.(i) <-
	Int64.to_int
	(Int64.rem
	   (mmm -| Int64.rem (Int64.of_int (mm / i) *| Int64.of_int inv.(mm mod i)) mmm)
	   mmm);
    done
  in
  let fact = Array.make (n + k + 2) 1 in
  let ifact = Array.make (n + k + 2) 1 in
  let () =
    for i = 2 to n + k + 1 do
      fact.(i) <-
	Int64.to_int
	(Int64.rem
	   (Int64.of_int fact.(i - 1) *| Int64.of_int i) mmm);
      ifact.(i) <-
	Int64.to_int
	(Int64.rem
	   (Int64.of_int ifact.(i - 1) *| Int64.of_int inv.(i)) mmm);
    done;
  in
  let binom n k =
    Int64.to_int
      (Int64.rem
	 (Int64.rem (Int64.of_int fact.(n) *| Int64.of_int ifact.(n - k)) mmm *|
	      Int64.of_int ifact.(k)) mmm)
  in
  (*let binomial = Array.make_matrix (n + k + 1) (k + 1) 0 in
  let _ =
    binomial.(0).(0) <- 1;
    for i = 1 to n + k do
      binomial.(i).(0) <- 1;
      for j = 1 to k do
	binomial.(i).(j) <-
	  (Int32.to_int
	     (Int32.rem
		(Int32.add
		   (Int32.of_int binomial.(i - 1).(j - 1))
		   (Int32.of_int binomial.(i - 1).(j)))
		(Int32.of_int mm)))
      done
    done
  in*)
  let m = l /| (Int64.of_int n) in
  let bmk = Array.make (k + 1) 1 in
  let _ =
    let m = Int64.rem m mmm in
      for i = 1 to k do
	bmk.(i) <-
	  Int64.to_int
	  (Int64.rem
	     (Int64.rem
		(Int64.of_int bmk.(i - 1) *| (m -| Int64.of_int (i - 1))) mmm *|
		    Int64.of_int inv.(i))
	     mmm);
	(*Printf.printf "qwe %Ld %d %d %d\n" m i bmk.(i) inv.(i)*)
      done;
  in
  let n' = Int64.to_int (Int64.rem l (Int64.of_int n)) in
  let a' = Array.sub a 0 n' in
  let b = Array.copy a in
  let () = Array.sort compare b in
  let b' = Array.copy a' in
  let () = Array.sort compare b' in
  let bs a x =
    let l = ref (-1) in
    let r = ref (Array.length a) in
      while !l < !r - 1 do
	let m = (!l + !r) lsr 1 in
	  if a.(m) <= x
	  then l := m
	  else r := m
      done;
      !r
  in
  let res = ref 0L in
    for i = 0 to n' - 1 do
      let c = bs b a.(i) in
	(*Printf.printf "asd %d %d %d\n" i a.(i) c;*)
	for kk = 1 to k do
	  let k = kk - 1 in
	    res :=
	      Int64.rem
		(!res +|
		     Int64.of_int bmk.(k) *|
			 Int64.of_int (binom (c + k - 1) k)) mmm;
	    (*Printf.printf "qwe %d %Ld %d\n" k !res bmk.(k)*)
	done;
    done;
    for kk = 1 to k do
      let k = kk in
	res :=
	  Int64.rem
	    (!res +|
		 Int64.of_int bmk.(k) *|
		     Int64.of_int (binom (n + k - 1) k)) mmm;
	(*Printf.printf "qwe %d %Ld %d\n" k !res bmk.(k)*)
    done;
    Printf.printf "%Ld\n" !res

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let mm = 1000000007 in
  let mmm = Int64.of_int mm in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let l = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
  in
  let inv = Array.make 1000001 1 in
  let _ =
    for i = 2 to 1000000 do
      inv.(i) <-
	Int64.to_int
	(Int64.rem
	   (mmm -| Int64.rem (Int64.of_int (mm / i) *| Int64.of_int inv.(mm mod i)) mmm)
	   mmm);
    done
  in
  let m = l /| (Int64.of_int n) in
  let bmk = Array.make (k + 1) 1 in
  let _ =
    let m = Int64.rem m mmm in
      for i = 1 to k do
	bmk.(i) <-
	  Int64.to_int
	  (Int64.rem
	     (Int64.rem
		(Int64.of_int bmk.(i - 1) *| (m -| Int64.of_int (i - 1))) mmm *|
		    Int64.of_int inv.(i))
	     mmm);
	(*Printf.printf "qwe %Ld %d %d %d\n" m i bmk.(i) inv.(i)*)
      done;
  in
  let n' = Int64.to_int (Int64.rem l (Int64.of_int n)) in
  let a' = Array.sub a 0 n' in
  let b = Array.copy a in
  let () = Array.sort compare b in
  let b' = Array.copy a' in
  let () = Array.sort compare b' in
  let bs a x =
    let l = ref (-1) in
    let r = ref (Array.length a) in
      while !l < !r - 1 do
	let m = (!l + !r) lsr 1 in
	  if a.(m) <= x
	  then l := m
	  else r := m
      done;
      !r
  in
  let d = Array.make_matrix n (k + 1) 1 in
  (*let cc = Array.init n (fun i -> bs b a.(i)) in*)
  let _ =
    for j = 1 to k do
      let p = ref 0 in
	for i = 0 to n - 1 do
	  while !p < n && b.(!p) <= b.(i) do
	    incr p;
	  done;
	  d.(i).(j) <-
	    if i = 0
	    then d.(!p - 1).(j - 1)
	    else
	      Int32.to_int
		(Int32.rem
		   (Int32.add
		      (Int32.of_int d.(i - 1).(j))
		      (Int32.of_int d.(!p - 1).(j - 1)))
		   (Int32.of_int mm));
	  (*Printf.printf "zxc %d %d %d\n" i j d.(i).(j)*)
	done
    done;
  in
  let res = ref 0L in
    for i = 0 to n' - 1 do
      let c = bs b a.(i) in
	(*Printf.printf "asd %d %d %d\n" i a.(i) c;*)
	for kk = 1 to k do
	  let k = kk - 1 in
	    if Int64.of_int k <= m then (
	      res :=
		Int64.rem
		  (!res +|
		       (*Int64.of_int bmk.(k) *| *)
			   Int64.of_int d.(c - 1).(k)) mmm;
	      (*Printf.printf "qwe %d %Ld %d\n" k !res bmk.(k)*)
	    )
	done;
    done;
    for kk = 1 to k do
      let k = kk in
	if Int64.of_int k <= m then (
	  res :=
	    Int64.rem
	      (!res +|
		   (m -| Int64.of_int (k - 1)) *|
		       Int64.of_int d.(n - 1).(k)) mmm;
	  (*Printf.printf "qwe %d %Ld %d\n" k !res bmk.(k)*)
	)
    done;
    Printf.printf "%Ld\n" !res

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let mm = 1000000007 in
  let mmm = Int64.of_int mm in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let l = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
  in
  let inv = Array.make 1000001 1 in
  let _ =
    for i = 2 to 1000000 do
      inv.(i) <-
	Int64.to_int
	(Int64.rem
	   (mmm -| Int64.rem (Int64.of_int (mm / i) *| Int64.of_int inv.(mm mod i)) mmm)
	   mmm);
    done
  in
  let fact = Array.make (n + k + 2) 1 in
  let ifact = Array.make (n + k + 2) 1 in
  let () =
    for i = 2 to n + k + 1 do
      fact.(i) <-
	Int64.to_int
	(Int64.rem
	   (Int64.of_int fact.(i - 1) *| Int64.of_int i) mmm);
      ifact.(i) <-
	Int64.to_int
	(Int64.rem
	   (Int64.of_int ifact.(i - 1) *| Int64.of_int inv.(i)) mmm);
    done;
  in
  let binom n k =
    Int64.to_int
      (Int64.rem
	 (Int64.rem (Int64.of_int fact.(n) *| Int64.of_int ifact.(n - k)) mmm *|
	      Int64.of_int ifact.(k)) mmm)
  in
  (*let binomial = Array.make_matrix (n + k + 1) (k + 1) 0 in
  let _ =
    binomial.(0).(0) <- 1;
    for i = 1 to n + k do
      binomial.(i).(0) <- 1;
      for j = 1 to k do
	binomial.(i).(j) <-
	  (Int32.to_int
	     (Int32.rem
		(Int32.add
		   (Int32.of_int binomial.(i - 1).(j - 1))
		   (Int32.of_int binomial.(i - 1).(j)))
		(Int32.of_int mm)))
      done
    done
  in*)
  let m = l /| (Int64.of_int n) in
  let bmk = Array.make (k + 1) 1 in
  let _ =
    let m = Int64.rem m mmm in
      for i = 1 to k do
	bmk.(i) <-
	  Int64.to_int
	  (Int64.rem
	     (Int64.rem
		(Int64.of_int bmk.(i - 1) *| (m -| Int64.of_int (i - 1))) mmm *|
		    Int64.of_int inv.(i))
	     mmm);
	(*Printf.printf "qwe %Ld %d %d %d\n" m i bmk.(i) inv.(i)*)
      done;
  in
  let n' = Int64.to_int (Int64.rem l (Int64.of_int n)) in
  let a' = Array.sub a 0 n' in
  let b = Array.copy a in
  let () = Array.sort compare b in
  let b' = Array.copy a' in
  let () = Array.sort compare b' in
  let bs a x =
    let l = ref (-1) in
    let r = ref (Array.length a) in
      while !l < !r - 1 do
	let m = (!l + !r) lsr 1 in
	  if a.(m) <= x
	  then l := m
	  else r := m
      done;
      !r
  in
  let d = Array.make_matrix n (k + 1) 1 in
  (*let cc = Array.init n (fun i -> bs b a.(i)) in*)
  let _ =
    d.(0).(0) <- 1;
    for j = 1 to k do
      let p = ref 0 in
	for i = 0 to n - 1 do
	  while !p < n && b.(!p) <= b.(i) do
	    incr p;
	  done;
	  d.(i).(j) <-
	    if i = 0
	    then d.(!p - 1).(j - 1)
	    else
	      Int32.to_int
		(Int32.rem
		   (Int32.add
		      (Int32.of_int d.(i - 1).(j))
		      (Int32.of_int d.(!p - 1).(j - 1)))
		   (Int32.of_int mm));
	  (*Printf.printf "zxc %d %d %d\n" i j d.(i).(j)*)
	done
    done;
  in
  let res = ref 0L in
    for i = 0 to n' - 1 do
      let c = bs b a.(i) in
	(*Printf.printf "asd %d %d %d\n" i a.(i) c;*)
	for kk = 1 to k do
	  let k = kk - 1 in
	    res :=
	      Int64.rem
		(!res +|
		     Int64.of_int bmk.(k) *|
			 Int64.of_int d.(c - 1).(k)) mmm;
	    (*Printf.printf "qwe %d %Ld %d\n" k !res bmk.(k)*)
	done;
    done;
    for kk = 1 to k do
      let k = kk in
	res :=
	  Int64.rem
	    (!res +|
		 Int64.of_int bmk.(k) *|
		     Int64.of_int d.(n - 1).(k)) mmm;
	(*Printf.printf "qwe %d %Ld %d\n" k !res bmk.(k)*)
    done;
    Printf.printf "%Ld\n" !res

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let mm = 1000000007 in
  let mmm = Int64.of_int mm in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let l = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
  in
  let inv = Array.make 1000001 1 in
  let _ =
    for i = 2 to 1000000 do
      inv.(i) <-
	Int64.to_int
	(Int64.rem
	   (mmm -| Int64.rem (Int64.of_int (mm / i) *| Int64.of_int inv.(mm mod i)) mmm)
	   mmm);
    done
  in
  let fact = Array.make (n + k + 2) 1 in
  let ifact = Array.make (n + k + 2) 1 in
  let () =
    for i = 2 to n + k + 1 do
      fact.(i) <-
	Int64.to_int
	(Int64.rem
	   (Int64.of_int fact.(i - 1) *| Int64.of_int i) mmm);
      ifact.(i) <-
	Int64.to_int
	(Int64.rem
	   (Int64.of_int ifact.(i - 1) *| Int64.of_int inv.(i)) mmm);
    done;
  in
  let binom n k =
    Int64.to_int
      (Int64.rem
	 (Int64.rem (Int64.of_int fact.(n) *| Int64.of_int ifact.(n - k)) mmm *|
	      Int64.of_int ifact.(k)) mmm)
  in
  (*let binomial = Array.make_matrix (n + k + 1) (k + 1) 0 in
  let _ =
    binomial.(0).(0) <- 1;
    for i = 1 to n + k do
      binomial.(i).(0) <- 1;
      for j = 1 to k do
	binomial.(i).(j) <-
	  (Int32.to_int
	     (Int32.rem
		(Int32.add
		   (Int32.of_int binomial.(i - 1).(j - 1))
		   (Int32.of_int binomial.(i - 1).(j)))
		(Int32.of_int mm)))
      done
    done
  in*)
  let m = l /| (Int64.of_int n) in
  let bmk = Array.make (k + 1) 1 in
  let _ =
    let m = Int64.rem m mmm in
      for i = 1 to k do
	bmk.(i) <-
	  Int64.to_int
	  (Int64.rem
	     (Int64.rem
		(Int64.of_int bmk.(i - 1) *| (m -| Int64.of_int (i - 1))) mmm *|
		    Int64.of_int inv.(i))
	     mmm);
	(*Printf.printf "qwe %Ld %d %d %d\n" m i bmk.(i) inv.(i)*)
      done;
  in
  let n' = Int64.to_int (Int64.rem l (Int64.of_int n)) in
  let a' = Array.sub a 0 n' in
  let b = Array.copy a in
  let () = Array.sort compare b in
  let b' = Array.copy a' in
  let () = Array.sort compare b' in
  let bs a x =
    let l = ref (-1) in
    let r = ref (Array.length a) in
      while !l < !r - 1 do
	let m = (!l + !r) lsr 1 in
	  if a.(m) <= x
	  then l := m
	  else r := m
      done;
      !r
  in
  let d = Array.make_matrix n (k + 1) 1 in
  (*let cc = Array.init n (fun i -> bs b a.(i)) in*)
  let _ =
    d.(0).(0) <- 1;
    for j = 1 to k do
      let p = ref 0 in
	for i = 0 to n - 1 do
	  while !p < n && b.(!p) <= b.(i) do
	    incr p;
	  done;
	  d.(i).(j) <-
	    if i = 0
	    then d.(!p - 1).(j - 1)
	    else
	      Int32.to_int
		(Int32.rem
		   (Int32.add
		      (Int32.of_int d.(i - 1).(j))
		      (Int32.of_int d.(!p - 1).(j - 1)))
		   (Int32.of_int mm));
	  (*Printf.printf "zxc %d %d %d\n" i j d.(i).(j)*)
	done
    done;
  in
  let res = ref 0L in
    for i = 0 to n' - 1 do
      let c = bs b a.(i) in
	(*Printf.printf "asd %d %d %d\n" i a.(i) c;*)
	for kk = 1 to k do
	  let k = kk - 1 in
	    res :=
	      Int64.rem
		(!res +|
		     Int64.of_int bmk.(k) *|
			 Int64.of_int (binom (c + k - 1) k)) mmm;
	    (*Printf.printf "qwe %d %Ld %d\n" k !res bmk.(k)*)
	done;
    done;
    for kk = 1 to k do
      let k = kk in
	res :=
	  Int64.rem
	    (!res +|
		 Int64.of_int bmk.(k) *|
		     Int64.of_int d.(n - 1).(k)) mmm;
	(*Printf.printf "qwe %d %Ld %d\n" k !res bmk.(k)*)
    done;
    Printf.printf "%Ld\n" !res

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

let m = 1_000_000_007

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

let ll a = Int64.of_int a

let () =
  let n = read_int () in
  let l = Int64.of_string (read_string ()) in
  let k = read_int () in
  let a = Array.init n (fun _ -> read_int ()) in
  let sorted = Array.init n (fun i -> (a.(i), i)) in
  Array.sort (fun a b -> (fst a) - (fst b)) sorted;

  let f = Array.make_matrix (k+1) n 0 in
  for j = 0 to n-1 do
    f.(1).(j) <- 1
  done;

  for i = 2 to k do
    let sum = ref 0 in
    let l = ref 0 in
    while !l < n do
      let r = ref !l in
      while !r < n && (fst sorted.(!r)) = (fst sorted.(!l)) do
        sum := (!sum + f.(i-1).(snd sorted.(!r))) mod m;
        r := !r + 1
      done;
      while !l < !r do
        f.(i).(snd sorted.(!l)) <- !sum;
        l := !l + 1
      done;
    done;
  done;

  let ans = ref 0 in
  for i = 1 to k do
    for j = 0 to n-1 do
      let len = ((ll (i-1)) ** (ll n)) ++ (ll (j+1)) in
      let ways = (l -- len ++ (ll n)) // (ll n) %% (ll m) in
      let llf = ll f.(i).(j) in
      let total = (ways ** llf) %% (ll m) in
      if len <= l then ans := (!ans + (Int64.to_int total)) mod m
    done;
  done;

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


Polycarpus has an array, consisting of n integers a1, a2, ..., an. Polycarpus likes it when numbers in an array match. That's why he wants the array to have as many equal numbers as possible. For that Polycarpus performs the following operation multiple times:  he chooses two elements of the array ai, aj (i ≠ j);  he simultaneously increases number ai by 1 and decreases number aj by 1, that is, executes ai = ai + 1 and aj = aj - 1. The given operation changes exactly two distinct array elements. Polycarpus can apply the described operation an infinite number of times. Now he wants to know what maximum number of equal array elements he can get if he performs an arbitrary number of such operation. Help Polycarpus.

The first line contains integer n (1 ≤ n ≤ 105) — the array size. The second line contains space-separated integers a1, a2, ..., an (|ai| ≤ 104) — the original array.

Print a single integer — the maximum number of equal array elements he can get if he performs an arbitrary number of the given operation.

(* Codeforces 246B *)

let gr () = Scanf.scanf " %d" (fun i -> i)
let rec readline n li = match n with
	| 0 -> li
	| _ -> readline (n-1) (gr () :: li);;

let rec sum l = match l with
	| [] -> 0
	| h :: t -> h + (sum t);;

let main () =
	let n = gr () in
	let ll = readline n [] in
	let sm = sum ll in
	let ret = if (sm mod n) = 0 then n else n -1 in
	(* print_string "sm: ";   *)
	(* print_int sm;          *)
	(* print_string " ret: "; *)
	print_int ret;;

main();;

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

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

let () =
  let n = read_int() in
  let a = Array.init n (fun i -> read_int()) in
  let s =  sum 0 (n-1) (fun i -> a.(i)) in
  let a = if s mod n = 0 then n else (n-1) in
    Printf.printf "%d\n" a

(* Codeforces 246B *)

let gr () = Scanf.scanf " %d" (fun i -> i)
let rec readline n li = match n with
	| 0 -> li
	| _ -> readline (n-1) (gr () :: li);;

let rec sum l = match l with
	| [] -> 0
	| h :: t -> h + (sum t);;

let main () =
	let n = gr () in
	let ll = readline n [] in
	let sm = sum ll in
	let ret = if (sm mod n) = 0 then n else n -1 in
	print_string "sm: ";
	print_int sm;
	print_string " ret: ";
	print_int ret;;

main();;

(* Codeforces 246B *)

let gr () = Scanf.scanf " %d" (fun i -> i)
let readline n li = match n with
	| 0 -> li
	| _ -> gr () :: li;;

let rec sum l = match l with
	| [] -> 0
	| h :: t -> h + (sum t);;

let main () =
	let n = gr () in
	let ll = readline n [] in
	let sm = sum ll in
	let ret = if (sm mod n) = 0 then n else n -1 in
	print_int ret;;

main();;


You are walking through a parkway near your house. The parkway has $$$n+1$$$ benches in a row numbered from $$$1$$$ to $$$n+1$$$ from left to right. The distance between the bench $$$i$$$ and $$$i+1$$$ is $$$a_i$$$ meters.Initially, you have $$$m$$$ units of energy. To walk $$$1$$$ meter of distance, you spend $$$1$$$ unit of your energy. You can't walk if you have no energy. Also, you can restore your energy by sitting on benches (and this is the only way to restore the energy). When you are sitting, you can restore any integer amount of energy you want (if you sit longer, you restore more energy). Note that the amount of your energy can exceed $$$m$$$.Your task is to find the minimum amount of energy you have to restore (by sitting on benches) to reach the bench $$$n+1$$$ from the bench $$$1$$$ (and end your walk).You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$; $$$1 \le m \le 10^4$$$). The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the distance between benches $$$i$$$ and $$$i+1$$$.

For each test case, print one integer — the minimum amount of energy you have to restore (by sitting on benches) to reach the bench $$$n+1$$$ from the bench $$$1$$$ (and end your walk) in the corresponding test case.

NoteIn the first test case of the example, you can walk to the bench $$$2$$$, spending $$$1$$$ unit of energy, then restore $$$2$$$ units of energy on the second bench, walk to the bench $$$3$$$, spending $$$2$$$ units of energy, restore $$$1$$$ unit of energy and go to the bench $$$4$$$.In the third test case of the example, you have enough energy to just go to the bench $$$6$$$ without sitting at all.

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

let rec get_energy_needed = function
| 0 -> 0
| n -> read_int () + get_energy_needed (n-1)
;;

let run_case = function
| () ->
     let n = read_int () in
     let m = read_int () in
     let r = get_energy_needed (n) in
     if (m>=r) then Printf.printf "%d\n" 0
     else Printf.printf "%d\n" (r-m)
;;

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

let t = read_int () in
iter_cases t;;


There is a grid, consisting of $$$2$$$ rows and $$$m$$$ columns. The rows are numbered from $$$1$$$ to $$$2$$$ from top to bottom. The columns are numbered from $$$1$$$ to $$$m$$$ from left to right.The robot starts in a cell $$$(1, 1)$$$. In one second, it can perform either of two actions:   move into a cell adjacent by a side: up, right, down or left;  remain in the same cell. The robot is not allowed to move outside the grid.Initially, all cells, except for the cell $$$(1, 1)$$$, are locked. Each cell $$$(i, j)$$$ contains a value $$$a_{i,j}$$$ — the moment that this cell gets unlocked. The robot can only move into a cell $$$(i, j)$$$ if at least $$$a_{i,j}$$$ seconds have passed before the move.The robot should visit all cells without entering any cell twice or more (cell $$$(1, 1)$$$ is considered entered at the start). It can finish in any cell.What is the fastest the robot can achieve that?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$m$$$ ($$$2 \le m \le 2 \cdot 10^5$$$) — the number of columns of the grid. The $$$i$$$-th of the next $$$2$$$ lines contains $$$m$$$ integers $$$a_{i,1}, a_{i,2}, \dots, a_{i,m}$$$ ($$$0 \le a_{i,j} \le 10^9$$$) — the moment of time each cell gets unlocked. $$$a_{1,1} = 0$$$. If $$$a_{i,j} = 0$$$, then cell $$$(i, j)$$$ is unlocked from the start. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a single integer — the minimum amount of seconds that the robot can take to visit all cells without entering any cell twice or more.

module A = Array
module L = List
module I = Int64

let pf = Printf.printf
let sf = Scanf.scanf
let read_int () = sf " %d" (fun x -> x)
let read_array read n = A.init n (fun _ -> read ())

let read_matrix read n m = A.init n (fun _ -> read_array read m)

let const x _y = x
let inf = 1000000000

let () =
  let t = read_int () in
  for _ = 1 to t do
    let m = read_int () in
    let a = read_matrix read_int 2 m in
    let min_s = A.init 2 (fun _ -> A.init (m + 1) (const 0)) in
    a.(0).(0) <- -1;
    for i = m - 1 downto 0 do
      let c = 2 * (m - i) in
      min_s.(0).(i) <- max (max a.(0).(i) (a.(1).(i) - c + 1)) (min_s.(0).(i + 1) - 1);
      min_s.(1).(i) <- max (max a.(1).(i) (a.(0).(i) - c + 1)) (min_s.(1).(i + 1) - 1);
    done;

    let relax_at arrived_j arrived_at_t =
      if (arrived_j mod 2 = 0) then max arrived_at_t min_s.(1).(arrived_j + 1) + 2 * (m - 1 - arrived_j)
      else max arrived_at_t min_s.(0).(arrived_j + 1) + 2 * (m - 1 - arrived_j)
    in
    let best_ans = ref (min_s.(0).(0) + 2 * m) in
    let cur_t = ref (a.(1).(0) + 1) in
    for i = 0 to m - 1 do
      best_ans := min !best_ans (relax_at i !cur_t);
      if (i mod 2 = 0 && i <> m - 1) then
        cur_t := max (max (!cur_t + 1) (a.(1).(i + 1) + 1) + 1) (a.(0).(i + 1) + 1)
      else if (i <> m - 1) then
        cur_t := max (max (!cur_t + 1) (a.(0).(i + 1) + 1) + 1) (a.(1).(i + 1) + 1)
    done;
    best_ans := min !best_ans !cur_t;
    pf "%d\n" !best_ans;
  done


A club plans to hold a party and will invite some of its $$$n$$$ members. The $$$n$$$ members are identified by the numbers $$$1, 2, \dots, n$$$. If member $$$i$$$ is not invited, the party will gain an unhappiness value of $$$a_i$$$.There are $$$m$$$ pairs of friends among the $$$n$$$ members. As per tradition, if both people from a friend pair are invited, they will share a cake at the party. The total number of cakes eaten will be equal to the number of pairs of friends such that both members have been invited.However, the club's oven can only cook two cakes at a time. So, the club demands that the total number of cakes eaten is an even number.What is the minimum possible total unhappiness value of the party, respecting the constraint that the total number of cakes eaten is even?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 10^5$$$, $$$0 \leq m \leq \min(10^5,\frac{n(n-1)}{2})$$$) — the number of club members and pairs of friends. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2, \dots,a_n$$$ ($$$0 \leq a_i \leq 10^4$$$) — the unhappiness value array. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \leq x,y \leq n$$$, $$$x \neq y$$$) indicating that $$$x$$$ and $$$y$$$ are friends. Each unordered pair $$$(x,y)$$$ appears at most once in each test case. It is guaranteed that both the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases do not exceed $$$10^5$$$.

For each test case, print a line containing a single integer – the minimum possible unhappiness value of a valid party.

NoteIn the first test case, all members can be invited. So the unhappiness value is $$$0$$$.In the second test case, the following options are possible:   invite $$$1$$$ and $$$2$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$3$$$);  invite $$$2$$$ and $$$3$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$2$$$);  invite only $$$1$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$4$$$);  invite only $$$2$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$5$$$);  invite only $$$3$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$3$$$);  invite nobody ($$$0$$$ cakes eaten, unhappiness value equal to $$$6$$$).  The minimum unhappiness value is achieved by inviting $$$2$$$ and $$$3$$$.In the third test case, inviting members $$$3,4,5$$$ generates a valid party with the minimum possible unhappiness value.

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.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,m) = read_pair() in
    let a = Array.init n read_int in
    let edge = Array.make m (0,0) in
    let degree = Array.make n 0 in
    for i = 0 to m-1 do
      let (x,y) = read_pair() in
      let (x,y) = (x-1,y-1) in
      edge.(i) <- (x,y);
      degree.(x) <- 1+degree.(x);
      degree.(y) <- 1+degree.(y);
    done;

    let infty = max_int in

    if m mod 2 = 0 then (
      printf "0\n";
    ) else (
      let option1 = minf 0 (n-1) (fun i ->
	if degree.(i) mod 2 = 1 then a.(i) else infty
      ) in

      let option2 = minf 0 (m-1) (fun e ->
	let (x,y) = edge.(e) in
	if degree.(x) mod 2 = 0 && degree.(y) mod 2 = 0 then a.(x) + a.(y) else infty
      ) in
      let answer = min option1 option2 in
      printf "%d\n" answer
    )
  done


You are given an integer array $$$a_1, a_2, \ldots, a_n$$$.The array $$$b$$$ is called to be a subsequence of $$$a$$$ if it is possible to remove some elements from $$$a$$$ to get $$$b$$$.Array $$$b_1, b_2, \ldots, b_k$$$ is called to be good if it is not empty and for every $$$i$$$ ($$$1 \le i \le k$$$) $$$b_i$$$ is divisible by $$$i$$$.Find the number of good subsequences in $$$a$$$ modulo $$$10^9 + 7$$$. Two subsequences are considered different if index sets of numbers included in them are different. That is, the values of the elements do not matter in the comparison of subsequences. In particular, the array $$$a$$$ has exactly $$$2^n - 1$$$ different subsequences (excluding an empty subsequence).

The first line contains an integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the length of the array $$$a$$$. The next line contains integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^6$$$).

Print exactly one integer — the number of good subsequences taken modulo $$$10^9 + 7$$$.

(* equivalent to 1061C's solution with n,m are maximized *)
let divisors n =
  let rec f0 i a =
    if i*i > n then a
    else if i*i = n && n mod i = 0 then i::a
    else if n mod i = 0 then f0 (i+1) (i::(n/i)::a)
    else f0 (i+1) a
  in f0 1 []
let (++) u v = Int64.rem (Int64.add u v) 1000000007L
external id : 'a -> 'a = "%identity"
let n = Scanf.scanf " %d" @@ id
let a = Array.init n (fun _ -> Scanf.scanf " %d" @@ id)
let dp = Array.make 1000007 0L
let () =
  Array.iter (fun v ->
    divisors v
    |> List.sort (fun u v -> compare v u)
    |> List.iter (fun d ->
      if d=1 then dp.(1) <- dp.(1) ++ 1L
      else dp.(d) <- dp.(d) ++ dp.(d-1)
    )
  ) a;
  Printf.printf "%Ld\n" @@ Array.fold_left (++) 0L dp

open Printf open Scanf
module Lib = struct
  let i32,i64,ist = Int64.(to_int,of_int,to_string)
  let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)
  let labs = Int64.abs
  let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)
  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 (%=) r v = r := !r % v
  let max_i64,min_i64 = Int64.(max_int,min_int)
  (* math *)
  let ceildiv p q = (p+q-1L) / q
  let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
  let lcm m n = m / gcd m n * n
  module I64_infix = struct
    let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =
      let open Int64 in
      (logand),(logor),(logxor),lognot,
      (fun u v -> shift_left u (i32 v)),
      (fun u v -> shift_right u (i32 v)),
      (fun u v -> shift_right_logical u (i32 v))
  end
  (* input *)
  let input_i64_array n = Array.init (i32 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 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)
  (* utils *)
  external id : 'a -> 'a = "%identity"
  let ( *< ) f g x = f (g x)
  let ( *> ) f g x = g (f x)
  let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)
  let alen a = i64 @@ Array.length a
  let llen l = i64 @@  List.length l
  let string_of_list ?(separator=" ") f ls = ls |> List.map f |> String.concat separator
  let string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
  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 fail _ = failwith "fail"
  let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]
  let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev
  let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten
  let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a
  let binary_search ng ok f = let d = if ng < ok then 1L else -1L in
    let rec f0 ng ok =
      if labs (ok - ng) <= 1L then ok
      else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
    in f0 (ng-1L*d) (ok+1L*d)
  let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)
  let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >  v)
  let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)
  let rec fix f x = f (fix f) x
  let fix_memo ?(size=10000) f x =
    let tb = Hashtbl.create ~random:true size in
    let rec f0 x =
      try Hashtbl.find tb x with
      | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)
    in f0 x
  (* imperative *)
  let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done
  let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done
  let repm f t ?(stride=1L) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m
  let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done
  let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done
  let repim f t ?(stride=1) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m
  let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v
  let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v
  let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v
  let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v
  (* output *)
  let print_list_mle f ls = string_of_list f ls |> print_endline
  let print_array_mle f a = string_of_array f a |> print_endline
  let print_list f ls = ls |> List.iter (fun v -> printf "%s " @@ f v); print_newline ()
  let print_array f a = a |> Array.iter (fun v -> printf "%s " @@ f v); print_newline ()
  (* debug *)
  let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)
  let dump_i64_list ls = print_list ist ls
  let dump_i64_array a = print_array ist a
end open Lib open Array
(* let divisors v =
  let rec f0 i a =
    if i*i > v then a
    else if i*i = v && v mod i = 0L then i::a
    else if v mod i = 0L then f0 (i+1L) (i::(v/i)::a)
    else f0 (i+1L) a in f0 1L [] *)
let divisors n =
  let rec f0 i a =
    if i*$i > n then a
    else if i*$i = n && n %$ i = 0 then i::a
    else if n %$ i = 0 then f0 (i+$1) (i::(n/$i)::a)
    else f0 (i+$1) a
  in f0 1 []
let n = get_i64 0
let a = input_i64_array n
let dp = make 1000007 0L
let (++) u v = (u+v) mod 1000000007L
let () =
  iter (fun v ->
    i32 v
    |> divisors
    |> List.sort (fun u v -> compare v u)
    |> List.iter (fun d ->
      if d=1 then dp.(1) <- dp.(1) ++ 1L
      else dp.(d) <- dp.(d) ++ dp.(d-$1)
    )
  ) a;
  printf "%Ld\n" @@ fold_left (++) 0L dp


There is a house with $$$n$$$ flats situated on the main street of Berlatov. Vova is watching this house every night. The house can be represented as an array of $$$n$$$ integer numbers $$$a_1, a_2, \dots, a_n$$$, where $$$a_i = 1$$$ if in the $$$i$$$-th flat the light is on and $$$a_i = 0$$$ otherwise.Vova thinks that people in the $$$i$$$-th flats are disturbed and cannot sleep if and only if $$$1 < i < n$$$ and $$$a_{i - 1} = a_{i + 1} = 1$$$ and $$$a_i = 0$$$.Vova is concerned by the following question: what is the minimum number $$$k$$$ such that if people from exactly $$$k$$$ pairwise distinct flats will turn off the lights then nobody will be disturbed? Your task is to find this number $$$k$$$.

The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 100$$$) — the number of flats in the house. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$a_i \in \{0, 1\}$$$), where $$$a_i$$$ is the state of light in the $$$i$$$-th flat.

Print only one integer — the minimum number $$$k$$$ such that if people from exactly $$$k$$$ pairwise distinct flats will turn off the light then nobody will be disturbed.

NoteIn the first example people from flats $$$2$$$ and $$$7$$$ or $$$4$$$ and $$$7$$$ can turn off the light and nobody will be disturbed. It can be shown that there is no better answer in this example.There are no disturbed people in second and third examples.

(* Problem 2 of round 521*)
open Scanf;;
open String;;
open Num;;

(*These are some utility functions*)
module U = struct
  let mprint z =
    print_endline (Num.string_of_num z);;

  let read_one format =
    let n = Scanf.scanf format (fun x -> x) in
    n;;

  let read_one_number () =
    let n = read_one "%d " in
    n

  let read_array n a =
    for i = 0 to n - 1 do
      let n = read_one_number () in
      a.(i) <- n
    done

end

(*The solutions*)

let n = U.read_one_number ()
let a = Array.make n 0
let () = U.read_array n a

(*test
let () =
  Array.iter (fun x-> print_int x; print_endline "" ) a
*)
let () =
  let t = ref 0 in
  for i = 1 to n-2 do
    if a.(i)==0 then
      begin
        if a.(i-1)==1 && a.(i+1)==1 then
          begin
            a.(i+1) <- 0;
            incr t
          end
      end
  done;
  print_int !t; print_endline ""

open Printf open Scanf
module Lib = struct
  let i32,i64,ist = Int64.(to_int,of_int,to_string)
  let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)
  let labs = Int64.abs
  let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)
  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 (%=) r v = r := !r % v
  let max_i64,min_i64 = Int64.(max_int,min_int)
  (* math *)
  let ceildiv p q = (p+q-1L) / q
  let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
  let lcm m n = m / gcd m n * n
  module I64_infix = struct
    let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =
      let open Int64 in
      (logand),(logor),(logxor),lognot,
      (fun u v -> shift_left u (i32 v)),
      (fun u v -> shift_right u (i32 v)),
      (fun u v -> shift_right_logical u (i32 v))
  end
  (* input *)
  let input_i64_array n = Array.init (i32 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 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)
  (* utils *)
  external id : 'a -> 'a = "%identity"
  let ( *< ) f g x = f (g x)
  let ( *> ) f g x = g (f x)
  let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)
  let alen a = i64 @@ Array.length a
  let llen l = i64 @@  List.length l
  let string_of_list ?(separator=" ") f ls = ls |> List.map f |> String.concat separator
  let string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
  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 fail _ = failwith "fail"
  let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]
  let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev
  let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten
  let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a
  let binary_search ng ok f = let d = if ng < ok then 1L else -1L in
    let rec f0 ng ok =
      if labs (ok - ng) <= 1L then ok
      else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
    in f0 (ng-1L*d) (ok+1L*d)
  let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)
  let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >  v)
  let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)
  let rec fix f x = f (fix f) x
  let fix_memo ?(size=10000) f x =
    let tb = Hashtbl.create ~random:true size in
    let rec f0 x =
      try Hashtbl.find tb x with
      | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)
    in f0 x
  (* imperative *)
  let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done
  let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done
  let repm f t ?(stride=1L) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m
  let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done
  let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done
  let repim f t ?(stride=1) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m
  let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v
  let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v
  let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v
  let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v
  (* output *)
  let print_list_mle f ls = string_of_list f ls |> print_endline
  let print_array_mle f a = string_of_array f a |> print_endline
  let print_list f ls = ls |> List.iter (fun v -> printf "%s " @@ f v); print_newline ()
  let print_array f a = a |> Array.iter (fun v -> printf "%s " @@ f v); print_newline ()
  (* debug *)
  let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)
  let dump_i64_list ls = print_list ist ls
  let dump_i64_array a = print_array ist a
end open Lib open Array

let () =
  let n = get_i64 0 in
  let a = input_i64_array n in
  let r = ref 0L in
  rep 1L (n-2L) (fun i ->
    let i = i32 i in
    if a.(i-$1)=1L && a.(i)=0L && a.(i+$1)=1L then (
      r += 1L;
      a.(i+$1) <- 0L;
    )
  );
  printf "%Ld\n" !r

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

let n = scan_int ();;
let a = Array.make n 0;;
for i = 0 to (n - 1) do
  a.(i) <- (scan_int ());
done

let k = ref 0;;
for i = 1 to (n - 2) do
  if a.(i - 1) = 1 && a.(i) = 0 && a.(i + 1) = 1 then
  begin
    a.(i + 1) <- 0;
    incr k;
  end;
done;;
print_int !k;;
print_endline "";;


One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (x1, y1), (x2, y2), ..., (xn, yn). Let's define neighbors for some fixed point from the given set (x, y):   point (x', y') is (x, y)'s right neighbor, if x' > x and y' = y  point (x', y') is (x, y)'s left neighbor, if x' < x and y' = y  point (x', y') is (x, y)'s lower neighbor, if x' = x and y' < y  point (x', y') is (x, y)'s upper neighbor, if x' = x and y' > y We'll consider point (x, y) from the given set supercentral, if it has at least one upper, at least one lower, at least one left and at least one right neighbor among this set's points.Vasya marked quite many points on the paper. Analyzing the picture manually is rather a challenge, so Vasya asked you to help him. Your task is to find the number of supercentral points in the given set.

The first input line contains the only integer n (1 ≤ n ≤ 200) — the number of points in the given set. Next n lines contain the coordinates of the points written as "x y" (without the quotes) (|x|, |y| ≤ 1000), all coordinates are integers. The numbers in the line are separated by exactly one space. It is guaranteed that all points are different.

Print the only number — the number of supercentral points of the given set.

NoteIn the first sample the supercentral points are only points (1, 1) and (1, 2).In the second sample there is one supercental point — point (0, 0).

let _ =
    let main () =
        let n = read_int () in
        let arr = Array.init n (fun i -> Scanf.sscanf (read_line ()) "%d %d" (fun x y -> x, y)) in
        let bits = Array.create n 0 in
        Array.iteri (fun i (x, y) ->
            Array.iteri (fun j (a, b) ->
                if a > x && y = b then bits.(j) <- bits.(j) lor 1;
                if a < x && y = b then bits.(j) <- bits.(j) lor 2;
                if a = x && y < b then bits.(j) <- bits.(j) lor 4;
                if a = x && y > b then bits.(j) <- bits.(j) lor 8;
            ) arr
        ) arr;
        Printf.printf "%d\n" (Array.fold_left (fun acc k -> acc + k / 15) 0 bits)
    in
    main ()

open Array;;
(* Common part*)
let (|>) x f = f x
let identity = fun x -> x

let flip f y x = f x y

let readInStr _ = Scanf.scanf "%d " identity
let readIntLn _ = Scanf.scanf "%d\n" identity
(*      Programme       *)
let f x y = match x, y with (x,y,_), (x1,y1,_) ->  if x=x1 then y-y1 else x-x1
let f1 x y = match x, y with (x,y,_), (x1,y1,_) -> if y=y1 then x-x1 else y-y1

let y arr n i = if i>=n then function _-> ()
  else function (x,y,z) ->
    match arr.(i+1)
    with (x1,y1,z1) when x1=x -> arr.(i)<-(x,y,z+1); arr.(i+1) <- (x1,y1,z1+1)
    | _ -> ()

let y1 arr n i = if i>=n then function _-> ()
  else function (x,y,z) ->
    match arr.(i+1)
    with (x1,y1,z1) when y=y1 -> arr.(i)<-(x,y,z+1); arr.(i+1) <- (x1,y1,z1+1)
    | _ -> ()

let main () =
  let n = readIntLn () in
  let arr = init n (function _ -> let a= readInStr () in (a, readIntLn (), 0) ) in
  fast_sort f arr;
   iteri (n-1|>y arr) arr;
  fast_sort f1 arr;
   iteri (n-1|>y1 arr) arr;
   fold_left (fun acc-> function (_,_,z) -> if z = 4 then (acc+1) else acc ) 0 arr |> print_int;
  ;;
main()

let is_right_neighbor a b = (fst a) > (fst b) && (snd a) = (snd b)
let is_left_neighbor a b = (fst a) < (fst b) && (snd a) = (snd b)
let is_lower_neighbor a b = (fst a) = (fst b) && (snd a) < (snd b)
let is_upper_neighbor a b = (fst a) = (fst b) && (snd a) > (snd b)

let is_supercentral_point p points =
  List.exists (is_right_neighbor p) points &&
  List.exists (is_left_neighbor p) points &&
  List.exists (is_lower_neighbor p) points &&
  List.exists (is_upper_neighbor p) points

let solve points =
  let count accum p =
    if is_supercentral_point p points then accum+1
    else accum
  in
  List.fold_left count 0 points

let rec read_n_tuples n lst =
  if n = 0 then lst
  else read_n_tuples (n-1) ((Scanf.scanf " %d %d" (fun x y -> (x, y))) :: lst)

let _ =
  let n = Scanf.scanf " %d" (fun x -> x) in
  let points = read_n_tuples n [] in
  Printf.printf "%d\n" (solve points)

open Array;;
(* Common part*)
let (|>) x f = f x
let identity = fun x -> x

let flip f y x = f x y

let readInStr _ = Scanf.scanf "%d " identity
let readIntLn _ = Scanf.scanf "%d\n" identity
(*      Programme       *)
let f x y = match x, y with (x,y,z), (x1,y1,z1) ->  if x=x1 then y-y1 else x-x1

let y arr n i = if i>=n then function _-> ()
  else function (x,y,z) ->
    match arr.(i+1)
    with (x1,y1,z1) when x1=x -> arr.(i)<-(x,y,z+1); arr.(i+1) <- (x1,y1,z1+1)
    | _ -> ()

let main () =
  let n = readIntLn () in
  let arr = init n (function _ -> let a= readInStr () in (a, readIntLn (), 0) ) in
  fast_sort f arr;
   iteri (n-1|>y arr) arr;
  fast_sort (flip f) arr;
   iteri (n-1|>y arr) arr;
   fold_left (fun acc-> function (_,_,z) -> if z = 4 then (acc+1) else acc ) 0 arr |> print_int;
  ;;
main()


You are given a sequence of positive integers a1, a2, ..., an. Find all such indices i, that the i-th element equals the arithmetic mean of all other elements (that is all elements except for this one).

The first line contains the integer n (2 ≤ n ≤ 2·105). The second line contains elements of the sequence a1, a2, ..., an (1 ≤ ai ≤ 1000). All the elements are positive integers.

Print on the first line the number of the sought indices. Print on the second line the sought indices in the increasing order. All indices are integers from 1 to n. If the sought elements do not exist, then the first output line should contain number 0. In this case you may either not print the second line or print an empty line.

open Str;;
open Array;;
open String;;

let split sep =
	let re = Str.regexp sep in
	Str.split re
;;

let rec range a b =
	if a = b then [] else a :: range (a+1) b
;;

let (!!) ls n =
	List.nth ls n
;;

let main =
	let len = read_int()
	and nums = Array.map float_of_string (Array.of_list (split " " (read_line()))) in
	let sum = Array.fold_left (+.) 0. nums in
	let ln = ref 0 in
	let indexes = Array.mapi (fun i x ->
		if (sum -. x) /. (float_of_int (len-1)) = x then begin
			incr ln;
			i + 1
		end else
			0
	) nums in
	let _ = print_int (!ln) in
	let _ = print_string "\n" in
	Array.iter (fun i ->
		if i > 0 then
			let _ = print_int i in
			print_string " "
	) indexes
;;

let rec input_seq n lst =
  if n <= 1 then (Scanf.scanf "%d\n" (fun x -> x)) :: lst
  else input_seq (n - 1) ((Scanf.scanf "%d " (fun x -> x)) :: lst)

let input_seq n = List.rev (input_seq n [])

let solve n =
  let seq = input_seq n in
  let sum = List.fold_left (+) 0 seq in
  let rec loop lst accm cnt = match lst with
    | [] -> accm
    | first :: rest
	-> if first * n == sum then loop rest (cnt::accm) (cnt+1)
	  else loop rest accm (cnt+1)
  in
  loop seq [] 1

let rec print_int_list = function
  | [] -> Printf.printf "\n"
  | lst :: [] -> Printf.printf "%d\n" lst
  | first :: rest ->
    begin
      Printf.printf "%d " first;
      print_int_list rest
    end

let _ =
  let ans = Scanf.scanf "%d\n" solve in
  Printf.printf "%d\n" (List.length ans);
  if List.length ans != 0 then print_int_list (List.rev ans)

open Str;;
open Array;;
open String;;

let split sep =
	let re = Str.regexp sep in
	Str.split re
;;

let rec range a b =
	if a = b then [] else a :: range (a+1) b
;;

let (!!) ls n =
	List.nth ls n
;;

let main =
	let len = read_int()
	and nums = Array.map float_of_string (Array.of_list (split " " (read_line()))) in
	let sum = Array.fold_left (+.) 0. nums in
	let indexes = List.filter (fun i ->
		(sum -. nums.(i)) /. (float_of_int (len-1)) = nums.(i)
	) (range 0 len) in
	let _ = print_int (List.length indexes) in
	let _ = print_string "\n" in
	print_string (String.concat " " (List.map (fun x ->string_of_int (x+1)) indexes))
;;

open Str;;
open List;;

let split sep =
	let re = Str.regexp sep in
	Str.split re
;;

let rec range a b =
	if a = b then [] else a :: range (a+1) b
;;

let (!!) ls n =
	List.nth ls n
;;

let main =
	let len = read_int()
	and nums = List.map float_of_string (split " " (read_line())) in
	let sum = List.fold_left (+.) 0. nums in
	let avg = sum /. (float_of_int len) in
	let indexes = List.filter (fun i ->
		(sum -. (List.nth nums i)) /. (float_of_int (len-1)) = List.nth nums i
	) (range 0 len) in
	let _ = print_int (List.length indexes) in
	let _ = print_string "\n" in
	List.iter (fun i -> print_int (i+1); print_string " ") indexes
;;

open Str;;
open List;;

let split sep =
	let re = Str.regexp sep in
	Str.split re
;;

let rec range a b =
	if a = b then [] else a :: range (a+1) b
;;

let (!!) ls n =
	List.nth ls n
;;

let main =
	let len = read_int()
	and nums = List.map int_of_string (split " " (read_line())) in
	let sum = List.fold_left (+) 0 nums in
	let avg = sum / len in
	let indexes = List.filter (fun i ->
		avg = List.nth nums i
	) (range 0 len) in
	let _ = print_int (List.length indexes) in
	let _ = print_string "\n" in
	List.iter (fun i -> print_int (i+1); print_string " ") indexes
;;

open Str;;
open List;;
open String;;

let split sep =
	let re = Str.regexp sep in
	Str.split re
;;

let rec range a b =
	if a = b then [] else a :: range (a+1) b
;;

let (!!) ls n =
	List.nth ls n
;;

let main =
	let len = read_int()
	and nums = List.map float_of_string (split " " (read_line())) in
	let sum = List.fold_left (+.) 0. nums in
	let avg = sum /. (float_of_int len) in
	let indexes = List.filter (fun i ->
		(sum -. (List.nth nums i)) /. (float_of_int (len-1)) = List.nth nums i
	) (range 0 len) in
	let _ = print_int (List.length indexes) in
	let _ = print_string "\n" in
	print_string (String.concat " " (List.map (fun x ->string_of_int (x+1)) indexes))
;;

let rec input_seq n lst =
  if n <= 1 then (Scanf.scanf "%d\n" (fun x -> x)) :: lst
  else input_seq (n - 1) ((Scanf.scanf "%d " (fun x -> x)) :: lst)

let input_seq n = List.rev (input_seq n [])

let solve n =
  let seq = input_seq n in
  let sum = List.fold_left (+) 0 seq in
  let rec loop lst accm cnt = match lst with
    | [] -> accm
    | first :: rest
	-> if (sum-first) / (n - 1) == first then loop rest (cnt::accm) (cnt+1)
	  else loop rest accm (cnt+1)
  in
  loop seq [] 1

let rec print_int_list = function
  | [] -> Printf.printf "\n"
  | lst :: [] -> Printf.printf "%d\n" lst
  | first :: rest ->
    begin
      Printf.printf "%d " first;
      print_int_list rest
    end

let _ =
  let ans = Scanf.scanf "%d\n" solve in
  Printf.printf "%d\n" (List.length ans);
  if List.length ans != 0 then print_int_list (List.rev ans)

let rec input_seq n lst =
  if n <= 1 then (Scanf.scanf "%d\n" (fun x -> x)) :: lst
  else input_seq (n - 1) ((Scanf.scanf "%d " (fun x -> x)) :: lst)

let input_seq n = List.rev (input_seq n [])

let solve n =
  let seq = input_seq n in
  let sum = List.fold_left (+) 0 seq in
  let rec loop lst accm cnt = match lst with
    | [] -> accm
    | first :: rest
	-> if (sum-first) / (n - 1) == first then loop rest (cnt::accm) (cnt+1)
	  else loop rest accm (cnt+1)
  in
  loop seq [] 1

let rec print_int_list = function
  | [] -> Printf.printf "\n"
  | lst :: [] -> Printf.printf "%d\n" lst
  | first :: rest ->
    begin
      Printf.printf "%d " first;
      print_int_list rest
    end

let _ =
  let ans = Scanf.scanf "%d\n" solve in
  Printf.printf "%d\n" (List.length ans);
  print_int_list (List.rev ans)


Captain Marmot wants to prepare a huge and important battle against his enemy, Captain Snake. For this battle he has n regiments, each consisting of 4 moles.Initially, each mole i (1 ≤ i ≤ 4n) is placed at some position (xi, yi) in the Cartesian plane. Captain Marmot wants to move some moles to make the regiments compact, if it's possible.Each mole i has a home placed at the position (ai, bi). Moving this mole one time means rotating his position point (xi, yi) 90 degrees counter-clockwise around it's home point (ai, bi).A regiment is compact only if the position points of the 4 moles form a square with non-zero area.Help Captain Marmot to find out for each regiment the minimal number of moves required to make that regiment compact, if it's possible.

The first line contains one integer n (1 ≤ n ≤ 100), the number of regiments. The next 4n lines contain 4 integers xi, yi, ai, bi ( - 104 ≤ xi, yi, ai, bi ≤ 104).

Print n lines to the standard output. If the regiment i can be made compact, the i-th line should contain one integer, the minimal number of required moves. Otherwise, on the i-th line print "-1" (without quotes).

NoteIn the first regiment we can move once the second or the third mole.We can't make the second regiment compact.In the third regiment, from the last 3 moles we can move once one and twice another one.In the fourth regiment, we can move twice the first mole and once the third mole.

open Printf
open Scanf

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

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

let (++) (a,b) (c,d) = (a+c, b+d)
let (--) (a,b) (c,d) = (a-c, b-d)

let rotate (x,y) (x0,y0) =  (* rotate (x,y) counterclock around (x0,y0) *)
  let (x,y) = (x,y) -- (x0,y0) in
  let (x,y) = (-y,x) in
  (x,y) ++ (x0,y0)

let () =
  let n = read_int () in

  let issquare p = (* p is an array of 4 points.  Is it a square? *)
    let rec inp a i = (i<4) && (p.(i) = a || inp a (i+1)) in

    let (cx,cy) = p.(0) ++ p.(1) ++ p.(2) ++ p.(3) in
    let c = (cx/4, cy/4) in
    p.(0) <> p.(1) && forall 0 3 (fun i -> inp (rotate p.(i) c) 0)
  in

  let solve p h =
    let found = ref 1000 in
    let blah i = p.(i) <- rotate p.(i) h.(i) in
    for i1 = 0 to 3 do
      for i2 = 0 to 3 do
	for i3 = 0 to 3 do
	  for i4 = 0 to 3 do
	    if issquare p then found := min !found (i1+i2+i3+i4);
	    blah 3
	  done;
	  blah 2
	done;
	blah 1
      done;
      blah 0
    done;
    if !found = 1000 then -1 else !found
  in

  for i=0 to n-1 do
    let p = Array.make 4 (0,0) in
    let h = Array.make 4 (0,0) in
    for j=0 to 3 do
      p.(j) <- read_pair_double ();
      h.(j) <- read_pair_double ();
    done;

    printf "%d\n" (solve p h)
  done;


There always is something to choose from! And now, instead of "Noughts and Crosses", Inna choose a very unusual upgrade of this game. The rules of the game are given below:There is one person playing the game. Before the beginning of the game he puts 12 cards in a row on the table. Each card contains a character: "X" or "O". Then the player chooses two positive integers a and b (a·b = 12), after that he makes a table of size a × b from the cards he put on the table as follows: the first b cards form the first row of the table, the second b cards form the second row of the table and so on, the last b cards form the last (number a) row of the table. The player wins if some column of the table contain characters "X" on all cards. Otherwise, the player loses.Inna has already put 12 cards on the table in a row. But unfortunately, she doesn't know what numbers a and b to choose. Help her win the game: print to her all the possible ways of numbers a, b that she can choose and win.

The first line of the input contains integer t (1 ≤ t ≤ 100). This value shows the number of sets of test data in the input. Next follows the description of each of the t tests on a separate line. The description of each test is a string consisting of 12 characters, each character is either "X", or "O". The i-th character of the string shows the character that is written on the i-th card from the start.

For each test, print the answer to the test on a single line. The first number in the line must represent the number of distinct ways to choose the pair a, b. Next, print on this line the pairs in the format axb. Print the pairs in the order of increasing first parameter (a). Separate the pairs in the line by whitespaces.

4
OXXXOXOOXOOX
OXOXOXOXOXOX
XXXXXXXXXXXX
OOOOOOOOOOOO

let n=read_int();;

let test a b s=
   let m=Array.make_matrix (a+1) (b+1) ' ' in
   for i=1 to a do
      for j=1 to b do
         m.(i).(j)<-s.[(i-1)*b+j-1]
      done
   done;
   let boo=ref false in
   for i=1 to b do
      let aux=ref true in
      for j=1 to a do
         if m.(j).(i)<>'X' then aux:=false
      done;
      boo:= !boo|| !aux
   done;
!boo;;

let rec nb=function
|[]->0
|(_,b)::t->if b then 1+nb t else nb t;;

let rec print_list=function
|[]->()
|(s,b)::t->if b then print_string s;print_list t;;

let tab=Array.make (n+1) " ";;

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

for i=1 to n do
   let s=tab.(i) in
   let r a b=(" "^string_of_int(a)^"x"^string_of_int(b),test a b s) in
   let sol=[r 1 12;r 2 6;r 3 4;r 4 3;r 6 2;r 12 1] in
   print_int (nb sol);
   print_list sol;
   print_newline()
done;;