Scanf.scanf "%d %d" (fun n q ->
    let nei = Array.make n [] in
    for i = 1 to n - 1 do
        Scanf.scanf " %d %d" (fun a b ->
            let a = a - 1 in
            let b = b - 1 in
            nei.(a) <- b :: nei.(a);
            nei.(b) <- a :: nei.(b);
        )
    done;
    let counter = Array.make n 0 in
    for i = 1 to q do
        Scanf.scanf " %d %d" (fun p x ->
            let p = p - 1 in
            counter.(p) <- counter.(p) + x
        )
    done;

    let parent = Array.make n (-1) in
    let rec parse_parent par cur =
        parent.(cur) <- par;
        List.iter (fun v -> if v <> par then parse_parent cur v) nei.(cur)
    in
    parse_parent (-1) 0;
    let score = Array.make n (-1) in
    score.(0) <- counter.(0);
    let rec calc p =
        if score.(p) >= 0 then score.(p) else
            let s = calc parent.(p) + counter.(p) in
            let () = score.(p) <- s in
            s
    in
    for i = 0 to n - 1 do
        Printf.printf "%d "@@ calc i
    done;
    print_newline ()
)

Score : 400 points

Problem Statement

Given is a rooted tree with N vertices numbered 1 to N.
The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i.

Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0.

Now, the following Q operations will be performed:

Operation j (1 \leq j \leq Q): Increment by x_j the counter on every vertex contained in the subtree rooted at Vertex p_j.

Find the value of the counter on each vertex after all operations.

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq Q \leq 2 \times 10^5

1 \leq a_i < b_i \leq N

1 \leq p_j \leq N

1 \leq x_j \leq 10^4

The given graph is a tree.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
a_1 b_1
:
a_{N-1} b_{N-1}
p_1 x_1
:
p_Q x_Q

Output

Print the values of the counters on Vertex 1, 2, \ldots, N after all operations, in this order, with spaces in between.

Sample Input 1

4 3
1 2
2 3
2 4
2 10
1 100
3 1

Sample Output 1

100 110 111 110

The tree in this input is as follows:

Each operation changes the values of the counters on the vertices as follows:

Operation 1: Increment by 10 the counter on every vertex contained in the subtree rooted at Vertex 2, that is, Vertex 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 0, 10, 10, 10, respectively.

Operation 2: Increment by 100 the counter on every vertex contained in the subtree rooted at Vertex 1, that is, Vertex 1, 2, 3, 4. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 110, 110, respectively.

Operation 3: Increment by 1 the counter on every vertex contained in the subtree rooted at Vertex 3, that is, Vertex 3. The values of the counters on Vertex 1, 2, 3, 4 are now 100, 110, 111, 110, respectively.

Sample Input 2

6 2
1 2
1 3
2 4
3 6
2 5
1 10
1 10

Sample Output 2

20 20 20 20 20 20


let n, q = Scanf.sscanf (read_line ()) "%d %d" (fun a b -> a, b)

let g = Array.init n (fun _ -> [])
let () =
  Array.init (n - 1) (fun _ -> Scanf.sscanf (read_line ()) "%d %d" (fun a b -> a-1, b-1))
  |> Array.iter (fun (a, b) ->
      g.(a) <- b :: g.(a);
      g.(b) <- a :: g.(b)
  )

let sum = Array.init n (fun _ -> 0)
let () =
  Array.init q (fun _ -> Scanf.sscanf (read_line ()) "%d %d" (fun q x -> q - 1, x))
  |> Array.iter (fun (q, x) -> sum.(q) <- sum.(q) + x)

let ans = Array.init n (fun _ -> 0)

let rec cumsum now par acc =
  let acc = acc + sum.(now) in (
    ans.(now) <- acc;
    List.iter (fun child -> if child = par then () else cumsum child now acc) g.(now)
  )

let () = (
  cumsum 0 0 0;
  for i = 0 to n - 1 do
    Printf.printf "%d " ans.(i)
  done
)

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


open Batteries
module EnumL = Enum.Labels
module ListL = List.Labels
module ArrayL = Array.Labels

let dbg0 x = Printf.eprintf "[debug]%s\n" @@ dump x
let dbg1 x = dbg0 x; x

let id = identity

let (++) n m = List.range n `To m
let (++-) n m = if n >= m then List.range n `Downto m else []
let (++^) n m = if n < m then List.range n `To (pred m) else []

let scan fmt = Scanf.sscanf (read_line ()) fmt

let scan_lines n fmt f =
  if n = 0 then []
  else List.map (fun _ -> scan fmt f) (1 ++ n)

let scan_list ?sep cnv =
  let line = read_line () in
  (match sep with
   | None -> List.map String.of_char @@ String.to_list line
   | Some sep -> String.split_on_char sep line)
  |> List.map cnv

let scan_array ?sep cnv = Array.of_list @@ scan_list ?sep cnv

let scan_matrix n m e ?sep conv =
  let arr = Array.make_matrix n m e in
  ListL.iter (0 ++^ n)
    ~f:(fun i -> arr.(i) <- Array.of_list @@ scan_list ?sep conv);
  arr

let atoi c = Char.code c - Char.code '0'

let rec powerset = function
  | [] -> [[]]
  | hd::tl ->
    let pws =  powerset tl in
    pws @ ListL.map pws ~f:(fun pw -> hd::pw)

let permutations l =
  let rec interleave x = function
    | [] -> [[x]]
    | (hd::tl) as l ->
      (x::l) :: (interleave x tl |> ListL.map ~f:(fun l -> hd::l)) in
  let rec aux = function
    | [] -> [[]]
    | a::rest ->
      aux rest |> ListL.map ~f:(interleave a) |> List.concat in
  aux l

let intersection l =
  EnumL.filter ~f:(fun x -> EnumL.exists ~f:((=) x) @@ Enum.clone l)

let zip l m =
  let n = min (List.length l) (List.length m) in
  List.combine (List.take n l) (List.take n m)

let lower_bound n f =
  let rec aux l u =
    if u - l > 1 then
      let m = (l + u) / 2 in
      if f m then aux l m
      else aux m u
    else u in aux (-1) n

let between n x m = n <= x && x < m

let (n,q) = scan "%d %d" Tuple2.make
let ls = scan_lines (pred n) "%d %d" Tuple2.make
let ml = scan_lines q "%d %d" Tuple2.make
let arr = Array.make (succ n) 0

let rec dfs tree visited n v =
  arr.(n) <- arr.(n) + v;
  visited.(n) <- true;
  ListL.iter tree.(n) ~f:(fun m ->
      if not visited.(m) then
        dfs tree visited m arr.(n))

let () =
  ListL.iter ml ~f:(fun (p,x) ->
      arr.(p) <- arr.(p) + x);
  let tree = Array.make (succ n) [] in
  ListL.iter ls ~f:(fun (a,b) ->
      tree.(a) <- b::tree.(a);
      tree.(b) <- a::tree.(b));
  let visited = Array.make (succ n)false in
  visited.(1) <- true;
  dfs tree visited 1 0;
  ListL.iter (1++n) ~f:(fun i ->
      if i <> 1 then Printf.printf " ";
      Printf.printf "%d" arr.(i));
  Printf.printf "\n"


open Batteries
module EnumL = Enum.Labels
module ListL = List.Labels
module ArrayL = Array.Labels

let dbg0 x = Printf.eprintf "[debug]%s\n" @@ dump x
let dbg1 x = dbg0 x; x

let id = identity

let (++) n m = List.range n `To m
let (++^) n m = if n < m then List.range n `To (pred m) else []

let scan fmt = Scanf.sscanf (read_line ()) fmt

let scan_lines n fmt f =
  if n = 0 then Enum.empty ()
  else
    List.map (fun _ -> scan fmt f) (List.range 1 `To n)
    |> List.enum

let scan_list cnv =
  String.split_on_char ' ' @@ read_line ()
  |> List.map cnv

let scan_array cnv = Array.of_list @@ scan_list cnv

let scan_matrix n m e conv =
  let arr = Array.make_matrix n m e in
  ListL.iter (List.range 0 `To (pred n))
    ~f:(fun i -> arr.(i) <- Array.of_list @@ scan_list conv);
  arr

let rec powerset e =
  match Enum.get e with
  | None -> Enum.singleton @@ Enum.empty ()
  | Some v ->
    let f = powerset e in
    let g = Enum.clone f in
    EnumL.map f ~f:(fun x -> let y = Enum.clone x in push y v; y)
    |>  Enum.append g

let permutations l =
  let rec aux l =
    let rec interleave x = function
      | [] -> [[x]]
      | (hd::tl) as lst ->
        (x::lst) ::
        (ListL.map ~f:(List.cons hd)  @@ interleave x tl)
    in
    match l with
    | [] -> [[]]
    | hd::tl -> List.concat @@ List.map (interleave hd) @@ aux tl in
  let l = List.sort (List.compare Int.compare) @@ aux @@ List.of_enum l in
  List.enum % ListL.map ~f:List.enum @@ l

let intersection l =
  EnumL.filter ~f:(fun x -> EnumL.exists ~f:((=) x) @@ Enum.clone l)

let lower_bound n f =
  let rec aux l u =
    if u - l > 1 then
      let m = (l + u) / 2 in
      if f m then aux l m
      else aux m u
    else u in aux (-1) n

let (n, q) = scan "%d %d" Tuple.Tuple2.make
let ab = List.of_enum @@ scan_lines (n-1) "%d %d" Tuple.Tuple2.make
let px = List.of_enum @@ scan_lines q "%d %d" Tuple.Tuple2.make

let () =
  let tree = Array.init n (fun _ -> []) in
  let ntree = Array.make n 0 in
  ListL.iter ab ~f:(fun (a, b) ->
      tree.(pred a) <- (pred b)::tree.(pred a);
      tree.(pred b) <- (pred a)::tree.(pred b));
  ListL.iter px ~f:(fun (p,x) ->
      ntree.(pred p) <- ntree.(pred p) + x);
  let rec update n v visited =
    if not visited.(n) then
      let w = v + ntree.(n) in
      visited.(n) <- true;
      ntree.(n) <- w;
      ListL.iter tree.(n) ~f:(fun p -> update p w visited)
  in
  update 0 0 (Array.make n false);
  IO.to_string (Array.print ~first:"" ~last:"\n" ~sep:" " Int.print) ntree
  |> Printf.printf "%s"


open Batteries
module EnumL = Enum.Labels
module ListL = List.Labels
module ArrayL = Array.Labels

let dbg0 x = Printf.eprintf "[debug]%s\n" @@ dump x
let dbg1 x = dbg0 x; x

let id = identity

let (++) n m = List.range n `To m
let (++^) n m = if n < m then List.range n `To (pred m) else []

let scan fmt = Scanf.sscanf (read_line ()) fmt

let scan_lines n fmt f =
  if n = 0 then Enum.empty ()
  else
    List.map (fun _ -> scan fmt f) (List.range 1 `To n)
    |> List.enum

let scan_list cnv =
  String.split_on_char ' ' @@ read_line ()
  |> List.map cnv

let scan_array cnv = Array.of_list @@ scan_list cnv

let scan_matrix n m e conv =
  let arr = Array.make_matrix n m e in
  ListL.iter (List.range 0 `To (pred n))
    ~f:(fun i -> arr.(i) <- Array.of_list @@ scan_list conv);
  arr

let rec powerset e =
  match Enum.get e with
  | None -> Enum.singleton @@ Enum.empty ()
  | Some v ->
    let f = powerset e in
    let g = Enum.clone f in
    EnumL.map f ~f:(fun x -> let y = Enum.clone x in push y v; y)
    |>  Enum.append g

let permutations l =
  let rec aux l =
    let rec interleave x = function
      | [] -> [[x]]
      | (hd::tl) as lst ->
        (x::lst) ::
        (ListL.map ~f:(List.cons hd)  @@ interleave x tl)
    in
    match l with
    | [] -> [[]]
    | hd::tl -> List.concat @@ List.map (interleave hd) @@ aux tl in
  let l = List.sort (List.compare Int.compare) @@ aux @@ List.of_enum l in
  List.enum % ListL.map ~f:List.enum @@ l

let intersection l =
  EnumL.filter ~f:(fun x -> EnumL.exists ~f:((=) x) @@ Enum.clone l)

let lower_bound n f =
  let rec aux l u =
    if u - l > 1 then
      let m = (l + u) / 2 in
      if f m then aux l m
      else aux m u
    else u in aux (-1) n

let (n, q) = scan "%d %d" Tuple.Tuple2.make
let ab = List.of_enum @@ scan_lines (n-1) "%d %d" Tuple.Tuple2.make
let px = List.of_enum @@ scan_lines q "%d %d" Tuple.Tuple2.make

let () =
  let tree = Array.init n (fun _ -> []) in
  let ntree = Array.make n 0 in
  let rec cut p n =
    let cs = tree.(n) in
    tree.(n) <- ListL.filter_map cs ~f:(fun c ->
        if c = p then None
        else (cut n c; Some c))
  in
  ListL.iter ab ~f:(fun (a, b) ->
      tree.(pred a) <- (pred b)::tree.(pred a);
      tree.(pred b) <- (pred a)::tree.(pred b));
  ListL.iter tree.(0) ~f:(cut 0);
  ListL.iter px ~f:(fun (p,x) ->
      ntree.(pred p) <- ntree.(pred p) + x);
  let rec update n v =
    let w = v + ntree.(n) in
    ntree.(n) <- w;
    ListL.iter tree.(n) ~f:(fun p ->
        update p w) in
  update 0 0;
  IO.to_string (Array.print ~first:"" ~last:"\n" ~sep:" " Int.print) ntree
  |> Printf.printf "%s"


open Batteries
module EnumL = Enum.Labels
module ListL = List.Labels
module ArrayL = Array.Labels

let dbg0 x = Printf.eprintf "[debug]%s\n" @@ dump x
let dbg1 x = dbg0 x; x

let id = identity

let (++) n m = List.range n `To m
let (++^) n m = if n < m then List.range n `To (pred m) else []

let scan fmt = Scanf.sscanf (read_line ()) fmt

let scan_lines n fmt f =
  if n = 0 then Enum.empty ()
  else
    List.map (fun _ -> scan fmt f) (List.range 1 `To n)
    |> List.enum

let scan_list cnv =
  String.split_on_char ' ' @@ read_line ()
  |> List.map cnv

let scan_array cnv = Array.of_list @@ scan_list cnv

let scan_matrix n m e conv =
  let arr = Array.make_matrix n m e in
  ListL.iter (List.range 0 `To (pred n))
    ~f:(fun i -> arr.(i) <- Array.of_list @@ scan_list conv);
  arr

let rec powerset e =
  match Enum.get e with
  | None -> Enum.singleton @@ Enum.empty ()
  | Some v ->
    let f = powerset e in
    let g = Enum.clone f in
    EnumL.map f ~f:(fun x -> let y = Enum.clone x in push y v; y)
    |>  Enum.append g

let permutations l =
  let rec aux l =
    let rec interleave x = function
      | [] -> [[x]]
      | (hd::tl) as lst ->
        (x::lst) ::
        (ListL.map ~f:(List.cons hd)  @@ interleave x tl)
    in
    match l with
    | [] -> [[]]
    | hd::tl -> List.concat @@ List.map (interleave hd) @@ aux tl in
  let l = List.sort (List.compare Int.compare) @@ aux @@ List.of_enum l in
  List.enum % ListL.map ~f:List.enum @@ l

let intersection l =
  EnumL.filter ~f:(fun x -> EnumL.exists ~f:((=) x) @@ Enum.clone l)

let lower_bound n f =
  let rec aux l u =
    if u - l > 1 then
      let m = (l + u) / 2 in
      if f m then aux l m
      else aux m u
    else u in aux (-1) n

let (n, q) = scan "%d %d" Tuple.Tuple2.make
let ab = List.of_enum @@ scan_lines (n-1) "%d %d" Tuple.Tuple2.make
let px = List.of_enum @@ scan_lines q "%d %d" Tuple.Tuple2.make

let () =
  let tree = Array.init n (fun _ -> []) in
  let ntree = Array.make n 0 in
  let rec cut p  =
    let cs = tree.(p) in
    ListL.iter cs
      ~f:(fun c ->
          tree.(c) <- ListL.filter tree.(c) ~f:((<>) p);
          cut c)
  in
  ListL.iter ab ~f:(fun (a, b) ->
      tree.(pred a) <- (pred b)::tree.(pred a);
      tree.(pred b) <- (pred a)::tree.(pred b));
  cut 0;
  ListL.iter px ~f:(fun (p,x) ->
      let rec aux x p =
        ntree.(p) <- ntree.(p) + x;
        let cs = tree.(p) in
        ListL.iter cs ~f:(aux x)
      in
      aux x (pred p));
  IO.to_string (Array.print ~first:"" ~last:"\n" ~sep:" " Int.print) ntree
  |> Printf.printf "%s"


open Batteries
module EnumL = Enum.Labels
module ListL = List.Labels
module ArrayL = Array.Labels

let dbg0 x = Printf.eprintf "[debug]%s\n" @@ dump x
let dbg1 x = dbg0 x; x

let id = identity

let (++) n m = List.range n `To m
let (++^) n m = if n < m then List.range n `To (pred m) else []

let scan fmt = Scanf.sscanf (read_line ()) fmt

let scan_lines n fmt f =
  if n = 0 then Enum.empty ()
  else
    List.map (fun _ -> scan fmt f) (List.range 1 `To n)
    |> List.enum

let scan_list cnv =
  String.split_on_char ' ' @@ read_line ()
  |> List.map cnv

let scan_array cnv = Array.of_list @@ scan_list cnv

let scan_matrix n m e conv =
  let arr = Array.make_matrix n m e in
  ListL.iter (List.range 0 `To (pred n))
    ~f:(fun i -> arr.(i) <- Array.of_list @@ scan_list conv);
  arr

let rec powerset e =
  match Enum.get e with
  | None -> Enum.singleton @@ Enum.empty ()
  | Some v ->
    let f = powerset e in
    let g = Enum.clone f in
    EnumL.map f ~f:(fun x -> let y = Enum.clone x in push y v; y)
    |>  Enum.append g

let permutations l =
  let rec aux l =
    let rec interleave x = function
      | [] -> [[x]]
      | (hd::tl) as lst ->
        (x::lst) ::
        (ListL.map ~f:(List.cons hd)  @@ interleave x tl)
    in
    match l with
    | [] -> [[]]
    | hd::tl -> List.concat @@ List.map (interleave hd) @@ aux tl in
  let l = List.sort (List.compare Int.compare) @@ aux @@ List.of_enum l in
  List.enum % ListL.map ~f:List.enum @@ l

let intersection l =
  EnumL.filter ~f:(fun x -> EnumL.exists ~f:((=) x) @@ Enum.clone l)

let lower_bound n f =
  let rec aux l u =
    if u - l > 1 then
      let m = (l + u) / 2 in
      if f m then aux l m
      else aux m u
    else u in aux (-1) n

let (n, q) = scan "%d %d" Tuple.Tuple2.make
let ab = List.of_enum @@ scan_lines (n-1) "%d %d" Tuple.Tuple2.make
let px = List.of_enum @@ scan_lines q "%d %d" Tuple.Tuple2.make

let () =
  let tree = Array.init n (fun _ -> []) in
  let ntree = Array.make n 0 in
  ListL.iter ab ~f:(fun (a, b) ->
      tree.(pred a) <- b::tree.(pred a));
  ListL.iter px ~f:(fun (p,x) ->
      let rec aux x p =
        ntree.(pred p) <- ntree.(pred p) + x;
        let cs = tree.(pred p) in
        ListL.iter cs ~f:(aux x)
      in
      aux x p);
  IO.to_string (Array.print ~first:"" ~last:"\n" ~sep:" " Int.print) ntree
  |> Printf.printf "%s"


let scan_int () = Scanf.scanf " %d" (fun x -> x)
let print_array a =
  let _ = Array.iter (Printf.printf "%d ") a in print_newline()

module Graph :
  sig
    type graph
    type edge = int * int * int
    val init : int -> graph
    val get_size : graph -> int
    val get_edge: graph -> int -> edge list
    val add_edge: graph -> int -> int -> int -> unit
    val add_biedge: graph -> int -> int -> int -> unit
    val dfs_tree: graph -> int -> int -> (edge -> unit) -> unit
    val dfs_rec: graph -> int -> bool array -> (edge -> unit) -> unit
    val dfs: graph -> (edge -> unit) -> unit
  end =
  struct
    type edge = int * int * int (* from, to, dist *)
    type graph = {v: int; e: (edge list) array}
    let init _n = {v = _n; e = Array.make _n []}
    let get_size g = g.v
    let get_edge g u = g.e.(u)
    let add_edge g u v d = g.e.(u) <- (u, v, d) :: g.e.(u)
    let add_biedge g u v d = let _ = add_edge g u v d in add_edge g v u d
    let rec dfs_tree g curr prev func =
      let transit curr prev edge =
        let _, next, _ = edge in
        if next = prev then ()
        else let _ = func edge in dfs_tree g next curr func in
      List.iter (transit curr prev) g.e.(curr)
    let rec dfs_rec g curr visited func =
      let _ = visited.(curr) <- true in
      let transit curr visited edge =
        let _, next, _ = edge in
        if visited.(next) then ()
        else let _ = func edge in dfs_rec g next visited func in
      List.iter (transit curr visited) g.e.(curr)
    let dfs g func =
      let visited = Array.make g.v false in
      for i = 0 to g.v - 1 do (if visited.(i) = false then dfs_rec g i visited func) done
  end

let make_graph g n =
  for i = 0 to n-2 do
    let a = scan_int() and b = scan_int() in
    Graph.add_biedge g (a-1) (b-1) 1
  done

let input_query q value =
  for i = 0 to q-1 do
    let p = scan_int() and x = scan_int() in
    value.(p-1) <- value.(p-1) + x
  done

let propagate value edge = let u, v, d = edge in value.(v) <- value.(u) + value.(v)

let () =
  let n = scan_int() and q = scan_int() in
  let g = Graph.init n in
  let _ = make_graph g n in
  let value = Array.make n 0 in
  let _ = input_query q value in
  let _ = Graph.dfs_tree g 0 n (propagate value) in
  print_array value


let n, q = Scanf.scanf " %d %d" @@ fun a b -> a, b
let g, ans = Array.(make n [], make n 0)
let rec f v p = List.iter (fun u -> if u <> p then (ans.(u) <- ans.(u) + ans.(v); f u v)) g.(v)
let _ = Scanf.(for _ = 1 to n - 1 do scanf " %d %d" @@ fun u v -> g.(u - 1) <- v - 1 :: g.(u - 1); g.(v - 1) <- u - 1 :: g.(v - 1) done;
  for _ = 1 to q do scanf " %d %d" @@ fun p x -> ans.(p - 1) <- ans.(p - 1) + x done);
  f 0 ~-1; Array.iteri (fun i n -> Printf.printf (if i = 0 then "%d" else " %d") n) ans; print_newline ()


let n, q = Scanf.scanf " %d %d" @@ fun a b -> a, b
let g = Array.make n []
let _ = for _ = 1 to n - 1 do Scanf.scanf " %d %d" @@ fun u v -> g.(u - 1) <- v - 1 :: g.(u - 1); g.(v - 1) <- u - 1 :: g.(v - 1) done
let pxs = Array.init q @@ fun _ -> Scanf.scanf " %d %d" @@ fun a b -> a - 1, b
let os, ans = Array.(make n 0, make n 0)
let rec f v p x = ans.(v) <- x + os.(v); List.iter (fun u -> if u <> p then f u v @@ x + os.(v)) g.(v)
let _ = Array.(iter (fun (p, x) -> os.(p) <- os.(p) + x) pxs; f 0 ~-1 0; iteri (fun i n -> Printf.printf (if i = 0 then "%d" else " %d") n) ans; print_newline ())


open Printf
open Scanf

let () =
  let n, q = scanf " %d %d" (fun x y -> x, y) in
  let g = Array.make n [] in
  for _ = 0 to n - 2 do
    let a, b = scanf " %d %d" (fun x y -> x - 1, y - 1) in
    g.(a) <- b :: g.(a);
    g.(b) <- a :: g.(b);
  done;
  let ans = Array.make n 0 in
  for _ = 0 to q - 1 do
    let p, x = scanf " %d %d" (fun x y -> x - 1, y) in
    ans.(p) <- ans.(p) + x;
  done;
  let rec dfs u p = g.(u) |> List.iter @@ fun v ->
    if v <> p then begin
      ans.(v) <- ans.(v) + ans.(u);
      dfs v u
    end in
  dfs 0 (-1);
  for i = 0 to n - 1 do
    printf "%d " ans.(i)
  done;
  print_newline ();


let () = Scanf.scanf "%d %d\n" @@ fun n q ->
  let es = Array.make n [] in
  for i = 0 to n - 2 do
    Scanf.scanf "%d %d\n" @@ fun a b ->
      es.(a - 1) <- b - 1 :: es.(a - 1);
      es.(b - 1) <- a - 1 :: es.(b - 1)
  done;
  let acc = Array.make n 0 in
  for i = 0 to q - 1 do
    Scanf.scanf "%d %d\n" @@ fun p x ->
      acc.(p - 1) <- acc.(p - 1) + x
  done;
  let visited = Array.make n false in
  let rec visit prev v =
    if not visited.(v) then begin
      visited.(v) <- true;
      acc.(v) <- acc.(v) + prev;
      List.iter (visit acc.(v)) es.(v)
    end in
  visit 0 0;
  Array.iter (Printf.printf "%d ") acc;
  print_newline ()


Scanf.scanf "%d %d %d" (fun n m p ->
    let nei = Array.make n [] in
    let uvw = Array.init m (fun _ ->
        Scanf.scanf " %d %d %d" (fun a b c ->
            let a = a - 1 in let b = b - 1 in
            nei.(a) <- b :: nei.(a);
            a, b, c - p
        )
    )
    in

    let sentinel = min_int / 10 in
    let bellman start =
        let cost = Array.make n sentinel in
        cost.(start) <- 0;
        for i = 0 to n - 1 do
            Array.iter (fun (u, v, w) ->
                if cost.(v) < cost.(u) + w then (
                    cost.(v) <- cost.(u) + w;
                )
            ) uvw
        done;
        cost
    in

    let reachable n1 n2 =
        let visited = Array.make n false in

        let rec visit cur =
            visited.(cur) <- true;
            List.iter (fun next -> if not visited.(next) then visit next) nei.(cur)
        in
        visit n1;
        visited.(n2)
    in

    let cost = bellman 0 in

    let flag = Array.fold_left (fun acc (u, v, w) ->
        if cost.(u) + w > cost.(v) && reachable 0 u && reachable u (n - 1) then true else acc) false uvw
    in
    Printf.printf "%d\n" @@ if flag then (-1) else max 0 cost.(n - 1)
)

Score : 500 points

Problem Statement

There is a directed graph with N vertices numbered 1 to N and M edges.
The i-th edge is directed from Vertex A_i to Vertex B_i, and there are C_i coins placed along that edge.
Additionally, there is a button on Vertex N.

We will play a game on this graph.
You start the game on Vertex 1 with zero coins, and head for Vertex N by traversing the edges while collecting coins.
It takes one minute to traverse an edge, and you can collect the coins placed along the edge each time you traverse it.
As usual in games, even if you traverse an edge once and collect the coins, the same number of coins will reappear next time you traverse that edge, which you can collect again.

When you reach Vertex N, you can end the game by pressing the button. (You can also choose to leave Vertex N without pressing the button and continue traveling.)
However, when you end the game, you will be asked to pay T \times P coins, where T is the number of minutes elapsed since the start of the game. If you have less than T \times P coins, you will have to pay all of your coins instead.

Your score will be the number of coins you have after this payment.
Determine if there exists a maximum value of the score that can be obtained. If the answer is yes, find that maximum value.

Constraints

2 \leq N \leq 2500

1 \leq M \leq 5000

1 \leq A_i, B_i \leq N

1 \leq C_i \leq 10^5

0 \leq P \leq 10^5

All values in input are integers.

Vertex N can be reached from Vertex 1.

Input

Input is given from Standard Input in the following format:

N M P
A_1 B_1 C_1
:
A_M B_M C_M

Output

If there exists a maximum value of the score that can be obtained, print that maximum value; otherwise, print -1.

Sample Input 1

3 3 10
1 2 20
2 3 30
1 3 45

Sample Output 1

35

There are two ways to travel from Vertex 1 to Vertex 3:

Vertex 1 \rightarrow 2 \rightarrow 3: You collect 20 + 30 = 50 coins on the way. After two minutes from the start of the game, you press the button, pay 2 \times 10 = 20 coins, and you have 50 - 20 = 30 coins left.

Vertex 1 \rightarrow 2: You collect 45 coins on the way. After one minute from the start of the game, you press the button, pay 1 \times 10 = 10 coins, and you have 45 - 10 = 35 coins left.

Thus, the maximum score that can be obtained is 35.

Sample Input 2

2 2 10
1 2 100
2 2 100

Sample Output 2

-1

The edge extending from Vertex 1 takes you to Vertex 2. If you then traverse the edge extending from Vertex 2 to itself t times and press the button, your score will be 90 + 90t. Thus, you can infinitely increase your score, which means there is no maximum value of the score that can be obtained.

Sample Input 3

4 5 10
1 2 1
1 4 1
3 4 1
2 2 100
3 3 100

Sample Output 3

0

There is no way to travel from Vertex 1 to Vertex 4 other than traversing the edge leading from Vertex 1 to Vertex 4 directly. You will pick up one coin along this edge, but after being asked to paying 10 coins, your score will be 0.

Note that you can collect an infinite number of coins if you traverse the edge leading from Vertex 1 to Vertex 2, but this is pointless since you can no longer reach Vertex 4 and end the game.


module WeightedDirectedGraph
  (Weight : sig
    type t
    val inf : t (* オーバーフローの恐れはないので，max_intとか突っ込んでも良い *)
    val zero : t
    val neg_inf : t (* オーバーフローの恐れはないので，min_intとか突っ込んでも良い *)
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  val bellman_ford :
    (* 頂点数n *)
    int ->
    (* 辺のリスト
       頂点は0からn-1までの整数でなくてはならない *)
    (int * int * Weight.t) church_list ->
    (* 始点 *)
    int ->
    (* 頂点を受け取り，そこまでの距離を返す関数
       頂点に到達するパスが無ければinfを返し，
       そこに到達するまでに負閉路があればneg_infを返す *)
    (int -> Weight.t)
end =
struct
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  let bellman_ford n es s =
    (* 距離を覚えるやつ *)
    let d = Array.make n Weight.inf in
    (* 自己辺の最小のコスト *)
    let self = Array.make n Weight.zero in
    (* 始点より終点のインデックスが大きくなる辺を集めた隣接リスト *)
    let inc = Array.make n [] in
    (* 始点より終点のインデックスが小さくなる辺を集めた隣接リスト *)
    let dec = Array.make n [] in
    es.fold (fun ((u, v, c) as e) () ->
      match compare v u with
      | 0 -> if 0 < Weight.compare self.(u) c then self.(u) <- c
      | cmp when 0 < cmp -> inc.(u) <- e :: inc.(u)
      | _ -> dec.(u) <- e :: dec.(u)) ();
    (* 自己辺は最初に緩和する必要がある *)
    Array.iteri (fun v c ->
      if 0 < Weight.compare Weight.zero c then
        inc.(v) <- (v, v, c) :: inc.(v)) self;
    d.(s) <- Weight.zero;
    (* 残りの反復回数 *)
    let i = ref n in
    (* 更新が行われたか *)
    let is_modified = ref true in
    (* 各辺の処理 *)
    let f (u, v, c) =
      let open Weight in
      (* 原点から到達できない頂点は更新しない *)
      if 0 < Weight.compare inf d.(u) then
        let dv = if 0 <= Weight.compare neg_inf d.(u) then neg_inf else d.(u) + c in
        if 0 < Weight.compare d.(v) dv then
          (is_modified := true; d.(v) <- if !i <= succ n lsr 1 then neg_inf else dv) in
    while 0 < !i && !is_modified do
      is_modified := false;
      (* インデックスが増加する辺の処理 *)
      Array.iter (List.iter f) inc;
      (* インデックスが減少する辺の処理 *)
      for u = n - 1 downto 0 do
        List.iter f dec.(u)
      done;
      decr i
    done;
    Array.get d
end

module G = WeightedDirectedGraph (struct
  type t = int
  let zero = 0
  let inf = min_int
  let neg_inf = max_int
  let ( + ) = ( + )
  let compare x y = compare y x
end)

let () = Scanf.scanf "%d %d %d\n" @@ fun n m p ->
  let abc = Array.init m @@ fun _ ->
    Scanf.scanf "%d %d %d\n" @@ fun a b c -> a - 1, b - 1, c - p in
  let d = G.bellman_ford n { G.fold = fun f -> Array.fold_right f abc } 0 (n - 1) in
  if max_int <= d
  then print_endline "-1"
  else Printf.printf "%d\n" @@ max 0 d


module WeightedDirectedGraph
  (Weight : sig
    type t
    val inf : t (* オーバーフローの恐れはないので，max_intとか突っ込んでも良い *)
    val zero : t
    val neg_inf : t (* オーバーフローの恐れはないので，min_intとか突っ込んでも良い *)
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  val bellman_ford :
    (* 頂点数n *)
    int ->
    (* 辺のリスト
       頂点は0からn-1までの整数でなくてはならない *)
    (int * int * Weight.t) church_list ->
    (* 始点 *)
    int ->
    (* 頂点を受け取り，そこまでの距離を返す関数
       頂点に到達するパスが無ければinfを返し，
       そこに到達するまでに負閉路があればneg_infを返す *)
    (int -> Weight.t)
end =
struct
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  let bellman_ford n es s =
    (* 距離を覚えるやつ *)
    let d = Array.make n Weight.inf in
    (* 自己辺の最小のコスト *)
    let self = Array.make n Weight.inf in
    (* 始点より終点のインデックスが大きくなる辺を集めた隣接リスト *)
    let inc = Array.make n [] in
    (* 始点より終点のインデックスが小さくなる辺を集めた隣接リスト *)
    let dec = Array.make n [] in
    es.fold (fun ((u, v, c) as e) () ->
      match compare v u with
      | 0 -> if 0 < Weight.compare self.(u) c then self.(u) <- c
      | cmp when 0 < cmp -> inc.(u) <- e :: inc.(u)
      | _ -> dec.(u) <- e :: dec.(u)) ();
    (* 自己辺は最初に緩和する必要がある *)
    Array.iteri (fun v c ->
      if 0 < Weight.compare Weight.inf c then
        inc.(v) <- (v, v, c) :: inc.(v)) self;
    d.(s) <- Weight.zero;
    (* 残りの反復回数 *)
    let i = ref n in
    (* 更新が行われたか *)
    let is_modified = ref true in
    (* 各辺の処理 *)
    let f (u, v, c) =
      let open Weight in
      (* 原点から到達できない頂点は更新しない *)
      if 0 < Weight.compare inf d.(u) then
        let dv = if 0 <= Weight.compare neg_inf d.(u) then neg_inf else d.(u) + c in
        if 0 < Weight.compare d.(v) dv then
          (is_modified := true; d.(v) <- if !i <= succ n lsr 1 then neg_inf else dv) in
    while 0 < !i && !is_modified do
      is_modified := false;
      (* インデックスが増加する辺の処理 *)
      for u = 0 to n - 1 do
        List.iter f inc.(u)
      done;
      (* インデックスが減少する辺の処理 *)
      for u = n - 1 downto 0 do
        List.iter f dec.(u)
      done;
      decr i
    done;
    Array.get d
end

module G = WeightedDirectedGraph (struct
  type t = int
  let zero = 0
  let inf = min_int
  let neg_inf = max_int
  let ( + ) = ( + )
  let compare x y = compare y x
end)

let () = Scanf.scanf "%d %d %d\n" @@ fun n m p ->
  let abc = Array.init m @@ fun _ ->
    Scanf.scanf "%d %d %d\n" @@ fun a b c -> a - 1, b - 1, c - p in
  let d = G.bellman_ford n { G.fold = fun f -> Array.fold_right f abc } 0 (n - 1) in
  if max_int <= d
  then print_endline "-1"
  else Printf.printf "%d\n" @@ max 0 d


module WeightedDirectedGraph
  (Weight : sig
    type t
    val inf : t (* オーバーフローの恐れはないので，max_intとか突っ込んでも良い *)
    val zero : t
    val neg_inf : t (* オーバーフローの恐れはないので，min_intとか突っ込んでも良い *)
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  val bellman_ford :
    (* 頂点数n *)
    int ->
    (* 辺のリスト
       頂点は0からn-1までの整数でなくてはならない *)
    (int * int * Weight.t) church_list ->
    (* 始点 *)
    int ->
    (* 頂点を受け取り，そこまでの距離を返す関数
       頂点に到達するパスが無ければinfを返し，
       そこに到達するまでに負閉路があればneg_infを返す *)
    (int -> Weight.t)
end =
struct
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  let bellman_ford n es s =
    (* 距離を覚えるやつ *)
    let d = Array.make n Weight.inf in
    (* 自己辺の最小のコスト *)
    let self = Array.make n Weight.inf in
    (* 始点より終点のインデックスが大きくなる辺を集めた隣接リスト *)
    let inc = Array.make n [] in
    (* 始点より終点のインデックスが小さくなる辺を集めた隣接リスト *)
    let dec = Array.make n [] in
    es.fold (fun ((u, v, c) as e) () ->
      match compare v u with
      | 0 -> if 0 < Weight.compare self.(u) c then self.(u) <- c
      | cmp when 0 < cmp -> inc.(u) <- e :: inc.(u)
      | _ -> dec.(u) <- e :: dec.(u)) ();
    (* 自己辺は最初に緩和する必要がある *)
    Array.iteri (fun v c ->
      if 0 < Weight.compare Weight.inf c then
        inc.(v) <- (v, v, c) :: inc.(v)) self;
    d.(s) <- Weight.zero;
    (* 各辺のの処理 *)
    let f i is_modified (u, v, c) =
      (* 原点から到達できない頂点は更新しない *)
      if 0 <= Weight.compare d.(u) Weight.inf
      then is_modified
      else
        let dv =
          if 0 <= Weight.compare Weight.neg_inf d.(u)
          then Weight.neg_inf
          else let open Weight in d.(u) + c in
        if 0 <= Weight.compare dv d.(v)
        then is_modified
        (* n / 2 回目以降に書き換わった場合，vまでの経路に負閉路が含まれている *)
        else (d.(v) <- if i <= succ n lsr 1 then Weight.neg_inf else dv; true) in
    let rec iter = function
      | 0 -> ()
      | i ->
          if
            Array.fold_right (Fun.flip (List.fold_left (f i))) dec @@
            Array.fold_left (List.fold_left (f i)) false inc
          then iter (i - 1) in
    iter n;
    Array.get d
end

module G = WeightedDirectedGraph (struct
  type t = int
  let zero = 0
  let inf = min_int
  let neg_inf = max_int
  let ( + ) = ( + )
  let compare x y = compare y x
end)

let () = Scanf.scanf "%d %d %d\n" @@ fun n m p ->
  let abc = Array.init m @@ fun _ ->
    Scanf.scanf "%d %d %d\n" @@ fun a b c -> a - 1, b - 1, c - p in
  let d = G.bellman_ford n { G.fold = fun f -> Array.fold_right f abc } 0 (n - 1) in
  if max_int <= d
  then print_endline "-1"
  else Printf.printf "%d\n" @@ max 0 d


module WeightedDirectedGraph
  (Weight : sig
    type t
    val inf : t (* オーバーフローの恐れはないので，max_intとか突っ込んでも良い *)
    val zero : t
    val neg_inf : t (* オーバーフローの恐れはないので，min_intとか突っ込んでも良い *)
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  val bellman_ford :
    (* 頂点数n *)
    int ->
    (* 辺のリスト
       頂点は0からn-1までの整数でなくてはならない *)
    (int * int * Weight.t) church_list ->
    (* 始点 *)
    int ->
    (* 頂点を受け取り，そこまでの距離を返す関数
       頂点に到達するパスが無ければinfを返し，
       そこに到達するまでに負閉路があればneg_infを返す *)
    (int -> Weight.t)
end =
struct
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  let bellman_ford n es s =
    (* 距離を覚えるやつ *)
    let d = Array.make n Weight.inf in
    (* 始点より終点のインデックスが大きくなる辺を集めた隣接リスト *)
    let inc = Array.make n [] in
    (* 始点より終点のインデックスが小さくなる辺を集めた隣接リスト *)
    let dec = Array.make n [] in
    es.fold (fun ((u, v, _) as e) () ->
      if u <= v
      then inc.(u) <- e :: inc.(u)
      else dec.(u) <- e :: dec.(u)) ();
    d.(s) <- Weight.zero;
    (* n / 2 回目以降の各辺の処理 *)
    let f is_modified (u, v, c) =
      (* 原点から到達できない頂点は更新しない *)
      if 0 <= Weight.compare d.(u) Weight.inf
      then is_modified
      else
        let dv =
          if 0 <= Weight.compare Weight.neg_inf d.(u)
          then Weight.neg_inf
          else let open Weight in d.(u) + c in
        if 0 <= Weight.compare dv d.(v)
        then is_modified
        else (d.(v) <- Weight.neg_inf; true) in
    (* n / 2 回以降の反復 *)
    let rec iter' = function
      | 0 -> ()
      | i ->
          if
            Array.fold_right (Fun.flip (List.fold_left f)) dec @@
            Array.fold_left (List.fold_left f) false inc
          then iter' (i - 1) in
    (* n / 2 回目以前の各辺の処理 *)
    let f is_modified (u, v, c) =
      (* 原点から到達できない頂点は更新しない *)
      if 0 <= Weight.compare d.(u) Weight.inf
      then is_modified
      else
        let dv = let open Weight in d.(u) + c in
        if 0 <= Weight.compare dv d.(v)
        then is_modified
        else (d.(v) <- dv; true) in
    let rec iter = function
      | 0 -> iter' (succ n lsr 1)
      | i ->
          if
            Array.fold_right (Fun.flip (List.fold_left f)) dec @@
            Array.fold_left (List.fold_left f) false inc
          then iter (i - 1) in
    iter (n lsr 1);
    Array.get d
end

module G = WeightedDirectedGraph (struct
  type t = int
  let zero = 0
  let inf = min_int
  let neg_inf = max_int
  let ( + ) = ( + )
  let compare x y = compare y x
end)

let () = Scanf.scanf "%d %d %d\n" @@ fun n m p ->
  let abc = Array.init m @@ fun _ ->
    Scanf.scanf "%d %d %d\n" @@ fun a b c -> a - 1, b - 1, c - p in
  let d = G.bellman_ford n { G.fold = fun f -> Array.fold_right f abc } 0 (n - 1) in
  if max_int <= d
  then print_endline "-1"
  else Printf.printf "%d\n" @@ max 0 d


module WeightedDirectedGraph
  (Weight : sig
    type t
    val inf : t (* オーバーフローの恐れはないので，max_intとか突っ込んでも良い *)
    val zero : t
    val neg_inf : t (* オーバーフローの恐れはないので，min_intとか突っ込んでも良い *)
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  val bellman_ford :
    (* 頂点数n *)
    int ->
    (* 辺のリスト
       頂点は0からn-1までの整数でなくてはならない *)
    (int * int * Weight.t) church_list ->
    (* 始点 *)
    int ->
    (* 頂点を受け取り，そこまでの距離を返す関数
       頂点に到達するパスが無ければinfを返し，
       そこに到達するまでに負閉路があればneg_infを返す *)
    (int -> Weight.t)
end =
struct
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  let bellman_ford n es s =
    (* 距離を覚えるやつ *)
    let d = Array.make n Weight.inf in
    (* 経路に負閉路が含まれる頂点を覚えるやつ *)
    let neg = Array.make n false in
    (* 始点より終点のインデックスが大きくなる辺を集めた隣接リスト *)
    let inc = Array.make n [] in
    (* 始点より終点のインデックスが小さくなる辺を集めた隣接リスト *)
    let dec = Array.make n [] in
    es.fold (fun ((u, v, c) as e) () ->
      if u <= v
      then inc.(u) <- e :: inc.(u)
      else dec.(u) <- e :: dec.(u)) ();
    d.(s) <- Weight.zero;
    (* 残りの反復回数 *)
    let i = ref n in
    (* 更新が行われたか *)
    let is_modified = ref true in
    (* 各辺の処理 *)
    let f (u, v, c) =
      let open Weight in
      if neg.(u) && not neg.(v) then (neg.(v) <- true; is_modified := true);
      if
        (* 原点から到達できない頂点は更新しない *)
        0 < Weight.compare inf d.(u)
        (* c は u から v への辺の重さ
           d.(u) + c < d.(v) *)
        && 0 < Weight.compare d.(v) (d.(u) + c)
      then begin
        d.(v) <- d.(u) + c;
        is_modified := true;
        if !i <= succ n lsr 1 then neg.(v) <- true
      end in
    while 0 < !i && !is_modified do
      is_modified := false;
      (* インデックスが増加する辺の処理 *)
      for u = 0 to n - 1 do
        List.iter f inc.(u)
      done;
      (* インデックスが減少する辺の処理 *)
      for u = n - 1 downto 0 do
        List.iter f dec.(u)
      done;
      decr i
    done;
    fun v -> if neg.(v) then Weight.neg_inf else d.(v)
end

module G = WeightedDirectedGraph (struct
  type t = int
  let zero = 0
  let inf = min_int
  let neg_inf = max_int
  let ( + ) = ( + )
  let compare x y = compare y x
end)

let () = Scanf.scanf "%d %d %d\n" @@ fun n m p ->
  let abc = Array.init m @@ fun _ ->
    Scanf.scanf "%d %d %d\n" @@ fun a b c -> a - 1, b - 1, c - p in
  let d = G.bellman_ford n { G.fold = fun f -> Array.fold_right f abc } 0 (n - 1) in
  if max_int <= d
  then print_endline "-1"
  else Printf.printf "%d\n" @@ max 0 d


module WeightedDirectedGraph
  (Weight : sig
    type t
    val inf : t (* オーバーフローの恐れはないので，max_intとか突っ込んでも良い *)
    val zero : t
    val neg_inf : t (* オーバーフローの恐れはないので，min_intとか突っ込んでも良い *)
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  val bellman_ford :
    (* 頂点数n *)
    int ->
    (* 辺のリスト
       頂点は0からn-1までの整数でなくてはならない *)
    (int * int * Weight.t) church_list ->
    (* 始点 *)
    int ->
    (* 頂点を受け取り，そこまでの距離を返す関数
       頂点に到達するパスが無ければinfを返し，
       そこに到達するまでに負閉路があればneg_infを返す *)
    (int -> Weight.t)
end =
struct
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  let bellman_ford n es s =
    (* 距離を覚えるやつ *)
    let d = Array.make n Weight.inf in
    (* 始点より終点のインデックスが大きくなる辺を集めた隣接リスト *)
    let inc = Array.make n [] in
    (* 始点より終点のインデックスが小さくなる辺を集めた隣接リスト *)
    let dec = Array.make n [] in
    es.fold (fun ((u, v, _) as e) () ->
      if u <= v
      then inc.(u) <- e :: inc.(u)
      else dec.(u) <- e :: dec.(u)) ();
    d.(s) <- Weight.zero;
    (* 残りの反復回数 *)
    let i = ref n in
    (* 更新が行われたか *)
    let is_modified = ref true in
    (* 各辺の処理 *)
    let f (u, v, c) =
      let open Weight in
      (* 原点から到達できない頂点は更新しない *)
      if 0 < Weight.compare inf d.(u) then
        let dv = if 0 <= Weight.compare neg_inf d.(u) then neg_inf else d.(u) + c in
        if 0 < Weight.compare d.(v) dv then
          (is_modified := true; d.(v) <- if !i <= succ n lsr 1 then neg_inf else dv) in
    while 0 < !i && !is_modified do
      is_modified := false;
      (* インデックスが増加する辺の処理 *)
      for u = 0 to n - 1 do
        List.iter f inc.(u)
      done;
      (* インデックスが減少する辺の処理 *)
      for u = n - 1 downto 0 do
        List.iter f dec.(u)
      done;
      decr i
    done;
    Array.get d
end

module G = WeightedDirectedGraph (struct
  type t = int
  let zero = 0
  let inf = min_int
  let neg_inf = max_int
  let ( + ) = ( + )
  let compare x y = compare y x
end)

let () = Scanf.scanf "%d %d %d\n" @@ fun n m p ->
  let abc = Array.init m @@ fun _ ->
    Scanf.scanf "%d %d %d\n" @@ fun a b c -> a - 1, b - 1, c - p in
  let d = G.bellman_ford n { G.fold = fun f -> Array.fold_right f abc } 0 (n - 1) in
  if max_int <= d
  then print_endline "-1"
  else Printf.printf "%d\n" @@ max 0 d


module WeightedDirectedGraph
  (Weight : sig
    type t
    val inf : t (* オーバーフローの恐れはないので，max_intとか突っ込んでも良い *)
    val zero : t
    val neg_inf : t (* オーバーフローの恐れはないので，min_intとか突っ込んでも良い *)
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  val bellman_ford :
    (* 頂点数n *)
    int ->
    (* 辺のリスト
       頂点は0からn-1までの整数でなくてはならない
       2n回呼び出されるので，リストを作るのに時間がかかるならメモ化すること *)
    (int * int * Weight.t) church_list ->
    (* 始点 *)
    int ->
    (* 頂点を受け取り，そこまでの距離を返す関数
       頂点に到達するパスが無ければinfを返し，
       そこに到達するまでに負閉路があればneg_infを返す *)
    (int -> Weight.t)
end =
struct
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  let bellman_ford n es s =
    (* 距離を覚えるやつ *)
    let d = Array.make n Weight.inf in
    (* 経路に負閉路が含まれる頂点を覚えるやつ *)
    let neg = Array.make n false in
    (* 始点より終点のインデックスが大きくなる辺を集めた隣接リスト *)
    let inc = Array.make n [] in
    (* 始点より終点のインデックスが小さくなる辺を集めた隣接リスト *)
    let dec = Array.make n [] in
    es.fold (fun ((u, v, c) as e) () ->
      if u <= v
      then inc.(u) <- e :: inc.(u)
      else dec.(u) <- e :: dec.(u)) ();
    d.(s) <- Weight.zero;
    (* 残りの反復回数 *)
    let i = ref n in
    (* 更新が行われたか *)
    let is_modified = ref true in
    (* 各辺の処理 *)
    let f (u, v, c) =
      let open Weight in
      if neg.(u) then neg.(v) <- true;
      if
        (* 原点から到達できない頂点は更新しない *)
        0 < Weight.compare inf d.(u)
        (* c は u から v への辺の重さ
           d.(u) + c < d.(v) *)
        && 0 < Weight.compare d.(v) (d.(u) + c)
      then begin
        d.(v) <- d.(u) + c;
        is_modified := true;
        if !i <= succ n lsr 1 then neg.(v) <- true
      end in
    while 0 < !i && !is_modified do
      is_modified := false;
      (* インデックスが増加する辺の処理 *)
      for u = 0 to n - 1 do
        List.iter f inc.(u)
      done;
      (* インデックスが減少する辺の処理 *)
      for u = n - 1 downto 0 do
        List.iter f dec.(u)
      done;
      decr i
    done;
    fun v -> if neg.(v) then Weight.neg_inf else d.(v)
end

module G = WeightedDirectedGraph (struct
  type t = int
  let zero = 0
  let inf = min_int
  let neg_inf = max_int
  let ( + ) = ( + )
  let compare x y = compare y x
end)

let () = Scanf.scanf "%d %d %d\n" @@ fun n m p ->
  let abc = Array.init m @@ fun _ ->
    Scanf.scanf "%d %d %d\n" @@ fun a b c -> a - 1, b - 1, c - p in
  let d = G.bellman_ford n { G.fold = fun f -> Array.fold_right f abc } 0 (n - 1) in
  if max_int <= d
  then print_endline "-1"
  else Printf.printf "%d\n" @@ max 0 d


module WeightedDirectedGraph
  (Weight : sig
    type t
    val inf : t (* オーバーフローの恐れはないので，max_intとか突っ込んでも良い *)
    val zero : t
    val neg_inf : t (* オーバーフローの恐れはないので，min_intとか突っ込んでも良い *)
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  val bellman_ford :
    (* 頂点数n *)
    int ->
    (* 辺のリスト
       頂点は0からn-1までの整数でなくてはならない
       2n回呼び出されるので，リストを作るのに時間がかかるならメモ化すること *)
    (int * int * Weight.t) church_list ->
    (* 始点 *)
    int ->
    (* 頂点を受け取り，そこまでの距離を返す関数
       頂点に到達するパスが無ければinfを返し，
       そこに到達するまでに負閉路があればneg_infを返す *)
    (int -> Weight.t)
end =
struct
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  let bellman_ford n es s =
    (* 距離を覚えるやつ *)
    let d = Array.make n Weight.inf in
    (* 経路に負閉路が含まれる頂点を覚えるやつ *)
    let neg = Array.make n false in
    (* 始点より終点のインデックスが大きくなる辺を集めた隣接リスト *)
    let inc = Array.make n [] in
    (* 始点より終点のインデックスが小さくなる辺を集めた隣接リスト *)
    let dec = Array.make n [] in
    es.fold (fun (u, v, c) () ->
      if u <= v
      then inc.(u) <- (v, c) :: inc.(u)
      else dec.(u) <- (v, c) :: dec.(u)) ();
    d.(s) <- Weight.zero;
    (* 残りの反復回数 *)
    let i = ref (n / 2) in
    (* 更新が行われたか *)
    let is_modified = ref true in
    (* 最初の方のループでの各辺の処理 *)
    let f u (v, c) =
      let open Weight in
      if
        (* 原点から到達できない頂点は更新しない *)
        0 < Weight.compare inf d.(u)
        (* c は u から v への辺の重さ
           d.(u) + c < d.(v) *)
        && 0 < Weight.compare d.(v) (d.(u) + c)
      then (d.(v) <- d.(u) + c; is_modified := true) in
    while 0 < !i && !is_modified do
      is_modified := false;
      (* インデックスが増加する辺の処理 *)
      for u = 0 to n - 1 do
        List.iter (f u) inc.(u)
      done;
      (* インデックスが減少する辺の処理 *)
      for u = n - 1 downto 0 do
        List.iter (f u) dec.(u)
      done;
      decr i
    done;
    (* 負閉路を見付けるループでの各辺の処理 *)
    let f u (v, c) =
      if neg.(u) then neg.(v) <- true;
      let open Weight in
      if 0 < Weight.compare inf d.(u) && 0 < Weight.compare d.(v) (d.(u) + c)
      then (d.(v) <- d.(u) + c; neg.(v) <- true; is_modified := true) in
    (* 負閉路を見付けるループ *)
    i := (n + 1) / 2;
    while 0 < !i && !is_modified do
      is_modified := false;
      (* インデックスが増加する辺の処理 *)
      for u = 0 to n - 1 do
        List.iter (f u) inc.(u)
      done;
      (* インデックスが減少する辺の処理 *)
      for u = n - 1 downto 0 do
        List.iter (f u) dec.(u)
      done;
      decr i
    done;
    fun v -> if neg.(v) then Weight.neg_inf else d.(v)
end

module G = WeightedDirectedGraph (struct
  type t = int
  let zero = 0
  let inf = min_int
  let neg_inf = max_int
  let ( + ) = ( + )
  let compare x y = compare y x
end)

let () = Scanf.scanf "%d %d %d\n" @@ fun n m p ->
  let abc = Array.init m @@ fun _ ->
    Scanf.scanf "%d %d %d\n" @@ fun a b c -> a - 1, b - 1, c - p in
  let d = G.bellman_ford n { G.fold = fun f -> Array.fold_right f abc } 0 (n - 1) in
  if max_int <= d
  then print_endline "-1"
  else Printf.printf "%d\n" @@ max 0 d


module WeightedDirectedGraph
  (Weight : sig
    type t
    val inf : t (* オーバーフローの恐れはないので，max_intとか突っ込んでも良い *)
    val zero : t
    val neg_inf : t (* オーバーフローの恐れはないので，min_intとか突っ込んでも良い *)
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  val bellman_ford :
    (* 頂点数n *)
    int ->
    (* 辺のリスト
       頂点は0からn-1までの整数でなくてはならない
       2n回呼び出されるので，リストを作るのに時間がかかるならメモ化すること *)
    (int * int * Weight.t) church_list ->
    (* 始点 *)
    int ->
    (* 頂点を受け取り，そこまでの距離を返す関数
       頂点に到達するパスが無ければinfを返し，
       そこに到達するまでに負閉路があればneg_infを返す *)
    (int -> Weight.t)
end =
struct
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  let bellman_ford n es s =
    (* 距離を覚えるやつ *)
    let d = Array.make n Weight.inf in
    (* 経路に負閉路が含まれる頂点を覚えるやつ *)
    let neg = Array.make n false in
    (* 始点より終点のインデックスが大きくなる辺を集めた隣接リスト *)
    let inc = Array.make n [] in
    (* 始点より終点のインデックスが小さくなる辺を集めた隣接リスト *)
    let dec = Array.make n [] in
    es.fold (fun (u, v, c) () ->
      if u <= v
      then inc.(u) <- (v, c) :: inc.(u)
      else dec.(u) <- (v, c) :: dec.(u)) ();
    d.(s) <- Weight.zero;
    (* 残りの反復回数 *)
    let i = ref (n / 2) in
    (* 更新が行われたか *)
    let is_modified = ref true in
    while 0 < !i && !is_modified do
      is_modified := false;
      (* インデックスが増加する辺の処理 *)
      for u = 0 to n - 1 do
        List.iter (fun (v, c) ->
          let open Weight in
          if
            (* 原点から到達できない頂点は更新しない *)
            0 < Weight.compare inf d.(u)
            (* c は u から v への辺の重さ
               d.(u) + c < d.(v) *)
            && 0 < Weight.compare d.(v) (d.(u) + c)
          then (d.(v) <- d.(u) + c; is_modified := true)) inc.(u)
      done;
      (* インデックスが減少する辺の処理 *)
      for u = n - 1 downto 0 do
        List.iter (fun (v, c) ->
          let open Weight in
          if 0 < Weight.compare inf d.(u) && 0 < Weight.compare d.(v) (d.(u) + c)
          then (d.(v) <- d.(u) + c; is_modified := true)) dec.(u);
      done;
      decr i
    done;
    (* 負閉路を見付けるループ *)
    i := (n + 1) / 2;
    while 0 < !i && !is_modified do
      is_modified := false;
      (* インデックスが増加する辺の処理 *)
      for u = 0 to n - 1 do
        List.iter (fun (v, c) ->
          if neg.(u) then neg.(v) <- true;
          let open Weight in
          if 0 < Weight.compare inf d.(u) && 0 < Weight.compare d.(v) (d.(u) + c)
          then (d.(v) <- d.(u) + c; neg.(v) <- true; is_modified := true)) inc.(u)
      done;
      (* インデックスが減少する辺の処理 *)
      for u = n - 1 downto 0 do
        List.iter (fun (v, c) ->
          if neg.(u) then neg.(v) <- true;
          let open Weight in
          if 0 < Weight.compare inf d.(u) && 0 < Weight.compare d.(v) (d.(u) + c)
          then (d.(v) <- d.(u) + c; neg.(v) <- true; is_modified := true)) dec.(u);
      done;
      decr i
    done;
    fun v -> if neg.(v) then Weight.neg_inf else d.(v)
end

module G = WeightedDirectedGraph (struct
  type t = int
  let zero = 0
  let inf = min_int
  let neg_inf = max_int
  let ( + ) = ( + )
  let compare x y = compare y x
end)

let () = Scanf.scanf "%d %d %d\n" @@ fun n m p ->
  let abc = Array.init m @@ fun _ ->
    Scanf.scanf "%d %d %d\n" @@ fun a b c -> a - 1, b - 1, c - p in
  let d = G.bellman_ford n { G.fold = fun f -> Array.fold_right f abc } 0 (n - 1) in
  if max_int <= d
  then print_endline "-1"
  else Printf.printf "%d\n" @@ max 0 d


module WeightedDirectedGraph
  (Weight : sig
    type t
    val inf : t (* オーバーフローの恐れはないので，max_intとか突っ込んでも良い *)
    val zero : t
    val neg_inf : t (* オーバーフローの恐れはないので，min_intとか突っ込んでも良い *)
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  val bellman_ford :
    (* 頂点数n *)
    int ->
    (* 辺のリスト
       頂点は0からn-1までの整数でなくてはならない
       2n回呼び出されるので，リストを作るのに時間がかかるならメモ化すること *)
    (int * int * Weight.t) church_list ->
    (* 始点 *)
    int ->
    (* 頂点を受け取り，そこまでの距離を返す関数
       頂点に到達するパスが無ければinfを返し，
       そこに到達するまでに負閉路があればneg_infを返す *)
    (int -> Weight.t)
end =
struct
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  let bellman_ford n es s =
    (* 距離を覚えるやつ *)
    let d = Array.make n Weight.inf in
    (* 経路に負閉路が含まれる頂点を覚えるやつ *)
    let neg = Array.make n false in
    d.(s) <- Weight.zero;
    (* n回目以降の反復を行う関数
       途中の反復で更新が行われなければfalseを返す *)
    let rec loop' n =
      n <= 0 ||
      es.fold (fun (u, v, c) b -> (* bは更新の有無 *)
        let open Weight in
        if neg.(u) then neg.(v) <- true;
        (* 原点から到達できない頂点は更新しない *)
        0 < Weight.compare inf d.(u)
        (* c は u から v への辺の重さ
           d.(u) + c < d.(v) *)
        && 0 < Weight.compare d.(v) (d.(u) + c)
        (* n 回目以降に変更が起こった場合，v までの経路に負閉路が含まれている *)
        && (d.(v) <- d.(u) + c; neg.(v) <- true; true) || b) false
      && loop' (n - 1) in
    (* n-1回目までの反復
       途中の反復で更新が行われなければfalseを返す *)
    let rec loop n =
      n <= 0 ||
      es.fold (fun (u, v, c) b ->
        let open Weight in
        (* 原点から到達できない頂点は更新しない *)
        0 < Weight.compare inf d.(u)
        && 0 < Weight.compare d.(v) (d.(u) + c)
        && (d.(v) <- d.(u) + c; true) || b) false
      && loop (n - 1) in
    if loop (n - 1) then ignore (loop' n);
    fun v -> if neg.(v) then Weight.neg_inf else d.(v)
end

module G = WeightedDirectedGraph (struct
  type t = int
  let zero = 0
  let inf = min_int
  let neg_inf = max_int
  let ( + ) = ( + )
  let compare x y = compare y x
end)

let () = Scanf.scanf "%d %d %d\n" @@ fun n m p ->
  let abc = Array.init m @@ fun _ ->
    Scanf.scanf "%d %d %d\n" @@ fun a b c -> a - 1, b - 1, c - p in
  let d = G.bellman_ford n { G.fold = fun f -> Array.fold_right f abc } 0 (n - 1) in
  if max_int <= d
  then print_endline "-1"
  else Printf.printf "%d\n" @@ max 0 d


module WeightedDirectedGraph
  (Weight : sig
    type t
    val inf : t (* オーバーフローの恐れはないので，max_intとか突っ込んでも良い *)
    val zero : t
    val neg_inf : t (* オーバーフローの恐れはないので，min_intとか突っ込んでも良い *)
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  val bellman_ford :
    (* 頂点数n *)
    int ->
    (* 辺のリスト
       頂点は0からn-1までの整数でなくてはならない
       2n回呼び出されるので，リストを作るのに時間がかかるならメモ化すること *)
    (int * int * Weight.t) church_list ->
    (* 始点 *)
    int ->
    (* 頂点を受け取り，そこまでの距離を返す関数
       頂点に到達するパスが無ければinfを返し，
       そこに到達するまでに負閉路があればneg_infを返す *)
    (int -> Weight.t)
end =
struct
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  let bellman_ford n es s =
    (* 距離を覚えるやつ *)
    let d = Array.make n Weight.inf in
    (* 経路に負閉路が含まれる頂点を覚えるやつ *)
    let neg = Array.make n false in
    d.(s) <- Weight.zero;
    (* n回目以降の反復 手動ループアンローリング *)
    let rec loop' n =
      if
        0 < n &&
        es.fold (fun (u, v, c) b -> (* bは更新の有無 *)
          let open Weight in
          if neg.(u) then neg.(v) <- true;
          (* 原点から到達できない頂点は更新しない *)
          0 < Weight.compare inf d.(u)
          (* c は u から v への辺の重さ
             d.(u) + c < d.(v) *)
          && 0 < Weight.compare d.(v) (d.(u) + c)
          (* n 回目以降に変更が起こった場合，v までの経路に負閉路が含まれている *)
          && (d.(v) <- d.(u) + c; neg.(v) <- true; true) || b) false
      then loop' (n - 1) in
    (* n-1回目までの反復 *)
    let rec loop = function
      | 0 -> loop' n
      | n ->
          if
            es.fold (fun (u, v, c) b ->
              let open Weight in
              (* 原点から到達できない頂点は更新しない *)
              0 < Weight.compare inf d.(u)
              && 0 < Weight.compare d.(v) (d.(u) + c)
              && (d.(v) <- d.(u) + c; true) || b) false
          then loop (n - 1) in
    loop (n - 1);
    fun v -> if neg.(v) then Weight.neg_inf else d.(v)
end

module G = WeightedDirectedGraph (struct
  type t = int
  let zero = 0
  let inf = min_int
  let neg_inf = max_int
  let ( + ) = ( + )
  let compare x y = compare y x
end)

let () = Scanf.scanf "%d %d %d\n" @@ fun n m p ->
  let abc = Array.init m @@ fun _ ->
    Scanf.scanf "%d %d %d\n" @@ fun a b c -> a - 1, b - 1, c - p in
  let d = G.bellman_ford n { G.fold = fun f -> Array.fold_right f abc } 0 (n - 1) in
  if max_int <= d
  then print_endline "-1"
  else Printf.printf "%d\n" @@ max 0 d


let () = Scanf.scanf "%d %d %d\n" @@ fun n m p ->
  let abc = Array.init m @@ fun _ ->
    Scanf.scanf "%d %d %d\n" @@ fun a b c -> a - 1, b - 1, c - p in
  let d = Array.make n (-1145141919) in
  let ng = Array.make n false in
  d.(0) <- 0;
  for i = 0 to 2 * n - 1 do
    Array.iter (fun (a, b, c) ->
      if ng.(a) then ng.(b) <- true;
      if d.(b) < d.(a) + c then begin
        d.(b) <- d.(a) + c;
          if n - 1 <= i then
            ng.(b) <- true
      end) abc
  done;
  if ng.(n - 1)
  then print_endline "-1"
  else Printf.printf "%d\n" @@ max 0 d.(n - 1)


let () = Scanf.scanf "%d %d %d\n" @@ fun n m p ->
  let abc = Array.init m @@ fun _ ->
    Scanf.scanf "%d %d %d\n" @@ fun a b c -> a - 1, b - 1, c - p in
  let d = Array.make n (-1145141919) in
  let ng = Array.make n false in
  d.(0) <- 0;
  for i = 0 to 2 * n - 1 do
    Array.iter (fun (a, b, c) ->
      if d.(b) < d.(a) + c then begin
        d.(b) <- d.(a) + c;
          if n - 1 <= i then
            ng.(b) <- true
      end) abc
  done;
  if ng.(n - 1)
  then print_endline "-1"
  else Printf.printf "%d\n" @@ max 0 d.(n - 1)


module WeightedDirectedGraph
  (Weight : sig
    type t
    val inf : t
    val zero : t
    val neg_inf : t
    val ( + ) : t -> t -> t
    val compare : t -> t -> int
  end) :
sig
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  val bellman_ford :
    (* 頂点数n *)
    int ->
    (* 辺のリスト
       頂点は0からn-1までの整数でなくてはならない
       2n回呼び出されるので，リストを作るのに時間がかかるならメモ化すること *)
    (int * int * Weight.t) church_list ->
    (* 始点 *)
    int ->
    (* 頂点を受け取り，そこまでの距離を返す関数
       頂点に到達するパスが無ければinfを返し，
       そこに到達するまでに負閉路があればneg_infを返す *)
    (int -> Weight.t)
end =
struct
  type 'a church_list = { fold : 'b. ('a -> 'b -> 'b) -> 'b -> 'b }

  let bellman_ford n es s =
    (* 距離を覚えるやつ *)
    let d = Array.make n Weight.inf in
    (* 経路に負閉路が含まれる頂点を覚えるやつ *)
    let neg = Array.make n false in
    d.(s) <- Weight.zero;
    (* n回目以降の反復 手動ループアンローリング *)
    let rec loop' n =
      if
        0 < n &&
        es.fold (fun (u, v, c) b -> (* bは更新の有無 *)
          let open Weight in
          (* c は u から v への辺の重さ
             d.(u) + c < d.(v) *)
          0 < Weight.compare d.(v) (d.(u) + c)
          (* n 回目以降に変更が起こった場合，v までの経路に負閉路が含まれている *)
          && (d.(v) <- d.(u) + c; neg.(v) <- true; true) || b) false
      then loop' (n - 1) in
    (* n-1回目までの反復 *)
    let rec loop = function
      | 0 -> loop' n
      | n ->
          if
            es.fold (fun (u, v, c) b ->
              let open Weight in
              0 < Weight.compare d.(v) (d.(u) + c) && (d.(v) <- d.(u) + c; true) || b) false
          then loop (n - 1) in
    loop (n - 1);
    fun v -> if neg.(v) then Weight.neg_inf else d.(v)
end

module G = WeightedDirectedGraph (struct
  type t = int
  let zero = 0
  let inf = -123456789012345678
  let neg_inf = 123456789012345678
  let ( + ) = ( + )
  let compare x y = compare y x
end)

let () = Scanf.scanf "%d %d %d\n" @@ fun n m p ->
  let abc = Array.init m @@ fun _ ->
    Scanf.scanf "%d %d %d\n" @@ fun a b c -> a - 1, b - 1, c - p in
  let d = G.bellman_ford n { G.fold = fun f -> Array.fold_right f abc } 0 (n - 1) in
  if 123456789012345678 <= d
  then print_endline "-1"
  else Printf.printf "%d\n" @@ max 0 d


(* 辺は (from,to,cost) の組 *)
open Scanf
open Printf

type edge = int * int * int;;
let (n,m,p) = sscanf (read_line ()) "%d %d %f" (fun a b c -> (a,b,c));;
let rec input = function
  | 0 -> []
  | t -> (sscanf (read_line ()) "%d %d %f" (fun a b c-> (a-1,b-1, -.(c -. p)))) :: input(t-1);;

let dist = Array.make n infinity;;
dist.(0) <- 0.0;;
let edges = input m;;
let loop_flag = ref false;;
let n_count_value = ref 0.0;;

let _ =
for i = 0 to 2 * n do
    if i = n - 1 then n_count_value := dist.(n-1) else ();
    List.iter (fun x ->
      let (f,t,c) = x in
      if (dist.(t) > dist.(f) +. c) then
        let _ = dist.(t) <-  dist.(f) +. c in
        if (i = n-1) && ((t == n-1) || (f == n-1)) then
          (*(printf "Loop found ! edge = f:%d t:%d") f t *)
          loop_flag := true
        else ()
      else ()
    ) edges
done;;

let _ =
if dist.(n-1) = infinity || int_of_float !n_count_value != int_of_float dist.(n-1) then
  printf "%d\n" (-1)
else
  printf "%d\n" (max 0 (int_of_float (-.dist.(n-1))));;


(* 辺は (from,to,cost) の組 *)
open Scanf
open Printf

type edge = int * int * int;;
let (n,m,p) = sscanf (read_line ()) "%d %d %f" (fun a b c -> (a,b,c));;
let rec input = function
  | 0 -> []
  | t -> (sscanf (read_line ()) "%d %d %f" (fun a b c-> (a-1,b-1, -.(c -. p)))) :: input(t-1);;

let dist = Array.make n infinity;;
dist.(0) <- 0.0;;
let edges = input m;;
let loop_flag = ref false;;

let _ =
for i = 0 to (n-1) do
    List.iter (fun x ->
      let (f,t,c) = x in
      if (dist.(t) > dist.(f) +. c) then
        let _ = dist.(t) <-  dist.(f) +. c in
        if (i = n-1) && ((t == n-1) || (f == n-1)) then
          (*(printf "Loop found ! edge = f:%d t:%d") f t *)
          loop_flag := true
        else ()
      else ()
    ) edges
done;;

let _ =
if !loop_flag || dist.(n-1) = infinity then
  printf "%d\n" (-1)
else
  printf "%d\n" (max 0 (int_of_float (-.dist.(n-1))));;


(* 辺は (from,to,cost) の組 *)
open Scanf
open Printf

type edge = int * int * int;;
let (n,m,p) = sscanf (read_line ()) "%d %d %f" (fun a b c -> (a,b,c));;
let rec input = function
  | 0 -> []
  | t -> (sscanf (read_line ()) "%d %d %f" (fun a b c-> (a-1,b-1, -.(c -. p)))) :: input(t-1);;

let dist = Array.make n infinity;;
dist.(0) <- 0.0;;
let edges = input m;;
let loop_flag = ref false;;

let _ =
for i = 0 to (n-1) do
    List.iter (fun x ->
      let (f,t,c) = x in
      if (dist.(t) > dist.(f) +. c) then
        let _ = dist.(t) <-  dist.(f) +. c in
        if (i = n-1) && ((t == n-1) || (f == n-1)) then
          (*(printf "Loop found ! edge = f:%d t:%d") f t *)
          loop_flag := true
        else ()
      else ()
    ) edges
done;;

let _ =
if !loop_flag then
  printf "%d\n" (-1)
else
  printf "%d\n" (max 0 (int_of_float (-.dist.(n-1))));;


(* 辺は (from,to,cost) の組 *)
open Scanf
open Printf

type edge = int * int * int;;
let (n,m,p) = sscanf (read_line ()) "%d %d %f" (fun a b c -> (a,b,c));;
let rec input = function
  | 0 -> []
  | t -> (sscanf (read_line ()) "%d %d %f" (fun a b c-> (a-1,b-1, -.(c -. p)))) :: input(t-1);;

let dist = Array.make n infinity;;
dist.(0) <- 0.0;;
let edges = input m;;
let loop_flag = ref false;;

let _ =
for i = 0 to (n-1) do
    List.iter (fun x ->
      let (f,t,c) = x in
      if (dist.(t) > dist.(f) +. c) then
        let _ = dist.(t) <-  dist.(f) +. c in
        if (i = n-1) && (t == n-1) then
          (*(printf "Loop found ! edge = f:%d t:%d") f t *)
          loop_flag := true
        else ()
      else ()
    ) edges
done;;

let _ =
if !loop_flag then
  printf "%d\n" (-1)
else
  printf "%d\n" (max 0 (int_of_float (-.dist.(n-1))));;


open Scanf
open Printf

let iota n : int list =
  let rec f n ans = if n = 0 then ans else f (n - 1) ((n - 1) :: ans) in
  f n []

let () =
  let n, m, p = scanf " %d %d %d" (fun a b c -> a, b, c) in
  let es = Array.init m @@ fun _ -> scanf " %d %d %d" @@ fun a b c -> (a - 1), (b - 1), c - p in
  let inf = max_int / 4 in
  let dist = Array.make n (-inf) in
  let from_s = Array.make n false in
  let from_t = Array.make n false in
  dist.(0) <- 0;
  from_s.(0) <- true;
  from_t.(n - 1) <- true;
  for _ = 0 to n do
    es |> Array.iter @@ fun (a, b, c) ->
      dist.(b) <- max dist.(b) (dist.(a) + c);
      from_s.(b) <- from_s.(b) || from_s.(a);
      from_t.(a) <- from_t.(a) || from_t.(b)
  done;
  let tmp = Array.copy dist in
  for _ = 0 to n do
    es |> Array.iter @@ fun (a, b, c) ->
      dist.(b) <- max dist.(b) (dist.(a) + c);
  done;
  if (iota n |> List.exists (fun i -> from_s.(i) && from_t.(i) && dist.(i) <> tmp.(i))) then
    printf "-1\n"
  else
    printf "%d\n" @@ max 0 dist.(n - 1);


(* Vicfred
 * https://atcoder.jp/contests/abc136/tasks/abc136_c
 * greedy
 * *)
let n = Scanf.scanf "%d\n" ( + ) 0
let h = Array.init n @@ fun _ -> Scanf.scanf " %d" ( + ) 0
let maxima = ref @@ h.(0) - 1
let main =
    for i = 1 to n - 1 do
        if !maxima > h.(i) then ( print_endline "No"; exit 0);
        maxima := h.(i) - if !maxima < h.(i) then 1 else 0
    done;
    print_endline "Yes"

Score : 300 points

Problem Statement

There are N squares arranged in a row from left to right. The height of the i-th square from the left is H_i.

For each square, you will perform either of the following operations once:

Decrease the height of the square by 1.

Do nothing.

Determine if it is possible to perform the operations so that the heights of the squares are non-decreasing from left to right.

Constraints

All values in input are integers.

1 \leq N \leq 10^5

1 \leq H_i \leq 10^9

Input

Input is given from Standard Input in the following format:

N
H_1 H_2 ... H_N

Output

If it is possible to perform the operations so that the heights of the squares are non-decreasing from left to right, print Yes; otherwise, print No.

Sample Input 1

5
1 2 1 1 3

Sample Output 1

Yes

You can achieve the objective by decreasing the height of only the second square from the left by 1.

Sample Input 2

4
1 3 2 1

Sample Output 2

No

Sample Input 3

5
1 2 3 4 5

Sample Output 3

Yes

Sample Input 4

1
1000000000

Sample Output 4

Yes


let rec solution h i m =
    if i == Array.length h then "Yes"
    else if h.(i) < m then "No"
    else solution h (i+1) @@ max (h.(i)-1) m;;

Printf.printf "%s\n" @@
Scanf.scanf "%d\n" @@ fun n ->
    let h = Array.init n @@ fun _ -> Scanf.scanf "%d " ( + ) 0 in
    solution h 0 0;;


open Batteries
let n = read_int ()
let h_list = read_line () |> String.split_on_char ' ' |> List.map int_of_string

let rec pp lst last =
  match lst with
  | [] -> []
  | first :: rest when last = -1 -> (first-1) :: pp rest (first-1)
  | first :: rest -> if first > last then (first-1) :: pp rest (first-1) else first :: pp rest first

let rec check lst last =
  match lst with
  | [] -> true
  | first :: rest when last = -1 -> check rest first
  | first :: rest -> if first < last then false else check rest first

let _ = if check (pp h_list (-1)) (-1) then print_endline "Yes" else print_endline "No"


open Batteries
let n = read_int ()
let h_list = read_line () |> String.split_on_char ' ' |> List.map int_of_string

let rec pp lst last =
  match lst with
  | [] -> []
  | first :: rest when last = -1 -> first :: pp rest first
  | first :: rest -> if first > last then (first-1) :: pp rest first else first :: pp rest first

let rec check lst last =
  match lst with
  | [] -> true
  | first :: rest when last = -1 -> check rest first
  | first :: rest -> if first < last then false else check rest first

let _ = if check (pp h_list (-1)) (-1) then print_endline "Yes" else print_endline "No"


let n = Scanf.scanf " %d" (+) 0
let hs = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let p = ref @@ hs.(0) - 1
let _ = for i = 1 to n - 1 do if !p > hs.(i) then (print_endline "No"; exit 0); p := hs.(i) - if !p < hs.(i) then 1 else 0 done; print_endline "Yes"


let n = Scanf.scanf " %d" (+) 0
let hs = Array.init n @@ fun _ -> Scanf.scanf " %d" (+) 0
let p = ref hs.(n - 1)
let _ = for i = n - 1 downto 0 do p := hs.(i) - if hs.(i) > !p then if hs.(i) - !p >= 2 then (print_endline "No"; exit 0) else 1 else 0 done; print_endline "Yes"


open Printf
open Scanf

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

let is_sorted a =
  let ans = ref true in
  for i = 0 to Array.length a - 2 do
    if a.(i) > a.(i+1) then ans := false
  done;
  !ans

let () =
  let n = readint () in
  let a = Array.init n (fun _ -> readint ()) in
  a.(0) <- a.(0) - 1;
  for i = 1 to n - 1 do
    if a.(i-1) < a.(i) then
      a.(i) <- a.(i) - 1
  done;
  printf "%s\n" @@ if is_sorted a then "Yes" else "No"


let () = Scanf.scanf "%d\n" @@ fun n ->
  let hs = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun h -> h in
  print_endline @@
  match
    Array.fold_right (fun h (b, h') ->
      if h <= h'
      then (b, h)
      else (b && h - 1 <= h', h - 1)) hs (true, max_int)
  with
  | (true, _) -> "Yes"
  | (false, _) -> "No"


let () =
    let split s =
        let rec loop i cur flag acc =
            if i = String.length s then ( if flag then cur :: acc else acc) else (
                match flag, s.[i] with
                | true,  ' ' -> loop (i + 1) "" false (cur :: acc)
                | false, ' ' -> loop (i + 1) "" false acc
                | true,  v   -> loop (i + 1) (Printf.sprintf "%s%c" cur v) true acc
                | false, v   -> loop (i + 1) (Printf.sprintf "%s%c" cur v) true acc
            )
        in
        List.map int_of_string (List.rev (loop 0 "" false []))
    in
    let main () =
        let n = int_of_string (read_line ()) in
        let h = split (read_line ()) in
        let rec loop prev = function
            | [] -> "Yes"
            | hd :: tl -> if hd > prev + 1 then "No" else
                          if hd = prev + 1 then loop (hd - 1) tl else
                              loop hd tl
        in
        match List.rev h with
        | hd :: tl -> print_endline (loop hd tl)
        | [] -> failwith "??"

    in
    main ()


let rec for_fold a b v f = if a >= b then v else for_fold (a+1) b (f a v) f
let ans =
  Scanf.scanf "%d %d" @@ fun l r ->
  let l, r = l mod 2019, r mod 2019 in
  if l = 0 && r < l then 0 else
  for_fold l (r+1) max_int @@ fun i a ->
    for_fold (i+1) (r+1) a @@ fun j a -> min a (i * j mod 2019)
let () = Printf.printf "%d\n" ans

Score : 300 points

Problem Statement

You are given two non-negative integers L and R.
We will choose two integers i and j such that L \leq i < j \leq R.
Find the minimum possible value of (i \times j) \mbox{ mod } 2019.

Constraints

All values in input are integers.

0 \leq L < R \leq 2 \times 10^9

Input

Input is given from Standard Input in the following format:

L R

Output

Print the minimum possible value of (i \times j) \mbox{ mod } 2019 when i and j are chosen under the given condition.

Sample Input 1

2020 2040

Sample Output 1

2

When (i, j) = (2020, 2021), (i \times j) \mbox{ mod } 2019 = 2.

Sample Input 2

4 5

Sample Output 2

20

We have only one choice: (i, j) = (4, 5).


let modulo = 2019
let ( *% ) a b = (a * b) mod modulo

exception Zero

let () =
  let (l, r) = Scanf.sscanf (input_line stdin) "%d %d" (fun a b -> (a, b)) in
  let rec loop_l i min_i =
    if min_i = 0 then raise Zero
    else if i >= r then min_i else
      let rec loop_r j min_j =
        if min_j = 0 then raise Zero
        else if j > r then min_j
        else loop_r (j + 1) (min (i *% j) min_j) in
      loop_l (i + 1) (min (loop_r (i + 1) 2019) min_i)
  in
  let ans = try (if l - r > 2019 then 0
                 else loop_l l 2019)
            with Zero -> 0
  in
  print_int ans;
  print_newline ()


let modulo = 2019
let ( *% ) a b = (a * b) mod modulo

let () =
  let (l, r) = Scanf.sscanf (input_line stdin) "%d %d" (fun a b -> (a, b)) in
  let rec loop_l : int -> int = fun i ->
    if i > r then 2019 else
      let rec loop_r : int -> int = fun j ->
        if j > r then 2019
        else min (i *% j) (loop_r (j + 1)) in
      min (loop_r (i + 1)) (loop_l (i + 1))
  in
  let ans = if l - r > 2019 then 0
            else loop_l l in
  print_int ans;
  print_newline ()


let l, r = Scanf.scanf " %d %d" @@ fun a b -> a, b
let ans = ref max_int
let r = min r @@ l + 2019
let _ =
  for i = l to r do
    for j = i + 1 to r do
      ans := min !ans @@ i * j mod 2019 done done;
  Printf.printf "%d\n" !ans


let () = Scanf.scanf "%d %d" @@ fun l r ->
  Printf.printf "%d\n" @@
  if
    l = 0 ||
    1 <= r / 673 - (l - 1) / 673 &&
    1 <= r / 3 - (l - 1) / 3
  then 0
  else
    Array.fold_left (Array.fold_left min) max_int @@
    Array.init (r - l + 1) @@ fun i ->
      Array.init (r - l + 1) @@ fun j ->
        let i = i + l in
        let j = j + l in
        if j <= i
        then max_int
        else (i * j) mod 2019


let () =
    let main () =
        let l, r = Scanf.sscanf (read_line ()) "%d %d" (fun l r -> l, r) in
        let rec loop_l li count_l acc =
            let rec loop_r rj count_r acc =
                if rj > r || count_r = 2019 then acc else
                    loop_r (rj + 1) (count_r + 1) (min acc ((li * rj) mod 2019))
            in
            if li = r || count_l = 2019 then acc else
                loop_l (li + 1) (count_l + 1) (loop_r (li + 1) 0 acc)
        in
        Printf.printf "%d\n" (loop_l l 0 2019)
    in
    main ()


let split_string ?(pattern="") = Str.split @@ Str.regexp pattern
let ($) f g = fun x -> g (f x)

let s = read_line ()
  |> Str.global_replace (Str.regexp "A") "x"
  |> Str.global_replace (Str.regexp "BC") "y"
  |> Str.split (Str.regexp "[^xy]+")
  |> List.map (split_string $ List.rev)

let rec f pos x_cnt sum = function
  | "x" :: xs -> f (pos + 1) (x_cnt + 1) (sum + pos - x_cnt) xs
  | "y" :: ys -> f (pos + 1) x_cnt sum ys
  | _ -> sum

let () = List.map (f 0 0 0) s |> List.fold_left (+) 0 |> Printf.printf "%d\n"

Score : 600 points

Problem Statement

You are given a string s consisting of A, B and C.

Snuke wants to perform the following operation on s as many times as possible:

Choose a contiguous substring of s that reads ABC and replace it with BCA.

Find the maximum possible number of operations.

Constraints

1 \leq |s| \leq 200000

Each character of s is A, B and C.

Input

Input is given from Standard Input in the following format:

s

Output

Find the maximum possible number of operations.

Sample Input 1

ABCABC

Sample Output 1

3

You can perform the operations three times as follows: ABCABC → BCAABC → BCABCA → BCBCAA. This is the maximum result.

Sample Input 2

C

Sample Output 2

0

Sample Input 3

ABCACCBABCBCAABCB

Sample Output 3

6


let () =
  let s = read_line () in
  Printf.printf "%d\n" @@
  fst @@
  Array.fold_left (fun (acc, s) c ->
    match s, c with
    | `A n, 'A' -> (acc, `A (n + 1))
    | `AB _, 'A' -> (acc, `A 1)
    | `A n, 'B' -> (acc, `AB n)
    | `AB n, 'C' -> (acc + n, `A n)
    | _ -> (acc, `A 0)) (0, `A 0) @@
  Array.init (String.length s) (String.get s)


let s = Str.global_replace (Str.regexp "BC") "D" @@ read_line ()
let rec f acc bc i =
  if i < 0 then acc
  else if s.[i] = 'A' then f (acc + bc) bc (i - 1)
  else if s.[i] = 'D' then f acc (bc + 1) (i - 1)
  else f acc 0 (i - 1)
let _ = f 0 0 @@ String.length s - 1 |> Printf.printf "%d\n"


let s = read_line ()
let rec f acc bc i =
  if i < 0 then acc
  else if s.[i] = 'A' then f (acc + bc) bc (i - 1)
  else if i = 0 then acc
  else if s.[i - 1] = 'B' && s.[i] = 'C' then f acc (bc + 1) (i - 2)
  else f acc 0 (i - 1)
let _ = f 0 0 @@ String.length s - 1 |> Printf.printf "%d\n"


(* O(|s|) *)
let s = read_line () in
let n = String.length s in
let rec find acc bc i =
  if i < 0 then acc
  else if i >= 1 && s.[i - 1] = 'B' && s.[i] = 'C' then find acc (bc + 1) @@ i - 2
  else if s.[i] = 'A' then find (acc + bc) bc @@ i - 1
  else find acc 0 @@ i - 1 in
find 0 0 @@ n - 1 |> Printf.printf "%d\n"


(* O(|s|) *)
let s = read_line () in
let n = String.length s in
let f i =
  let rec loop_a a j =
    if j >= n then a
    else if s.[j] <> 'A' then a
    else loop_a (a + 1) (j + 1) in
  let rec loop_bc bc j =
    if j >= n - 1 then bc
    else if s.[j] <> 'B' || s.[j + 1] <> 'C' then bc
    else loop_bc (bc + 1) (j + 2) in
  let a = loop_a 0 i in
  if a = 0 then 0, 0, i + 1
  else
    let bc = loop_bc 0 (i + a) in
    if bc = 0 then 0, 0, i + a + 1
    else a, bc, i + a + 2 * bc in
let rec find acc a0 i =
  if i >= n then acc
  else
    let a, bc, j = f i in
    if a = 0 then find acc 0 j
    else
      let a1 = a0 + a in
      find (acc + a1 * bc) a1 j in
find 0 0 0 |> Printf.printf "%d\n"


let id x = x
let split_string ?(pattern="") = Str.split @@ Str.regexp pattern

let (h, w) = Scanf.scanf "%d %d\n" @@ fun h w -> (h, w)
let a = Array.init h (fun _ -> Array.of_list (split_string (Scanf.scanf "%s\n" id)))

let da = Array.init h @@ fun x -> Array.init w @@ fun y -> if a.(x).(y) = "#" then 0 else max_int

let que = Queue.create ()

let add x y d =
  List.iter (fun (x, y) ->
    if 0 <= x && x < h && 0 <= y && y < w && da.(x).(y) > d then Queue.add (x, y, d) que
  ) [(x + 1, y); (x - 1, y); (x, y + 1); (x, y - 1)]

let () =
  for x = 0 to (h - 1) do
    for y = 0 to (w - 1) do
      if da.(x).(y) = 0 then
        add x y 1
    done
  done;
  while not (Queue.is_empty que) do
    let (x, y, d) = Queue.pop que in
    if da.(x).(y) > d then begin
      da.(x).(y) <- d;
      add x y (d + 1)
    end
  done;
  print_int @@ Array.fold_left max 0 @@ Array.map (Array.fold_left max 0) da

Score : 300 points

Problem Statement

You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black.
HW characters from A_{11} to A_{HW} represent the colors of the squares.
A_{ij} is # if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is . if that square is white.

We will repeatedly perform the following operation until all the squares are black:

Every white square that shares a side with a black square, becomes black.

Find the number of operations that will be performed.
The initial grid has at least one black square.

Constraints

1 \leq H,W \leq 1000

A_{ij} is # or ..

The given grid has at least one black square.

Input

Input is given from Standard Input in the following format:

H W
A_{11}A_{12}...A_{1W}
:
A_{H1}A_{H2}...A_{HW}

Output

Print the number of operations that will be performed.

Sample Input 1

3 3
...
.#.
...

Sample Output 1

2

After one operation, all but the corners of the grid will be black. After one more operation, all the squares will be black.

Sample Input 2

6 6
..#..#
......
#..#..
......
.#....
....#.

Sample Output 2

3


let id x = x
let split_string ?(pattern="") = Str.split @@ Str.regexp pattern

let (h, w) = Scanf.scanf "%d %d\n" @@ fun h w -> (h, w)
let a = Array.init h (fun _ -> Array.of_list (split_string (Scanf.scanf "%s\n" id)))

let da = Array.init h @@ fun x -> Array.init w @@ fun y -> if a.(x).(y) = "#" then 0 else max_int

let rec f arr x y d =
  if 0 <= x && x < h && 0 <= y && y < w then
    if arr.(x).(y) >= d then begin
      arr.(x).(y) <- d;
      f arr (x + 1) y (d + 1);
      f arr (x - 1) y (d + 1);
      f arr x (y + 1) (d + 1);
      f arr x (y - 1) (d + 1);
    end

let () =
  for x = 0 to (h - 1) do
    for y = 0 to (w - 1) do
      if da.(x).(y) = 0 then f da x y 0
    done
  done;
  print_int @@ Array.fold_left max 0 @@ Array.map (Array.fold_left max 0) da


Scanf.sscanf (read_line ()) "%d %d" (fun h w ->
    let a = Array.init h (fun _ -> Bytes.of_string @@ read_line ()) in
    let rec loop_y y acc =
        let rec loop_x x acc =
            if x < 0 then acc else loop_x (x - 1) (if Bytes.get a.(y) x = '#' then (x, y) :: acc else acc)
        in
        if y < 0 then acc else loop_y (y - 1) (loop_x (w - 1) acc)
    in

    let rec bfs step next = function
        | [] -> if next = [] then step - 1 else bfs (step + 1) [] next
        | (x, y) :: tl ->
                let next = if x > 0     && Bytes.get a.(y) (x - 1) = '.' then (Bytes.set a.(y) (x - 1) '#'; (x - 1, y) :: next) else next in
                let next = if y > 0     && Bytes.get a.(y - 1) (x) = '.' then (Bytes.set a.(y - 1) (x) '#'; (x, y - 1) :: next) else next in
                let next = if x < w - 1 && Bytes.get a.(y) (x + 1) = '.' then (Bytes.set a.(y) (x + 1) '#'; (x + 1, y) :: next) else next in
                let next = if y < h - 1 && Bytes.get a.(y + 1) (x) = '.' then (Bytes.set a.(y + 1) (x) '#'; (x, y + 1) :: next) else next in
                bfs step next tl
    in
    bfs 1 [] (loop_y (h - 1) []) |> Printf.printf "%d\n"
)


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

Scanf.sscanf (read_line ()) "%d %d" (fun h w ->
    let a = Array.init h (fun _ -> Bytes.of_string @@ read_line ()) in
    let rec loop_y y acc =
        let rec loop_x x acc =
            if x < 0 then acc else loop_x (x - 1) (if Bytes.get a.(y) x = '#' then (x, y) :: acc else acc)
        in
        if y < 0 then acc else loop_y (y - 1) (loop_x (w - 1) acc)
    in

    let rec bfs step next = function
        | [] -> if S.is_empty next then step - 1 else bfs (step + 1) S.empty (S.elements next)
        | (x, y) :: tl ->
                let next = if x > 0     && Bytes.get a.(y) (x - 1) = '.' then (Bytes.set a.(y) (x - 1) '#'; S.add (x - 1, y) next) else next in
                let next = if y > 0     && Bytes.get a.(y - 1) (x) = '.' then (Bytes.set a.(y - 1) (x) '#'; S.add (x, y - 1) next) else next in
                let next = if x < w - 1 && Bytes.get a.(y) (x + 1) = '.' then (Bytes.set a.(y) (x + 1) '#'; S.add (x + 1, y) next) else next in
                let next = if y < h - 1 && Bytes.get a.(y + 1) (x) = '.' then (Bytes.set a.(y + 1) (x) '#'; S.add (x, y + 1) next) else next in
                bfs step next tl
    in
    bfs 1 S.empty (loop_y (h - 1) []) |> Printf.printf "%d\n"
)


let () =
  let (h, w) = Scanf.scanf "%d %d" (fun a b -> (a, b)) in
  let queue = Queue.create () in
  let dp = Array.make_matrix h w 0 in
  let field = Array.init h @@ fun i -> Array.init w @@
    fun j -> Scanf.scanf "%c"
      (fun c -> if c == '#' then Queue.push (i,j) queue; c)
  in
  let count = ref 0 in
  while not @@ Queue.is_empty queue do
    let (i,j) = Queue.pop queue in
    List.iter (fun (y, x) ->
        count := dp.(i).(j) + 1;
        dp.(y).(x) <- !count;
        Queue.push (y,x) queue;
        field.(y).(x) <- '#'
      ) @@
    List.filter (fun (y, x) -> y >= 0 && y < h && x >= 0 && x < w && field.(y).(x) == '.') [(i+1,j);(i-1,j);(i,j+1);(i,j-1)];
  done;
  Printf.printf "%d\n" !count


let () =
  let (h, w) = Scanf.scanf "%d %d" (fun a b -> (a, b)) in
  let queue = Queue.create () in
  let dp = Array.make_matrix h w 0 in
  let field = Array.init h @@ fun i -> Array.init w @@
    fun j -> Scanf.scanf "%c"
      (fun c -> if c == '#' then Queue.push (i,j) queue; c)
  in
  let count = ref 0 in
  while not @@ Queue.is_empty queue do
    let (i,j) = Queue.pop queue in
    List.iter (fun (y, x) ->
        count := dp.(i).(j);
        dp.(y).(x) <- !count + 1;
        Queue.push (y,x) queue;
        field.(y).(x) <- '#'
      ) @@
    List.filter (fun (y, x) -> y >= 0 && y < h && x >= 0 && x < w && field.(y).(x) == '.') [(i+1,j);(i-1,j);(i,j+1);(i,j-1)];
  done;
  Printf.printf "%d\n" !count


(* O(h w) *)
let h, w = Scanf.scanf " %d %d" @@ fun a b -> a, b
let q = Queue.create ()
let ds = Array.make_matrix h w @@ -1
let a_ss = Array.init h @@ fun i -> Array.init w @@ fun j -> Scanf.scanf " %c" @@ fun a ->
  if a = '#' then (ds.(i).(j) <- 0; Queue.push (i, j) q); a
let ans = ref 0
let _ =
  while not @@ Queue.is_empty q do
    let y0, x0 = Queue.pop q in
    let f (dy, dx) =
      let y, x = y0 + dy, x0 + dx in
      if 0 <= y && y < h && 0 <= x && x < w && ds.(y).(x) = -1 then
        (ans := ds.(y0).(x0) + 1; ds.(y).(x) <- !ans; Queue.push (y, x) q) in
    List.iter f [-1, 0; 0, -1; 1, 0; 0, 1]
  done;
  Printf.printf "%d\n" !ans


let kInf = 1010101
let h, w = Scanf.scanf " %d %d" @@ fun a b -> a, b
let q = Queue.create ()
let ds = Array.make_matrix h w kInf
let a_ss = Array.init h @@ fun i -> Array.init w @@ fun j -> Scanf.scanf " %c" @@ fun a ->
  if a = '#' then (ds.(i).(j) <- 0; Queue.push (i, j) q); a
let _ =
  while not @@ Queue.is_empty q do
    let y0, x0 = Queue.pop q in
    let f (dy, dx) =
      let y, x = y0 + dy, x0 + dx in
      if 0 <= y && y < h && 0 <= x && x < w && ds.(y).(x) > ds.(y0).(x0) + 1 then
        (ds.(y).(x) <- ds.(y0).(x0) + 1; Queue.push (y, x) q) in
    List.iter f [-1, 0; 0, -1; 1, 0; 0, 1]
  done;
  Array.fold_left (Array.fold_left max) 0 ds |> Printf.printf "%d\n"


let () = Scanf.scanf "%d %d\n" @@ fun h w ->
  let ass = Array.init h @@ fun _ -> Scanf.scanf "%s\n" @@ fun s -> s in
  let rec bfs n ijs =
    match
      List.fold_left (fun (b, ijs) (i, j) ->
        if
          i < 0 || h <= i ||
          j < 0 || w <= j ||
          ass.(i).[j] = '#'
        then (b, ijs)
        else begin
          ass.(i).[j] <- '#';
          (false, (i - 1, j) :: (i + 1, j) :: (i, j - 1) :: (i, j + 1) :: ijs)
        end) (true, []) ijs
    with
    | (true, _) -> n
    | (false, ijs) -> bfs (n + 1) ijs in
  Printf.printf "%d\n" @@ bfs 0 @@
  List.concat @@ Array.to_list @@ Array.init h @@ fun i ->
    List.concat @@ Array.to_list @@ Array.init w @@ fun j ->
      if
        ass.(i).[j] = '#' ||
        List.for_all (fun (i, j) ->
          i < 0 || h <= i ||
          j < 0 || w <= j ||
          ass.(i).[j] = '.')
        [(i - 1, j); (i + 1, j); (i, j - 1); (i, j + 1)]
      then []
      else [(i, j)]


let () = Scanf.scanf "%d %d\n" @@ fun h w ->
  let ass = Array.init h @@ fun _ -> Scanf.scanf "%s\n" @@ fun s -> s in
  let rec bfs n ijs =
    match
      List.fold_left (fun (b, ijs) (i, j) ->
        if
          i < 0 || h <= i ||
          j < 0 || w <= j ||
          ass.(i).[j] = '#'
        then (b, ijs)
        else begin
          ass.(i).[j] <- '#';
          (false, (i - 1, j) :: (i + 1, j) :: (i, j - 1) :: (i, j + 1) :: ijs)
        end) (true, []) ijs
    with
    | (true, _) -> n
    | (false, ijs) -> bfs (n + 1) ijs in
  Printf.printf "%d\n" @@ bfs 0 @@
  List.concat @@ Array.to_list @@ Array.init h @@ fun i ->
    List.concat @@ Array.to_list @@ Array.init w @@ fun j ->
      if ass.(i).[j] = '.'
      then []
      else [(i - 1, j); (i + 1, j); (i, j - 1); (i, j + 1)]


module PQ = Set.Make(struct
  type t = int * int * int
  let compare (d0,x0,y0) (d1,x1,y1) =
    if d0 <> d1 then d0-d1 else if x0 <> x1 then x0-x1 else y0-y1
end)

let () =
  Scanf.scanf "%d %d" @@ fun h w ->
  let a = Array.init h (fun _ -> Scanf.scanf " %s" (fun s -> s)) in
  let a = Array.mapi (fun i s -> Array.init w (fun j -> i, j, s.[j])) a in

  let pq0 =
    Array.fold_left (Array.fold_left
      (fun pq (i,j,c) -> if c = '#' then PQ.add (0,i,j) pq else pq)) PQ.empty a
  in

  let c = Array.init h (fun _ -> Array.make w max_int) in
  PQ.iter (fun (_,x,y) -> c.(x).(y) <- 0) pq0;

  let rec loop pq =
    if PQ.is_empty pq then () else
    let (d,x,y) = PQ.min_elt pq in
    let pq = PQ.remove (d,x,y) pq in
    if d > c.(x).(y) then loop pq else
    [(1,0); (0,1); (-1,0); (0,-1)] |> List.fold_left (fun pq (dx,dy) ->
      let x', y' = x+dx, y+dy in
      if x' < 0 || h <= x' || y' < 0 || w <= y' || d+1 >= c.(x').(y') then pq
      else begin
        c.(x').(y') <- d+1;
        PQ.add (d+1,x',y') pq
      end
    ) pq |> loop
  in
  loop pq0;

  Array.fold_left (Array.fold_left max) 0 c
  |> Printf.printf "%d\n"


open Batteries
(* a と b の最大公約数を返す関数 *)
let rec gcd a b =
  match b with
  | 0 -> a
  | _ -> gcd b (a mod b)
(* 素数かどうか *)
let is_prime n =
  let rec judge n' i =
    match i with
    | i when n' < i * i -> true
    | i -> if n' mod i = 0 then false else judge n' (i+1)
  in judge n 2
let n = read_int ()
let a = read_line () |> String.split_on_char ' ' |> List.map int_of_string
let get_gcd l =
  let rec loop lst hd =
    match lst with
    | [] -> hd
    | first :: rest -> gcd first (loop rest hd)
  in loop (List.tl l) (List.hd l)

let rec loop old lst =
  match lst with
  | [] -> min_int
  | first :: rest ->
    max (get_gcd @@ old @ rest) (loop (first::old) (rest))

let _ = Printf.printf "%d\n" @@ loop [] a

Score : 300 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, written on the blackboard.

You will choose one of them and replace it with an integer of your choice between 1 and 10^9 (inclusive), possibly the same as the integer originally written.

Find the maximum possible greatest common divisor of the N integers on the blackboard after your move.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Output

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible greatest common divisor of the N integers on the blackboard after your move.

Sample Input 1

3
7 6 8

Sample Output 1

2

If we replace 7 with 4, the greatest common divisor of the three integers on the blackboard will be 2, which is the maximum possible value.

Sample Input 2

3
12 15 18

Sample Output 2

6

Sample Input 3

2
1000000000 1000000000

Sample Output 3

1000000000

We can replace an integer with itself.


(* O(n log(max a_s)) *)
let n = Scanf.scanf " %d" @@ (+) 0
let a_s = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let gcds = Array.make_matrix 2 (n + 1) 0
let rec gcd a b = if b = 0 then a else gcd b (a mod b)
let ans = ref 0
let _ =
  Array.iteri (fun i a -> gcds.(0).(i + 1) <- gcd gcds.(0).(i) a) a_s;
  Array.iteri (fun i a -> gcds.(1).(n - i - 1) <- gcd gcds.(1).(n - i) a_s.(n - i - 1)) a_s;
  for i = 0 to n - 1 do
    ans := max !ans @@ gcd gcds.(0).(i) gcds.(1).(i + 1)
  done;
  Printf.printf "%d\n" !ans


let rec gcd a b = if b = 0 then a else gcd b (a mod b)
let () =
  let n = Scanf.scanf "%d\n" (fun x -> x) in
  let lst = Array.to_list (Array.init n (fun _ -> Scanf.scanf "%d " (fun x -> x))) in
  let buf_lst = (List.tl lst) @ [List.hd lst] in
  let ans_lst = List.map2 (fun a b -> gcd a b) lst buf_lst in
  Printf.printf "%d\n" (List.fold_left max min_int ans_lst)


open Printf open Scanf
open Array

let rec gcd m n = match m,n with | m,0 -> m | m,n -> gcd n (m mod n)

module SegTree_tmp = struct
  module type S = sig
    type t
    val  op: t -> t -> t
    val ide: t
    val upd: t -> t -> t
  end
  let par i = (i-1)/2
  let chl i = 2*i+1
  let chr i = 2*i+2
  module Make (X:S) = struct
    type t = SegTree of (X.t array * int)
    let raw (SegTree (a,_)) = a
    let make raw = (* O(n) *)
      let ln = Array.length raw in
      let n =
        let n = ref 1 in
        while !n<ln do n := !n*2 done; !n in
      let a = Array.make (2*n-1) X.ide in
      for i=0 to ln-1 do
        a.(i+n-1) <- raw.(i) done;
      for i=n-2 downto 0 do
        a.(i) <- X.op a.(chl i) a.(chr i) done;
      SegTree (a,n)
    let update_destructive (SegTree(a,n)) i v =
      let i = ref @@ i+(n-1) in
      a.(!i) <- X.upd a.(!i) v;
      while !i>0 do
        i := par !i;
        a.(!i) <- X.op a.(chl !i) a.(chr !i) done
    let get_half_open (SegTree(a,n)) l r = (* O(logn), [l,r) *)
      let rec f0 i p q =
        if q<=l || r<=p then X.ide
        else if l<=p && q<=r then a.(i)
        else
          let vl = f0 (2*i+1) p ((p+q)/2) in
          let vr = f0 (2*i+2) ((p+q)/2) q in
          X.op vl vr
      in f0 0 0 n
    let get_closed seg l r = get_half_open seg l (r+1) (* [l,r] *)
  end
end

module ST = SegTree_tmp.Make(struct
  type t = int
  let op = gcd
  let ide = 0
  let upd _prev nw = nw
end)

let () = scanf " %d" @@ fun n ->
  let a = init n (fun _ -> scanf " %d" @@ fun v -> v) in
  let t = ST.make a in
  mapi (fun i _ ->
    let l = if i=0 then 0 else ST.get_closed t 0 (i-1) in
    let r = if i=n-1 then 0 else ST.get_closed t (i+1) (n-1)
    in gcd l r
  ) a
  |> fold_left max 0
  |> print_int


open Printf open Scanf
open Array

let rec gcd m n = match m,n with | m,0 -> m | m,n -> gcd n (m mod n)

let print_array f a = Array.iter (fun v -> printf "%s " @@ f v) a; print_newline ()

let () = scanf " %d" @@ fun n ->
  let a = init n (fun _ -> scanf " %d" @@ fun v -> v) in
  let lr = make n a.(0) in
  let rl = make n a.(n-1) in
  for i=1 to n-1 do
    lr.(i) <- gcd lr.(i-1) a.(i)
  done;
  for i=n-2 downto 0 do
    rl.(i) <- gcd rl.(i+1) a.(i)
  done;
  (* print_array string_of_int lr;
  print_array string_of_int rl; *)
  init n (fun i ->
    let w =
      if i=0 then rl.(1)
      else if i=n-1 then lr.(n-2)
      else gcd rl.(i+1) lr.(i-1)
    in w)
  |> fold_left max 0
  |> print_int


let rec gcd m n =
  if m = n then m
  else if m > n then gcd n m
  else gcd (n - m) m

let gcd_of_list ls =
  let init = List.hd ls in
  List.fold_left (fun acc l -> gcd acc l) init ls

let solve n a =
  let rec inner acc i =
    if i = n - 1 then acc
    else
      let tmp = ref [] in
      for j = 0 to n - 1 do
        if j <> i then tmp := a.(j)::!tmp;
      done;
      inner (max acc @@ gcd_of_list !tmp) (i + 1)
  in inner 0 0

let _ =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let a = Array.make n 0 in
  for i = 0 to n - 1 do
    Scanf.scanf (if i <> n - 1 then "%d " else "%d\n") (fun a' -> a.(i) <- a')
  done;
  solve n a
  |> print_int


let rec gcd a b = if b = 0 then a else gcd b (a mod b)
let () =
  Scanf.scanf "%d" @@ fun n ->
  let a = Array.init n (fun _ -> Scanf.scanf " %d" ((+) 0)) in
  let l = Array.init n (fun i -> a.(i)) in
  for i = 1 to n-1 do l.(i) <- gcd a.(i) l.(i-1) done;

  let r = Array.init n (fun i -> a.(i)) in
  for i = n-2 downto 0 do r.(i) <- gcd a.(i) r.(i+1) done;

  Array.init n (fun i ->
    if i = 0 then r.(1) else if i = n-1 then l.(n-2)
    else gcd l.(i-1) r.(i+1))
  |> Array.fold_left max 0
  |> Printf.printf "%d\n"


let rec gcd n m =
  if m = 0 then n
  else gcd m (n mod m)

let () = Scanf.scanf "%d\n" @@ fun n ->
  let as_ = Array.init n @@ fun _ -> Scanf.scanf "%d " @@ fun a -> a in
  let acc = Array.make (n + 1) 0 in
  let acc' = Array.make (n + 1) 0 in
  for i = 0 to n - 1 do
    acc.(i + 1) <- gcd acc.(i) as_.(i)
  done;
  for i = n - 1 downto 0 do
    acc'.(i) <- gcd acc'.(i + 1) as_.(i)
  done;
  Printf.printf "%d\n" @@
  Array.fold_left max min_int @@
  Array.init n @@ fun i -> gcd acc.(i) acc'.(i + 1)


let () = Scanf.scanf "%d %d %d" @@ fun a b c -> Printf.printf "%d\n" @@ min (b / a) c

Score : 100 points

Problem Statement

Takahashi likes the sound when he buys a drink from a vending machine.

That sound can be heard by spending A yen (the currency of Japan) each time.

Takahashi has B yen. He will hear the sound as many times as he can with that money, but at most C times, as he would be satisfied at that time.

How many times will he hear the sound?

Constraints

All values in input are integers.

1 \leq A, B, C \leq 100

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the number of times Takahashi will hear his favorite sound.

Sample Input 1

2 11 4

Sample Output 1

4

Since he has not less than 8 yen, he will hear the sound four times and be satisfied.

Sample Input 2

3 9 5

Sample Output 2

3

He may not be able to be satisfied.

Sample Input 3

100 1 10

Sample Output 3

0


let favorite_sound a b c =
  if b / a > c then c else b / a

let () = Scanf.scanf "%d %d %d" favorite_sound |> Printf.printf "%d\n"


Scanf.scanf"%d %d %d"@@fun a b c->Printf.printf"%d"@@if a*c<b then c else b/a


open Printf
open Scanf

let solve a b c = min (b / a) c

let () =
  scanf "%d %d %d " solve |> printf "%d\n"


let a, b, c = Scanf.scanf " %d %d %d" @@ fun a b c -> a, b, c
let _ = Printf.printf "%d\n" @@ min c @@ b / a


    let f a b c = (min (b/a) c);;
    let () = Scanf.scanf "%d %d %d" f
    |> Printf.printf "%d\n"


    let f a b c = (min (a/b) c);;
    let () = Scanf.scanf "%d %d %d" f
    |> Printf.printf "%d\n"


let f a b c = (min a (b*c))/b;;
let () = Scanf.scanf "%d %d %d" f
|> Printf.printf "%d\n"


(* O(1) *)
let solve a b c = min (b / a) c

let _ = Scanf.scanf "%d %d %d" (fun a b c -> solve a b c) |> string_of_int |> print_endline


let () =
  Scanf.scanf "%d %d %d\n"
    (fun a b c ->
       if a * c <= b then c
       else b/a)
|> print_int


let () =
  let (a, b, c) = Scanf.scanf "%d %d %d" (fun a b c -> (a, b, c)) in
  let n = b / a in
  (if n < c then
    n
  else c) |> string_of_int |> print_endline


let solve a b c =
  let n = b / a in
  min n c

let _ =
  let a, b, c = Scanf.scanf "%d %d %d" (fun a b c -> (a, b, c)) in
  print_int @@ solve a b c


let () = Scanf.scanf "%d %d %d" @@ fun a b c ->
  Printf.printf "%d\n" @@ min c (b / a)


Scanf.scanf "%d %d %d" @@ fun a b c -> min c (b / a) |> Printf.printf "%d\n"


open Batteries
let n = read_int ()
let h = Array.init n (fun a -> Scanf.scanf " %d" @@ fun b -> b)

let dp = Array.init 100010 @@ fun a -> max_int
let _ = dp.(0) <- 0

let change i w =
  if dp.(i) > dp.(i-w) + (abs @@ h.(i) - h.(i-w)) then dp.(i) <- dp.(i-w) + (abs @@ h.(i) - h.(i-w))

let rec loop i =
  if i >= n then dp.(n-1) else (
    change i 1;
    if i > 1 then change i 2 else ();
    loop (i+1)
    )

let _ = Printf.printf "%d\n" @@ loop 1

Score : 100 points

Problem Statement

There are N stones, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), the height of Stone i is h_i.

There is a frog who is initially on Stone 1.
He will repeat the following action some number of times to reach Stone N:

If the frog is currently on Stone i, jump to Stone i + 1 or Stone i + 2. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.

Find the minimum possible total cost incurred before the frog reaches Stone N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq h_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 \ldots h_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

4
10 30 40 20

Sample Output 1

30

If we follow the path 1 → 2 → 4, the total cost incurred would be |10 - 30| + |30 - 20| = 30.

Sample Input 2

2
10 10

Sample Output 2

0

If we follow the path 1 → 2, the total cost incurred would be |10 - 10| = 0.

Sample Input 3

6
30 10 60 10 60 50

Sample Output 3

40

If we follow the path 1 → 3 → 5 → 6, the total cost incurred would be |30 - 60| + |60 - 60| + |60 - 50| = 40.


open Batteries
let n = read_int ()
let h = read_line () |> String.split_on_char ' ' |> List.map int_of_string |> Array.of_list

let rec loop i result =
  if i = n-1 then result else
  if i + 1 = n-1 then loop (i+1) (result + (abs @@ h.(i) - h.(i+1))) else
  min (loop (i+1) (result + (abs @@ h.(i) - h.(i+1)))) (loop (i+2) (result + (abs @@ h.(i) - h.(i+2))))

let _ = Printf.printf "%d\n" @@ loop 0 0


let rec solve (cost1, cost2) (h1, h2) hs =
    match hs with
    | h :: hs' ->
            let m = min (cost1 + abs (h - h1)) (cost2 + abs (h - h2)) in
            solve (cost2, m) (h2, h) hs'
    | [] -> cost2

let () =
    let _ = read_line () in
    let h =
        read_line ()
        |> Str.split (Str.regexp " ")
        |> List.map int_of_string
    in
    match h with
    | h1 :: h2 :: hs ->
            print_int (solve (0, abs (h2 - h1)) (h1, h2) hs);
            print_newline ()
    | _ -> ()


(* O(n) *)
let kInf = 1 lsl 60
let n = Scanf.scanf " %d" @@ (+) 0
let hs = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let dp = Array.make n kInf
let cost i j = abs @@ hs.(i) - hs.(j)
let _ =
  dp.(0) <- 0;
  for i = 0 to n - 2 do
    dp.(i + 1) <- min dp.(i + 1) @@ dp.(i) + cost i (i + 1);
    if i < n - 2 then dp.(i + 2) <- min dp.(i + 2) @@ dp.(i) + cost i (i + 2) done;
  Printf.printf "%d\n" dp.(n - 1)


(* O(n) *)
let n = Scanf.scanf " %d" @@ (+) 0
let hs = Array.init n @@ fun _ -> Scanf.scanf " %d" @@ (+) 0
let dp = Array.make n 0
let cost i j = abs @@ hs.(i) - hs.(j)
let _ =
  dp.(1) <- cost 0 1;
  for i = 2 to n - 1 do dp.(i) <- min (dp.(i - 1) + cost (i - 1) i) @@ dp.(i - 2) + cost (i - 2) i done;
  Printf.printf "%d\n" @@ dp.(n - 1)


let () =
  Scanf.scanf "%d" @@ fun n ->
  let h = Array.init n (fun _ -> Scanf.scanf " %d" ((+) 0)) in
  let dp = Array.make n max_int in
  dp.(0) <- 0;
  dp.(1) <- abs (h.(0) - h.(1));
  for i = 2 to n-1 do
    dp.(i) <-
      min (dp.(i-2) + abs (h.(i-2) - h.(i)))
          (dp.(i-1) + abs (h.(i-1) - h.(i)))
  done;
  Printf.printf "%d\n" dp.(n-1)