This is an interactive task.Dasha and NN like playing chess. While playing a match they decided that normal chess isn't interesting enough for them, so they invented a game described below.There are $$$666$$$ black rooks and $$$1$$$ white king on the chess board of size $$$999 \times 999$$$. The white king wins if he gets checked by rook, or, in other words, if he moves onto the square which shares either a row or column with a black rook.The sides take turns, starting with white. NN plays as a white king and on each of his turns he moves a king to one of the squares that are adjacent to his current position either by side or diagonally, or, formally, if the king was on the square $$$(x, y)$$$, it can move to the square $$$(nx, ny)$$$ if and only $$$\max (|nx - x|, |ny - y|) = 1$$$ , $$$1 \leq nx, ny \leq 999$$$. NN is also forbidden from moving onto the squares occupied with black rooks, however, he can move onto the same row or column as a black rook.Dasha, however, neglects playing by the chess rules, and instead of moving rooks normally she moves one of her rooks on any space devoid of other chess pieces. It is also possible that the rook would move onto the same square it was before and the position wouldn't change. However, she can't move the rook on the same row or column with the king.Each player makes $$$2000$$$ turns, if the white king wasn't checked by a black rook during those turns, black wins. NN doesn't like losing, but thinks the task is too difficult for him, so he asks you to write a program that will always win playing for the white king. Note that Dasha can see your king and play depending on its position.

In the beginning your program will receive $$$667$$$ lines from input. Each line contains two integers $$$x$$$ and $$$y$$$ ($$$1 \leq x, y \leq 999$$$) — the piece's coordinates. The first line contains the coordinates of the king and the next $$$666$$$ contain the coordinates of the rooks. The first coordinate denotes the number of the row where the piece is located, the second denotes the column. It is guaranteed that initially the king isn't in check and that all pieces occupy different squares.

After getting king checked, you program should terminate immediately without printing anything extra.

NoteThe example is trimmed. The full initial positions of the rooks in the first test are available at https://pastebin.com/qQCTXgKP. It is not guaranteed that they will behave as in the example.

Scanf.(Array.(scanf " %d %d" @@ fun x y ->
  let map = make_matrix 1000 1000 false in
  let rooks = make 666 (0,0) in
  init 666 (fun i ->
    scanf " %d %d" @@ fun x y ->
      (map.(x).(y) <- true; rooks.(i) <- x,y)
  ) |> ignore;
  let x,y = ref x,ref y in
  let rec move p q =
    if map.(!x+p).(!y+q) then (
      move p 0
    ) else (
      x := !x + p;
      y := !y + q;
      Printf.printf "%d %d\n%!" !x !y;
      let i,u,v = scanf " %d %d %d" @@ fun p q r -> p,q,r in
      if i=0 && u=0 && v=0 then exit 0 (* WA *)
      else if i= -1 && u= -1 && v= -1 then exit 0 (* AC *)
      else (
        let pu,pv = rooks.(i-1) in
        map.(pu).(pv) <- false;
        map.( u).( v) <- true;
        rooks.(i-1) <- u,v;
        Printf.eprintf "%d: %d,%d --> %d %d\n%!" i pu pv u v;
      )
    )
  in
  while !x <> 500 || !y <> 500 do
    if !x < 500 then move 1 0
    else if !x > 500 then move (-1) 0
    else if !y < 500 then move 0 1
    else if !y > 500 then move 0 (-1)
  done;
  let tr,tl,bl,br = fold_left (fun (p,q,r,s) (x,y) ->
    match x>500, y>500 with
    (* t/f: right/left, top/bottom *)
    |  true, true -> (p+1,q,r,s)
    | false, true -> (p,q+1,r,s)
    | false,false -> (p,q,r+1,s)
    |  true,false -> (p,q,r,s+1)
  ) (0,0,0,0) rooks
  in
  Printf.eprintf "%d; %d; %d; %d\n%!" tr tl bl br;
  let mn = fold_left min br [|tr;tl;bl|] in
  ignore @@ init 499 @@ fun _ ->
    if mn=tr then move (-1) (-1)
    else if mn=tl then move 1 (-1)
    else if mn=bl then move 1 1
    else move (-1) 1
))

open Printf
open String

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

let nrooks = (* 6 *) 666
let (maxx,maxy) = (* (9,9) *) (999,999)
let (cx,cy) = ((maxx+1)/2, (maxy+1)/2)

let split_string s =
  let s = trim s in

  let n = String.length s in
  let li = fold 0 (n-1)
    (fun i ac -> if s.[i] = ' ' then i::ac else ac) []
  in

  let rec chop prev li ac =
    match li with [] -> List.rev ac
      | i::tail ->
	chop i tail ((sub s (prev+1) (i-prev-1))::ac)
  in

  chop (-1) (List.rev (n::li)) []

let read_ints () =
  let c = split_string (read_line()) in
  let c = List.map (fun s -> int_of_string s) c in
  Array.of_list c

let () =
  let rook = Array.make (nrooks+1) (0,0) in

  let line1 = read_ints() in
  let (kx, ky) = (line1.(0), line1.(1)) in

  for i=1 to nrooks do
    let linei = read_ints() in
    rook.(i) <- (linei.(0), linei.(1));
  done;

  let in_check (kx,ky) =
    (* return true if this king is in check *)
    exists 1 nrooks (fun i ->
      let (x,y) = rook.(i) in
      x = kx || y = ky
    )
  in

  let collide (kx,ky) =
  (* return true if the king is on top of a rook *)
    exists 1 nrooks (fun i -> rook.(i) = (kx,ky))
  in

  let dirs = [(-1,-1);(-1,0);(-1,1);(0,-1);(0,1);(1,-1);(1,0);(1,1)] in

  let rec move_to_goal (kx,ky) (goalx,goaly) = if kx = goalx && ky = goaly then true else (
    (* assume (kx,ky) has already been checked for being in check, or in a collision *)
(*    printf "move_to_goal (%d,%d) (%d,%d)\n" kx ky goalx goaly; *)
    let check_dirs = List.filter (fun (dx,dy) ->
      let (nx,ny) = (kx+dx, ky+dy) in
      nx >= 1 && ny >= 1 && nx<=maxx && ny <= maxy && in_check (nx,ny) && (not (collide (nx,ny)))
    ) dirs in

    let (terminal,kx,ky) =
      if check_dirs <> [] then (
	let (dx,dy) = List.hd check_dirs in
	let (kx,ky) = (kx+dx, ky+dy) in
	printf "%d %d\n" kx ky;
	(true,kx,ky) (* found a winning move *)
      ) else (
	let dx = Pervasives.compare goalx kx in
	let dy = Pervasives.compare goaly ky in
	let (kx,ky) = (kx+dx, ky+dy) in
	printf "%d %d\n" kx ky;
	(in_check (kx,ky), kx, ky)
      )
    in

    if terminal then false else (
      (* wait for a move from the other guy *)
      let line = read_ints() in
      let (k,x,y) = (line.(0), line.(1), line.(2)) in
      rook.(k) <- (x,y);
      move_to_goal (kx,ky) (goalx,goaly)
    )
  ) in

  if move_to_goal (kx,ky) (cx,cy) then (
    let count = Array.make_matrix 2 2 0 in
    for i=1 to nrooks do
      let wx = if fst rook.(i) < cx then 0 else 1 in
      let wy = if snd rook.(i) < cy then 0 else 1 in
      count.(wx).(wy) <- count.(wx).(wy) + 1
    done;
    let (_, i,j) =
      minf 0 1 (fun i ->
	minf 0 1 (fun j ->
	  (count.(i).(j), i, j)
	)
      )
    in
    let goalx = [|0;maxx|].(1-i) in
    let goaly = [|0;maxy|].(1-j) in

    if move_to_goal (cx,cy) (goalx, goaly) then failwith "bad" else ()
  ) else (
    (* the game is already over *)
  )

Scanf.(Array.(scanf " %d %d" @@ fun x y ->
  let map = make_matrix 1000 1000 false in
  let rooks = make 666 (0,0) in
  init 666 (fun i ->
    scanf " %d %d" @@
      fun x y -> map.(x).(y) <- true;
      rooks.(i) <- x,y) |> ignore;
  let x,y = ref x,ref y in
  let rec move p q =
    if map.(!x+p).(!y+q) then (
      move p 0
    ) else (
      x := !x + p;
      y := !y + q;
      Printf.printf "%d %d\n" !x !y; flush stdout;
      let i,u,v = scanf " %d %d %d" @@ fun p q r -> p,q,r in
      if i=0 && u=0 && v=0 then exit 0 (* WA *)
      else if i= -1 && u= -1 && v= -1 then exit 0 (* AC *)
      else (
        let pu,pv = rooks.(i-1) in
        map.(pu).(pv) <- false;
        map.( u).( v) <- true;
        rooks.(i-1) <- u,v;
        Printf.eprintf "%d: %d,%d --> %d %d\n" i pu pv u v; flush stderr
      )
    )
  in
  while !x <> 499 || !y <> 499 do
    if !x < 499 then move 1 0
    else if !x > 499 then move (-1) 0
    else if !y < 499 then move 0 1
    else if !y > 499 then move 0 (-1)
  done;
  let tr,tl,bl,br = fold_left (fun (p,q,r,s) (x,y) ->
    match x>499, y>499 with
    (* t/f: right/left, top/bottom *)
    |  true, true -> (p+1,q,r,s)
    | false, true -> (p,q+1,r,s)
    | false,false -> (p,q,r+1,s)
    |  true,false -> (p,q,r,s+1)
  ) (0,0,0,0) rooks
  in
  let mn = fold_left min br [|tr;tl;bl|] in
  ignore @@ init 499 @@ fun _ ->
    if mn=tr then move (-1) (-1)
    else if mn=tl then move 1 (-1)
    else if mn=bl then move 1 1
    else move (-1) 1
))

(* 11:35 *)
open Printf
open String

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

let split_string s =
  let s = trim s in

  let n = String.length s in
  let li = fold 0 (n-1)
    (fun i ac -> if s.[i] = ' ' then i::ac else ac) []
  in

  let rec chop prev li ac =
    match li with [] -> List.rev ac
      | i::tail ->
	chop i tail ((sub s (prev+1) (i-prev-1))::ac)
  in

  chop (-1) (List.rev (n::li)) []

let read_ints () =
  let c = split_string (read_line()) in
  let c = List.map (fun s -> int_of_string s) c in
  Array.of_list c

let () =
  let nrooks = 666 in
  let rook = Array.make (nrooks+1) (0,0) in

  let line1 = read_ints() in
  let (kx, ky) = (line1.(0), line1.(1)) in

  for i=1 to nrooks do
    let linei = read_ints() in
    rook.(i) <- (linei.(0), linei.(1));
  done;

  let in_check (kx,ky) =
    (* return true if this king is in check *)
    exists 1 nrooks (fun i ->
      let (x,y) = rook.(i) in
      x = kx || y = ky
    )
  in

  let collide (kx,ky) =
  (* return true if the king is on top of a rook *)
    exists 1 nrooks (fun i -> rook.(i) = (kx,ky))
  in

  let dirs = [(-1,-1);(-1,0);(-1,1);(0,-1);(0,1);(1,-1);(1,0);(1,1)] in

  let rec move_to_goal (kx,ky) (goalx,goaly) = if kx = goalx && ky = goaly then true else (
  (* assume (kx,ky) has already been checked for being in check, or in a collision *)
    let check_dirs = List.filter (fun (dx,dy) ->
      let (nx,ny) = (kx+dx, ky+dy) in
      nx >= 1 && ny >= 1 && nx<=999 && ny <= 999 && in_check (nx,ny) && (not (collide (nx,ny)))
    ) dirs in

    let terminal =
      if check_dirs <> [] then (
	let (dx,dy) = List.hd check_dirs in
	printf "%d %d\n" (kx+dx) (ky+dy);
	true (* found a winning move *)
      ) else (
	let dx = Pervasives.compare goalx kx in
	let dy = Pervasives.compare goaly ky in
	let (kx,ky) = (kx+dx, ky+dy) in
	printf "%d %d\n" kx ky;
	in_check (kx,ky)
      )
    in

    if terminal then false else (
      (* wait for a move from the other guy *)
      let line = read_ints() in
      let (k,x,y) = (line.(0), line.(1), line.(2)) in
      rook.(k) <- (x,y);
      move_to_goal (kx,ky) (goalx,goaly)
    )
  ) in

  if move_to_goal (kx,ky) (500,500) then (
    let count = Array.make_matrix 2 2 0 in
    for i=1 to nrooks do
      let wx = if fst rook.(i) < 500 then 0 else 1 in
      let wy = if snd rook.(i) < 500 then 0 else 1 in
      count.(wx).(wy) <- count.(wx).(wy) + 1
    done;
    let (_, i,j) =
      minf 0 1 (fun i ->
	minf 0 1 (fun j ->
	  (count.(i).(j), i, j)
	)
      )
    in
    let goalx = [|0;999|].(1-i) in
    let goaly = [|0;999|].(1-j) in

    if move_to_goal (500,500) (goalx, goaly) then () else failwith "bad"
  ) else (
    (* the game is already over *)
  )

(* 11:35 *)
open Printf
open String

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

let split_string s =
  let s = trim s in

  let n = String.length s in
  let li = fold 0 (n-1)
    (fun i ac -> if s.[i] = ' ' then i::ac else ac) []
  in

  let rec chop prev li ac =
    match li with [] -> List.rev ac
      | i::tail ->
	chop i tail ((sub s (prev+1) (i-prev-1))::ac)
  in

  chop (-1) (List.rev (n::li)) []

let read_ints () =
  let c = split_string (read_line()) in
  let c = List.map (fun s -> int_of_string s) c in
  Array.of_list c

let () =
  let nrooks = 666 in
  let rook = Array.make (nrooks+1) (0,0) in

  let line1 = read_ints() in
  let (kx, ky) = (line1.(0), line1.(1)) in

  for i=1 to nrooks do
    let linei = read_ints() in
    rook.(i) <- (linei.(0), linei.(1));
  done;

  let in_check (kx,ky) =
    (* return true if this king is in check *)
    exists 1 nrooks (fun i ->
      let (x,y) = rook.(i) in
      x = kx || y = ky
    )
  in

  let collide (kx,ky) =
  (* return true if the king is on top of a rook *)
    exists 1 nrooks (fun i -> rook.(i) = (kx,ky))
  in

  let dirs = [(-1,-1);(-1,0);(-1,1);(0,-1);(0,1);(1,-1);(1,0);(1,1)] in

  let rec move_to_goal (kx,ky) (goalx,goaly) = if kx = goalx && ky = goaly then true else (
  (* assume (kx,ky) has already been checked for being in check, or in a collision *)
    let check_dirs = List.filter (fun (dx,dy) ->
      let (nx,ny) = (kx+dx, ky+dy) in
      nx >= 0 && ny >= 0 && nx<=999 && ny <= 999 && in_check (nx,ny) && (not (collide (nx,ny)))
    ) dirs in

    let terminal =
      if check_dirs <> [] then (
	let (dx,dy) = List.hd check_dirs in
	printf "%d %d\n" (kx+dx) (ky+dy);
	true (* found a winning move *)
      ) else (
	let dx = Pervasives.compare goalx kx in
	let dy = Pervasives.compare goaly ky in
	let (kx,ky) = (kx+dx, ky+dy) in
	printf "%d %d\n" kx ky;
	in_check (kx,ky)
      )
    in

    if terminal then false else (
      (* wait for a move from the other guy *)
      let line = read_ints() in
      let (k,x,y) = (line.(0), line.(1), line.(2)) in
      rook.(k) <- (x,y);
      move_to_goal (kx,ky) (goalx,goaly)
    )
  ) in

  if move_to_goal (kx,ky) (500,500) then (
    let count = Array.make_matrix 2 2 0 in
    for i=1 to nrooks do
      let wx = if fst rook.(i) < 500 then 0 else 1 in
      let wy = if snd rook.(i) < 500 then 0 else 1 in
      count.(wx).(wy) <- count.(wx).(wy) + 1
    done;
    let (_, i,j) =
      minf 0 1 (fun i ->
	minf 0 1 (fun j ->
	  (count.(i).(j), i, j)
	)
      )
    in
    let goalx = [|0;999|].(1-i) in
    let goaly = [|0;999|].(1-j) in

    if move_to_goal (500,500) (goalx, goaly) then () else failwith "bad"
  ) else (
    (* the game is already over *)
  )


You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a".

The only line of input contains the string s (1 ≤ |s| ≤ 105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.

Print the string a to the first line and string b to the second line. Each string should be surrounded by quotes (ASCII 34). If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.

NoteIn the second example the string s contains five words: "1", "", "01", "a0", "".

let _ =
  let sb = Scanf.Scanning.stdib in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let s1 = ref [] in
  let s2 = ref [] in
  let cs = ref [] in
  let d = ref true in
  let s = s ^ ";" in
    for i = 0 to String.length s - 1 do
      let c = s.[i] in
	match c with
	  | ',' | ';' -> (
	      let cs' = List.rev !cs in
	      let dd =
		if !d then (
		  match cs' with
		    | ['0'] -> true
		    | []
		    | '0' :: _ -> false
		    | _ -> true
		) else false
	      in
		d := true;
		cs := [];
		if dd
		then s1 := cs' :: !s1
		else s2 := cs' :: !s2
	    )
	  | '0'..'9' ->
	      cs := c :: !cs;
	  | 'a'..'z' | 'A'..'Z' | '.' ->
	      d := false;
	      cs := c :: !cs;
	  | _ -> assert false
    done;
    let print ss =
      let ss = List.rev ss in
	if ss = []
	then Printf.printf "-\n"
	else (
	  let first = ref true in
	    Printf.printf "\"";
	    List.iter
	      (fun cs ->
		 if not !first
		 then Printf.printf ",";
		 List.iter (Printf.printf "%c") cs;
		 first := false;
	      ) ss;
	    Printf.printf "\"\n"
	)
    in
      print !s1;
      print !s2


You are given sequence a1, a2, ..., an and m queries lj, rj (1 ≤ lj ≤ rj ≤ n). For each query you need to print the minimum distance between such pair of elements ax and ay (x ≠ y), that:  both indexes of the elements lie within range [lj, rj], that is, lj ≤ x, y ≤ rj;  the values of the elements are equal, that is ax = ay. The text above understands distance as |x - y|.

The first line of the input contains a pair of integers n, m (1 ≤ n, m ≤ 5·105) — the length of the sequence and the number of queries, correspondingly.  The second line contains the sequence of integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109).  Next m lines contain the queries, one per line. Each query is given by a pair of numbers lj, rj (1 ≤ lj ≤ rj ≤ n) — the indexes of the query range limits.

Print m integers — the answers to each query. If there is no valid match for some query, please print -1 as an answer to this query.

(*[@@@warning "-30"]*)

type node = {
  l : int;
  r : int;
  x : int;
  left : node;
  right : node
}

let rec dummy = { l = 0; r = -1; x = -1; left = dummy; right = dummy }

let build_min a =
  let next l a a' =
    let rec next i i' =
     if i > l - 1 then i'
     else if i = l - 1 then begin a'.(i') <- a.(i); i' + 1 end
     else begin
       let left = a.(i) and right = a.(i + 1) in
       a'.(i') <- { l = left.l; r = right.r; x = min left.x right.x; left; right };
       next (i + 2) (i' + 1)
     end
    in
    next
  in
  let rec build l a =
    match l with
    | 0 -> dummy
    | 1 -> a.(0)
    | l ->
      let a' = Array.make (l / 2 + 1) dummy in
      let l' = next l a a' 0 0 in
      build l' a'
  in
  let a = Array.mapi (fun i x -> { l = i; r = i; x; left = dummy; right = dummy}) a in
  build (Array.length a) a

let many = 10000000

let find_min root l r =
  let rec find root =
    if root.r < l || root.l > r then many
    else if l <= root.l && root.r <= r then root.x
    else
      min (find root.left) (find root.right)
  in
  find root

type cmp = Lt | Gt | Eq

type return = Left | Right

let search compare return arr =
  let rec search l r =
    if r = l + 1 then Some (match return with Left -> l | Right -> r)
    else
      let m = l + (r - l) / 2 in
      match compare arr.(m) with
      | Eq -> Some m
      | Lt -> search m r
      | Gt -> search l m
  in
  let l = 0 and r = Array.length arr - 1 in
  if r < l then None
  else
    let cl = compare arr.(l) and cr = compare arr.(r) in
    if cl = Gt then (if return = Right then Some l else None)
    else if cr = Lt then (if return = Left then Some r else None)
    else if cl = Eq then Some l
    else if cr = Eq then Some r
    else search l r

let cmp (a : int) b = if a < b then Lt else if a > b then Gt else Eq

let () =
  let open Scanf in
  scanf "%d %d\n" @@ fun n m ->
  let ns = Array.(init n (fun i -> scanf "%d " @@ fun x -> x, i)) in
  Array.sort compare ns;
  let lrs = ref [] in
  Array.iteri (fun i (x, j) -> if i < n - 1 && x = fst ns.(i + 1) then lrs := (j, snd ns.(i + 1)) :: !lrs) ns;
  let lrs = Array.of_list !lrs in
  Array.sort compare lrs;
  let s = Stack.create () in
  Array.iter
    (fun (_, r as lr) ->
       while not (Stack.is_empty s) && snd (Stack.top s) > r do ignore (Stack.pop s) done;
       Stack.push lr s)
    lrs;
  let lrs = Array.init (Stack.length s) (fun _ -> Stack.pop s) in
  (let l = Array.length lrs in
   for i = 0 to l / 2 - 1 do let t = lrs.(l - i - 1) in lrs.(l - i - 1) <- lrs.(i); lrs.(i) <- t done);
  let search_left l' = search (fun (l, _) -> cmp l l') Right lrs in
  let search_right r' = search (fun (_, r) -> cmp r r') Left lrs in
  let root = build_min @@ Array.map (fun (l, r) -> r - l) lrs in
  for _ = 1 to m do
    scanf "%d %d\n" @@ fun l r ->
    match search_left (l - 1), search_right (r - 1) with
    | Some l, Some r ->
      Printf.printf "%d\n" (let r = find_min root l r in if r = many then -1 else r)
    | _ -> Printf.printf "-1\n"
  done

open Stack
open Array

type node = {
  l : int;
  r : int;
  x : int;
  left : node;
  right : node
}

let rec dummy = { l = 0; r = -1; x = -1; left = dummy; right = dummy }

let build_min a =
  let next l a a' =
    let rec next i i' =
     if i > l - 1 then i'
     else if i = l - 1 then (a'.(i') <- a.(i); i' + 1)
     else
       let left = a.(i) and right = a.(i + 1) in
       a'.(i') <- { l = left.l; r = right.r; x = min left.x right.x; left; right };
       next (i + 2) (i' + 1)
    in
    next
  in
  let rec build l a =
    match l with
    | 0 -> dummy
    | 1 -> a.(0)
    | l ->
      let a' = make (l / 2 + 1) dummy in
      let l' = next l a a' 0 0 in
      build l' a'
  in
  let a = mapi (fun i x -> { l = i; r = i; x; left = dummy; right = dummy}) a in
  build (length a) a

let many = 10000000

let find_min root l r =
  let rec find root =
    if root.r < l || root.l > r then many
    else if l <= root.l && root.r <= r then root.x
    else min (find root.left) (find root.right)
  in
  find root

let search compare return arr =
  let rec search l r =
    if r = l + 1 then Some (match return with `Left -> l | `Right -> r)
    else
      let m = l + (r - l) / 2 in
      match compare arr.(m) with
      | `Eq -> Some m
      | `Lt -> search m r
      | `Gt -> search l m
  in
  let l = 0 and r = length arr - 1 in
  if r < l then None
  else
    let cl = compare arr.(l) and cr = compare arr.(r) in
    if cl = `Gt then (if return = `Right then Some l else None)
    else if cr = `Lt then (if return = `Left then Some r else None)
    else if cl = `Eq then Some l
    else if cr = `Eq then Some r
    else search l r

let cmp (a : int) b = if a < b then `Lt else if a > b then `Gt else `Eq

let () =
  let open Scanf in
  scanf "%d %d\n" @@ fun n m ->
  let ns = init n (fun i -> scanf "%d " @@ fun x -> x, i) in
  sort compare ns;
  let lrs = ref [] in
  iteri (fun i (x, j) -> if i < n - 1 && x = fst ns.(i + 1) then lrs := (j, snd ns.(i + 1)) :: !lrs) ns;
  let lrs = of_list !lrs in
  sort compare lrs;
  let s = Stack.create () in
  iter
    (fun (_, r as lr) ->
       while not (is_empty s) && snd (top s) > r do ignore (pop s) done;
       push lr s)
    lrs;
  let lrs = init (Stack.length s) (fun _ -> pop s) in
  (let l = length lrs in
   for i = 0 to l / 2 - 1 do let t = lrs.(l - i - 1) in lrs.(l - i - 1) <- lrs.(i); lrs.(i) <- t done);
  let search_left l' = search (fun (l, _) -> cmp l l') `Right lrs in
  let search_right r' = search (fun (_, r) -> cmp r r') `Left lrs in
  let root = build_min @@ map (fun (l, r) -> r - l) lrs in
  for _ = 1 to m do
    scanf "%d %d\n" @@ fun l r ->
    match search_left (l - 1), search_right (r - 1) with
    | Some l, Some r ->
      Printf.printf "%d\n" (let r = find_min root l r in if r = many then -1 else r)
    | _ -> Printf.printf "-1\n"
  done

open Stack
open Array

let upd_min a n i (v : int) =
  let rec upd p l r =
    if l <= i && i <= r then begin
      if v < a.(p) then a.(p) <- v;
      if r - l >= 1 then
        let m = l + (r - l) / 2 in
        upd (p lsl 1 + 1) l m;
        upd ((p + 1) lsl 1) (m + 1) r
    end
  in
  upd 0 0 (n - 1)

let big_n = 10000000

let find_min a n l r =
  let rec find p l' r' =
    if r' < l || l' > r then big_n
    else if l <= l' && r' <= r then a.(p)
    else if r' - l' >= 1 then
      let m = l' + (r' - l') / 2 in
      min (find (p lsl 1 + 1) l' m) (find ((p + 1) lsl 1) (m + 1) r')
    else big_n
  in
  find 0 0 (n - 1)

let () =
  let open Scanf in
  scanf "%d %d\n" @@ fun n m ->
  let ns = init n (fun i -> scanf "%d " @@ fun x -> x, i) in
  sort compare ns;
  let lrs = ref [] in
  iteri (fun i (x, j) -> if i < n - 1 && x = fst ns.(i + 1) then lrs := (j, snd ns.(i + 1)) :: !lrs) ns;
  let lrs = of_list !lrs in
  sort compare lrs;
  let s = Stack.create () in
  iter
    (fun (_, r as lr) ->
       while not (is_empty s) && snd (top s) > r do ignore (pop s) done;
       push lr s)
    lrs;
  let lrs = init (Stack.length s) (fun _ -> pop s) in
  let len = length lrs in
  for i = 0 to len / 2 - 1 do let t = lrs.(len - i - 1) in lrs.(len - i - 1) <- lrs.(i); lrs.(i) <- t done;
  let ls, rs = make n ~-1, make n ~-1 in
  ignore @@ fold_left (fun (p, i) (l, _) -> for j = p + 1 to l do ls.(j) <- i done; l, i + 1) (~-1, 0) lrs;
  ignore @@ fold_right (fun (_, r) (p, i) -> for j = r to p - 1 do rs.(j) <- i done; r, i - 1) lrs (n, len - 1);
  let a = make (n * 3 + 1) big_n in
  iteri (fun i (l, r) -> upd_min a len i (r - l)) lrs;
  for _ = 1 to m do
    scanf "%d %d\n" @@ fun l r ->
    let l = ls.(l - 1) and r = rs.(r - 1) in
    if l >= 0 && r >= 0 then Printf.printf "%d\n" (let r = find_min a len l r in if r = big_n then -1 else r)
    else Printf.printf "-1\n"
  done

open Stack
open Array

type node = {
  l : int;
  r : int;
  x : int;
  left : node;
  right : node
}

let rec dummy = { l = 0; r = -1; x = -1; left = dummy; right = dummy }

let build_min a =
  let next l a a' =
    let rec next i i' =
     if i > l - 1 then i'
     else if i = l - 1 then (a'.(i') <- a.(i); i' + 1)
     else
       let left = a.(i) and right = a.(i + 1) in
       a'.(i') <- { l = left.l; r = right.r; x = min left.x right.x; left; right };
       next (i + 2) (i' + 1)
    in
    next
  in
  let rec build l a =
    match l with
    | 0 -> dummy
    | 1 -> a.(0)
    | l ->
      let a' = make (l / 2 + 1) dummy in
      let l' = next l a a' 0 0 in
      build l' a'
  in
  let a = mapi (fun i x -> { l = i; r = i; x; left = dummy; right = dummy}) a in
  build (length a) a

let many = 10000000

let find_min root l r =
  let rec find root =
    if root.r < l || root.l > r then many
    else if l <= root.l && root.r <= r then root.x
    else min (find root.left) (find root.right)
  in
  find root

let () =
  let open Scanf in
  scanf "%d %d\n" @@ fun n m ->
  let ns = init n (fun i -> scanf "%d " @@ fun x -> x, i) in
  sort compare ns;
  let lrs = ref [] in
  iteri (fun i (x, j) -> if i < n - 1 && x = fst ns.(i + 1) then lrs := (j, snd ns.(i + 1)) :: !lrs) ns;
  let lrs = of_list !lrs in
  sort compare lrs;
  let s = Stack.create () in
  iter
    (fun (_, r as lr) ->
       while not (is_empty s) && snd (top s) > r do ignore (pop s) done;
       push lr s)
    lrs;
  let lrs = init (Stack.length s) (fun _ -> pop s) in
  let l = length lrs in
  for i = 0 to l / 2 - 1 do let t = lrs.(l - i - 1) in lrs.(l - i - 1) <- lrs.(i); lrs.(i) <- t done;
  let ls, rs = make n ~-1, make n ~-1 in
  ignore @@ fold_left (fun (p, i) (l, _) -> for j = p + 1 to l do ls.(j) <- i done; l, i + 1) (~-1, 0) lrs;
  ignore @@ fold_right (fun (_, r) (p, i) -> for j = r to p - 1 do rs.(j) <- i done; r, i - 1) lrs (n, l - 1);
  let root = build_min @@ map (fun (l, r) -> r - l) lrs in
  for _ = 1 to m do
    scanf "%d %d\n" @@ fun l r ->
    let l = ls.(l - 1) and r = rs.(r - 1) in
    if l >= 0 && r >= 0 then Printf.printf "%d\n" (let r = find_min root l r in if r = many then -1 else r)
    else Printf.printf "-1\n"
  done

type sub = {
  mutable bl : node;
  mutable br : node;
  mutable tr : node
}
and node =
  | Empty
  | Node of int ref * sub

type tree = { mutable root : node; size : int }

let empty = 0, -1, 0, -1

let split (lmin, lmax, rmin, rmax) =
  let lmid = lmin  + (lmax - lmin) / 2 in
  let rmid = rmin + (rmax - rmin) / 2 in
  if lmin < lmax && rmin < rmax then
    (lmin, lmid, rmin, rmid),
    (lmin, lmid, rmid + 1, rmax),
    (lmid + 1, lmax, rmid + 1, rmax)
  else if lmin < lmax then
    (lmin, lmid, rmin, rmax),
    empty,
    (lmid + 1, lmax, rmin, rmax)
  else if rmin < rmax then
    (lmin, lmax, rmin, rmid),
    (lmin, lmax, rmid + 1, rmax),
    empty
  else
    empty, empty, empty

let add ({ root; size } as t) l r =
  let dist = r - l in
  let rec add (lmin, lmax, rmin, rmax as rect) t =
    if lmin <= l && l <= lmax && rmin <= r && r <= rmax then
      match t with
      | Empty ->
        let r = { bl = Empty; br = Empty; tr = Empty } in
        add' rect r;
        Node (ref dist, r)
      | Node (min, r) as node ->
        add' rect r;
        if dist < !min then min := dist;
        node
    else t
  and add' rect r =
    let bl, br, tr = split rect in
    r.bl <- add bl r.bl;
    r.br <- add br r.br;
    r.tr <- add tr r.tr
  in
  t.root <- add (0, size - 1, 0, size - 1) root

let none = max_int

let min { root; size } l r =
  let rec min (lmin, lmax, rmin, rmax as rect) =
    function
    | Empty -> none
    | _ when lmin > lmax || rmin > rmax -> none
    | Node (m, _)
      when l <= lmin && lmax <= r && l <= rmin && rmax <= r -> !m
    | Node _
      when r < lmin || l > lmax || r < rmin || l > rmax -> none
    | Node (_, rct) ->
      let bl, br, tr = split rect in
      let bl = min bl rct.bl and br = min br rct.br and tr = min tr rct.tr in
      let br = if bl < br then bl else br in
      if br < tr then br else tr
  in
  min (0, size - 1, 0, size - 1) root

type element = { v : int64; i : int }

let () =
  let open Scanf in
  scanf "%d %d\n" @@ fun n m ->
  let seq = Array.init n (fun i -> scanf "%Ld " @@ fun v -> { v; i }) in
  Array.sort
    (fun e1 e2 ->
       let r = Int64.compare e1.v e2.v in
       if r <> 0 then r else compare e1.i e2.i)
    seq;
  let t = { root = Empty; size = n } in
  Array.iteri (fun i v -> if i < n - 1 && v.v = seq.(i + 1).v then add t v.i seq.(i + 1).i) seq;
  for _ = 1 to m do
    scanf "%d %d\n" @@ fun l r -> Printf.printf "%d\n" @@ let m = min t (l - 1) (r - 1) in if m = none then -1 else m
  done

type sub = {
  mutable bl : node;
  mutable br : node;
  mutable tr : node
}
and node =
  | Empty
  | Node of int ref * sub

type tree = { mutable root : node; size : int }

let empty = 0, -1, 0, -1

let split (lmin, lmax, rmin, rmax) =
  let lmid = lmin  + (lmax - lmin) / 2 in
  let rmid = rmin + (rmax - rmin) / 2 in
  if lmin < lmax && rmin < rmax then
    (lmin, lmid, rmin, rmid),
    (lmin, lmid, rmid + 1, rmax),
    (lmid + 1, lmax, rmid + 1, rmax)
  else if lmin < lmax then
    (lmin, lmid, rmin, rmax),
    (lmid + 1, lmax, rmin, rmax),
    empty
  else if rmin < rmax then
    (lmin, lmax, rmin, rmid),
    (lmin, lmax, rmid + 1, rmax),
    empty
  else
    empty, empty, empty

let add ({ root; size } as t) l r =
  let dist = r - l in
  let rec add (lmin, lmax, rmin, rmax as rect) t =
    if lmin <= l && l <= lmax && rmin <= r && r <= rmax then
      match t with
      | Empty ->
        let r = { bl = Empty; br = Empty; tr = Empty } in
        add' rect r;
        Node (ref dist, r)
      | Node (min, r) as node ->
        add' rect r;
        if dist < !min then min := dist;
        node
    else t
  and add' rect r =
    let bl, br, tr = split rect in
    r.bl <- add bl r.bl;
    r.br <- add br r.br;
    r.tr <- add tr r.tr
  in
  t.root <- add (0, size - 1, 0, size - 1) root

let none = max_int

let min { root; size } l r =
  let rec min (lmin, lmax, rmin, rmax as rect) =
    function
    | Empty -> none
    | Node (m, _)
      when l <= lmin && lmax <= r && l <= rmin && rmax <= r -> !m
    | Node _
      when r < lmin || l > lmax || r < rmin || l > rmax -> none
    | Node (_, rct) ->
      let bl, br, tr = split rect in
      let bl = min bl rct.bl and br = min br rct.br and tr = min tr rct.tr in
      let br = if bl < br then bl else br in
      if br < tr then br else tr
  in
  min (0, size - 1, 0, size - 1) root

type element = { v : int; i : int }

let () =
  let open Scanf in
  scanf "%d %d\n" @@ fun n m ->
  let seq = Array.init n (fun i -> scanf "%d " @@ fun v -> { v; i }) in
  Array.sort compare seq;
  let t = { root = Empty; size = n } in
  Array.iteri (fun i v -> if i < n - 1 && v.v = seq.(i + 1).v then add t v.i seq.(i + 1).i) seq;
  for _ = 1 to m do
    scanf "%d %d\n" @@ fun l r -> Printf.printf "%d\n" @@ let m = min t (l - 1) (r - 1) in if m = none then -1 else m
  done

type sub = {
  mutable bl : node;
  mutable br : node;
  mutable tl : node;
  mutable tr : node
}
and node =
  | Empty
  | Node of int * sub

type tree = { mutable root : node; size : int }

let split (lmin, lmax, rmin, rmax) =
  let lmid = lmin  + (lmax - lmin) / 2 in
  let rmid = rmin + (rmax - rmin) / 2 in
  let empty = 0, -1, 0, -1 in
  if lmin < lmax && rmin < rmax then
    (lmin, lmid, rmin, rmid),
    (lmin, lmid, rmid + 1, rmax),
    (lmid + 1, lmax, rmin, rmid),
    (lmid + 1, lmax, rmid + 1, rmax)
  else if lmin < lmax then
    (lmin, lmid, rmin, rmax),
    empty,
    (lmid + 1, lmax, rmin, rmax),
    empty
  else if rmin < rmax then
    (lmin, lmax, rmin, rmid),
    (lmin, lmax, rmid + 1, rmax),
    empty,
    empty
  else
    empty, empty, empty, empty

let inside l r (lmin, lmax, rmin, rmax) =
  lmin <= l && l <= lmax && rmin <= r && r <= rmax

let add ({ root; size } as t) l r =
  let dist = r - l in
  let rec add rect =
    if inside l r rect then
      let add r =
        let bl, br, tl, tr = split rect in
        r.bl <- add bl r.bl;
        r.br <- add br r.br;
        r.tl <- add tl r.tl;
        r.tr <- add tr r.tr
      in
      function
      | Empty ->
        let r = { bl = Empty; br = Empty; tl = Empty; tr = Empty } in
        add r;
        Node (dist, r)
      | Node (min, r) as node ->
        add r;
        if dist < min then Node (dist, r) else node
    else fun x -> x
  in
  t.root <- add (0, size - 1, 0, size - 1) root

let none = -1

let min4 x y z k =
  let min x y = if x = none then y else if y = none then x else if x < y then x else y in
  List.fold_left min none [x; y; z; k]

let min { root; size } l r =
  let rec min (lmin, lmax, rmin, rmax as rect) =
    function
    | Empty -> none
    | Node _
      when not (inside l l rect || inside l r rect || inside r l rect || inside r r rect) -> none
    | Node (m, rct) ->
      if l <= lmin && lmax <= r && l <= rmin && rmax <= r then m
      else
        let bl, br, tl, tr = split rect in
        min4 (min bl rct.bl) (min br rct.br) (min tl rct.tl) (min tr rct.tr)
  in
  min (0, size - 1, 0, size - 1) root

type element = { v : int; i : int }

let () =
  let open Scanf in
  scanf "%d %d\n" @@ fun n m ->
  let seq = Array.init n (fun i -> scanf "%d " @@ fun v -> { v; i }) in
  Array.sort compare seq;
  let t = { root = Empty; size = n } in
  Array.iteri (fun i v -> if i < n - 1 && v.v = seq.(i + 1).v then add t v.i seq.(i + 1).i) seq;
  for _ = 1 to m do
    scanf "%d %d\n" @@ fun l r -> Printf.printf "%d\n" @@ min t (l - 1) (r - 1)
  done

type cmp = Le | Gt

let cmp a b =
  if a <= b then Le
  else Gt

type node = {
  l : int;
  r : int;
  mutable ll : quadr;
  mutable lr : quadr;
  mutable rl : quadr;
  mutable rr : quadr;
}
and quadr = Some of node | None

let rec merge a b =
  match a, b with
  | None, None -> None
  | Some _, None -> a
  | None, Some _ -> b
  | Some p, Some c ->
    let lp, rp, lc, rc, p, c, r =
      match cmp (abs (p.r - p.l)) (abs (c.r - c.l)) with
      | Le -> p.l, p.l, c.l, c.l, a, b, p
      | Gt -> c.l, c.r, p.l, p.r, b, a, c
    in
    begin match cmp lp lc, cmp rp rc with
    | Le, Le -> r.ll <- merge r.ll c
    | Le, Gt -> r.lr <- merge r.lr c
    | Gt, Le -> r.rl <- merge r.rl c
    | Gt, Gt -> r.rr <- merge r.rr c
    end;
    p

let add (l, r) t = merge t (Some { l; r; ll = None; lr = None; rl = None; rr = None })

let rec find t ((l, r) as e) =
  match t with
  | None -> -1
  | Some { l = l'; r = r'; ll; lr; rl; rr } ->
    let try2 a b =
      let a, b = find a e, find b e in
      match cmp 0 a, cmp 0 b, cmp a b with
      | Le, Le, Le -> a
      | Le, Le, Gt -> b
      | Le, Gt, _ -> a
      | Gt, Le, _ -> b
      | Gt, Gt, _ -> -1
    in
    match cmp l l', cmp r' r, cmp l' r, cmp l r' with
    | Le, Le, _, _ -> abs (r' - l')
    | Le, Gt, Le, _ -> try2 lr rr
    | Le, Gt, Gt, _ -> find rr e
    | Gt, Le, _, Le -> try2 ll lr
    | Gt, Le, _, Gt -> find ll e
    | Gt, Gt, _, _ -> find lr e

let (@@) a b = a b

exception End of quadr

let () =
  Scanf.scanf "%d %d\n" @@ fun n m ->
  let a = Array.init n (fun i -> Scanf.scanf " %d" @@ fun x -> (x, i)) in
  Array.sort (fun (a, i) (a', i') -> let r = compare a a' in if r <> 0 then r else compare i i') a;
  let t = Array.make (n - 1) ((0, 0), n) in
  Array.iteri
    (fun i (c, ci) ->
       if i > 0 then
         let p, pi = a.(i - 1) in
         if p = c then
           t.(i - 1) <- (pi, ci), Random.int n)
    a;
  Array.sort (fun (_, k) (_, k') -> compare k k') t;
  let t = try Array.fold_left (fun t (e, k)-> if k < n then add e t else raise (End t)) None t with End t -> t in
  for i = 1 to m do
    Scanf.scanf " %d %d" @@ fun l r -> Printf.printf "%d\n" @@ find t (l - 1, r - 1)
  done

type sub = {
  mutable bl : node;
  mutable br : node;
  mutable tr : node
}
and node =
  | Empty
  | Node of int ref * sub

type tree = { mutable root : node; size : int }

let empty = 0, -1, 0, -1

let split (lmin, lmax, rmin, rmax) =
  let lmid = lmin  + (lmax - lmin) / 2 in
  let rmid = rmin + (rmax - rmin) / 2 in
  if lmin < lmax && rmin < rmax then
    (lmin, lmid, rmin, rmid),
    (lmin, lmid, rmid + 1, rmax),
    (lmid + 1, lmax, rmid + 1, rmax)
  else if lmin < lmax then
    (lmin, lmid, rmin, rmax),
    empty,
    (lmid + 1, lmax, rmin, rmax)
  else if rmin < rmax then
    (lmin, lmax, rmin, rmid),
    (lmin, lmax, rmid + 1, rmax),
    empty
  else
    empty, empty, empty

let add ({ root; size } as t) l r =
  let dist = r - l in
  let rec add (lmin, lmax, rmin, rmax as rect) t =
    if lmin <= l && l <= lmax && rmin <= r && r <= rmax then
      match t with
      | Empty ->
        let r = { bl = Empty; br = Empty; tr = Empty } in
        add' rect r;
        Node (ref dist, r)
      | Node (min, r) as node ->
        add' rect r;
        if dist < !min then min := dist;
        node
    else t
  and add' rect r =
    let bl, br, tr = split rect in
    r.bl <- add bl r.bl;
    r.br <- add br r.br;
    r.tr <- add tr r.tr
  in
  t.root <- add (0, size - 1, 0, size - 1) root

let none = max_int

let min { root; size } l r =
  let rec min (lmin, lmax, rmin, rmax as rect) =
    function
    | Empty -> none
    | Node (m, _)
      when l <= lmin && lmax <= r && l <= rmin && rmax <= r -> !m
    | Node _
      when r < lmin || l > lmax || r < rmin || l > rmax -> none
    | Node (_, rct) ->
      let bl, br, tr = split rect in
      let bl = min bl rct.bl and br = min br rct.br and tr = min tr rct.tr in
      let br = if bl < br then bl else br in
      if br < tr then br else tr
  in
  min (0, size - 1, 0, size - 1) root

type element = { v : int64; i : int }

let () =
  let open Scanf in
  scanf "%d %d\n" @@ fun n m ->
  let seq = Array.init n (fun i -> scanf "%Ld " @@ fun v -> { v; i }) in
  Array.sort compare seq;
  let t = { root = Empty; size = n } in
  Array.iteri (fun i v -> if i < n - 1 && v.v = seq.(i + 1).v then add t v.i seq.(i + 1).i) seq;
  for _ = 1 to m do
    scanf "%d %d\n" @@ fun l r -> Printf.printf "%d\n" @@ let m = min t (l - 1) (r - 1) in if m = none then -1 else m
  done

(*[@@@warning "-30"]*)

type node = {
          left   : node option;
  mutable right  : node option;
  mutable parent : node option;
          l      : int;
          r      : int;
          olca   : olca
}
and olca = {
          uf       : uf;
  mutable ancestor : node option;
  mutable colored  : bool
}
and uf = {
  mutable parent   : node option;
  mutable rank     : int
}

module H = Hashtbl.Make(struct type t = node let equal = (==) let hash n = n.l end)

let olca () = { uf = { parent = None; rank = 0 }; ancestor = None; colored = false }

let rec add curr l r =
  match curr with
  | Some curr when curr.r - curr.l < r - l ->
    let olca = olca () in
    begin match curr.right with
    | Some right as left ->
      let node = Some { left; right = None; parent = Some curr; l; r; olca } in
      right.parent <- node;
      curr.right <- node;
      node
    | None ->
      let node = Some { left = None; right = None; parent = Some curr; l; r; olca } in
      curr.right <- node;
      node
    end
  | Some curr ->
    begin match curr.parent with
    | Some _ as p -> add p l r
    | None ->
      let node = Some { left = Some curr; right = None; parent = None; l; r; olca = olca () } in
      curr.parent <- node;
      node
    end
  | None -> Some { left = None; right = None; parent = None; l; r; olca = olca () }

exception Empty_tree

let of_some = function Some x -> x | None -> raise Empty_tree

let tarjan_olca queries =
  let init n =
     n.olca.uf.parent <- Some n;
     n.olca.uf.rank   <- 0
  in
  let rec find n =
    match n.olca.uf.parent with
    | Some n' when n' == n -> n
    | Some n' ->
      let p = find n' in
      n.olca.uf.parent <- Some p;
      p
    | None -> assert false
  in
  let union u v =
    let u, v = find u, find v in
    if u.olca.uf.rank > v.olca.uf.rank then
      v.olca.uf.parent <- Some u
    else if u.olca.uf.rank < v.olca.uf.rank then
      u.olca.uf.parent <- Some v
    else if u != v then begin
      v.olca.uf.parent <- Some u;
      u.olca.uf.rank <- u.olca.uf.rank + 1
    end
  in
  let rec tarjan u =
     init u;
     u.olca.ancestor <- Some u;
     let recur v =
       tarjan v;
       union u v;
       (find u).olca.ancestor <- Some u
     in
     let handle =
       match u.parent with
       | None -> (function Some v -> recur v | None -> ())
       | Some v' -> function Some v -> if v != v' then recur v | None -> ()
     in
     handle u.left;
     handle u.right;
     u.olca.colored <- true;
     try
       H.iter
         (fun v a ->
            if v.olca.colored then
              let r = of_some (find v).olca.ancestor in
              a := r;
              H.find (H.find queries v) u := r)
         (H.find queries u)
     with
     | Not_found -> ()
  in
  tarjan

type cmp = Lt | Gt | Eq

let search compare return arr =
  let rec search l r =
    if r = l + 1 then Some (return (arr.(l), arr.(r)))
    else
      let m = l + (r - l) / 2 in
      match compare arr.(m) with
      | Eq -> Some arr.(m)
      | Lt -> search m r
      | Gt -> search l m
  in
  let l = 0 and r = Array.length arr - 1 in
  if compare arr.(l) = Gt || compare arr.(r) = Lt then None
  else if compare arr.(l) = Eq then Some arr.(l)
  else if compare arr.(r) = Eq then Some arr.(r)
  else search l r

let () =
  let open Scanf in
  scanf "%d %d\n" @@ fun n m ->
  let ns = Array.init n (fun i -> scanf "%d " @@ fun x -> x, i) in
  Array.sort compare ns;
  let lrs = ref [] in
  Array.iteri (fun i (x, j) -> if i < n - 1 && x = fst ns.(i + 1) then lrs := (j, snd ns.(i + 1)) :: !lrs) ns;
  let lrs = Array.of_list !lrs in
  Array.sort compare lrs;
  let lrs' = ref [] in
  try
    let root =
      let r =
        of_some @@ Array.fold_left (fun root (l, r) -> let r = add root l r in lrs' := of_some r :: !lrs'; r) None lrs
      in
      let rec root r = match r.parent with None -> r | Some p -> root p in
      root r
    in
    let lrs' = Array.of_list @@ List.rev !lrs' in
    let queries, queries_list = H.create 32, ref [] in
    let add_query u v =
      H.replace
        (try H.find queries u with Not_found -> let h = H.create 16 in H.replace queries u h; h)
        v
        (ref root)
    in
    let add_query l r u v = add_query u v; add_query v u; queries_list := Some (l, r, u, v) :: !queries_list in
    let cmp a b = if a < b then Lt else if b < a then Gt else Eq in
    let search_left l' = search (fun { l; _ } -> cmp l l') snd lrs' in
    let search_right r' = search (fun { r; _ } -> cmp r r') fst lrs' in
    for _ = 1 to m do
      scanf "%d %d\n" @@ fun l r ->
      match search_left (l - 1), search_right (r - 1) with
      | Some u, Some v -> add_query (l - 1) (r - 1) u v
      | _ -> queries_list := None :: !queries_list
    done;
    tarjan_olca queries root;
    List.iter Printf.(
        function
        | None -> printf "-1\n"
        | Some (l', r', u, v) ->
          let { l; r; _ } = !H.(find (find queries u) v) in
          if l' <= l && r <= r' then printf "%d\n" (r - l)
          else printf "-1\n")
      (List.rev !queries_list)
  with
  | Empty_tree ->  for _ = 1 to m do Printf.printf "-1\n" done

(*[@@@warning "-30"]*)

type node = {
  l : int;
  r : int;
  x : int;
  left : node option;
  right : node option
}

let build f l =
  let rec next acc =
    function
    | [] -> List.rev acc
    | [x] -> List.rev (x :: acc)
    | x :: y :: xs ->
      next ({ l = x.l; r = y.r; x = f x.x y.x; left = Some x; right = Some y } :: acc) xs
  in
  let next = next [] in
  let rec build =
    function
    | [] -> { l = 0; r = -1; x = -1; left = None; right = None }
    | [root] -> root
    | layer -> build (next layer)
  in
  build @@ List.mapi (fun i x -> { l = i; r = i; x; left = None; right = None}) l

let find f root l r =
  let rec find root =
    if l <= root.l && root.r <= r then [root.x]
    else if root.r < l || root.l > r then []
    else
      let map = function None -> [] | Some t -> find t in
      let l = map root.left @ map root.right in
      match l with
      | [] -> []
      | _ :: _ -> List.[fold_left f (hd l) (tl l)]
  in
  find root

let build_min = build min and find_min = find min

type cmp = Lt | Gt | Eq

let search compare return arr =
  let rec search l r =
    if r = l + 1 then Some (return (l, r))
    else
      let m = l + (r - l) / 2 in
      match compare arr.(m) with
      | Eq -> Some m
      | Lt -> search m r
      | Gt -> search l m
  in
  let l = 0 and r = Array.length arr - 1 in
  if r < l || compare arr.(l) = Gt || compare arr.(r) = Lt then None
  else if compare arr.(l) = Eq then Some l
  else if compare arr.(r) = Eq then Some r
  else search l r

let () =
  let open Scanf in
  scanf "%d %d\n" @@ fun n m ->
  let ns = Array.(init n (fun i -> scanf "%d " @@ fun x -> x, i)) in
  Array.sort compare ns;
  let lrs = ref [] in
  Array.iteri (fun i (x, j) -> if i < n - 1 && x = fst ns.(i + 1) then lrs := (j, snd ns.(i + 1)) :: !lrs) ns;
  let lrs = Array.of_list !lrs in
  Array.sort compare lrs;
  let s = Stack.create () in
  Array.iter
    (fun (_, r as lr) ->
       while not (Stack.is_empty s) && snd (Stack.top s) > r do ignore (Stack.pop s) done;
       Stack.push lr s)
    lrs;
  let lrs =
    Array.(init (Stack.length s) (fun _ -> Stack.pop s) |>
           to_list |>
           List.rev |>
           of_list)
  in
  let cmp a b = if a < b then Lt else if a > b then Gt else Eq in
  let search_left l' = search (fun (l, _) -> cmp l l') snd lrs in
  let search_right r' = search (fun (_, r) -> cmp r r') fst lrs in
  let root = build_min Array.(to_list @@ map (fun (l, r) -> r - l) lrs) in
  for _ = 1 to m do
    scanf "%d %d\n" @@ fun l r ->
    match search_left (l - 1), search_right (r - 1) with
    | Some l, Some r ->
      Printf.printf "%d\n" @@
      begin match find_min root l r with
      | [] -> -1
      | [x] -> x
      | l -> List.(fold_left min (hd l) (tl l))
      end
    | _ -> Printf.printf "-1\n"
  done


You are given a binary matrix $$$A$$$ of size $$$n \times n$$$. Rows are numbered from top to bottom from $$$1$$$ to $$$n$$$, columns are numbered from left to right from $$$1$$$ to $$$n$$$. The element located at the intersection of row $$$i$$$ and column $$$j$$$ is called $$$A_{ij}$$$. Consider a set of $$$4$$$ operations:  Cyclically shift all rows up. The row with index $$$i$$$ will be written in place of the row $$$i-1$$$ ($$$2 \le i \le n$$$), the row with index $$$1$$$ will be written in place of the row $$$n$$$.  Cyclically shift all rows down. The row with index $$$i$$$ will be written in place of the row $$$i+1$$$ ($$$1 \le i \le n - 1$$$), the row with index $$$n$$$ will be written in place of the row $$$1$$$.  Cyclically shift all columns to the left. The column with index $$$j$$$ will be written in place of the column $$$j-1$$$ ($$$2 \le j \le n$$$), the column with index $$$1$$$ will be written in place of the column $$$n$$$.  Cyclically shift all columns to the right. The column with index $$$j$$$ will be written in place of the column $$$j+1$$$ ($$$1 \le j \le n - 1$$$), the column with index $$$n$$$ will be written in place of the column $$$1$$$.     The $$$3 \times 3$$$ matrix is shown on the left before the $$$3$$$-rd operation is applied to it, on the right — after. You can perform an arbitrary (possibly zero) number of operations on the matrix; the operations can be performed in any order.After that, you can perform an arbitrary (possibly zero) number of new xor-operations:  Select any element $$$A_{ij}$$$ and assign it with new value $$$A_{ij} \oplus 1$$$. In other words, the value of $$$(A_{ij} + 1) \bmod 2$$$ will have to be written into element $$$A_{ij}$$$. Each application of this xor-operation costs one burl. Note that the $$$4$$$ shift operations — are free. These $$$4$$$ operations can only be performed before xor-operations are performed.Output the minimum number of burles you would have to pay to make the $$$A$$$ matrix unitary. A unitary matrix is a matrix with ones on the main diagonal and the rest of its elements are zeros (that is, $$$A_{ij} = 1$$$ if $$$i = j$$$ and $$$A_{ij} = 0$$$ otherwise).

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test. The descriptions of the test cases follow. Before each test case, an empty line is written in the input. The first line of each test case contains a single number $$$n$$$ ($$$1 \le n \le 2000$$$) This is followed by $$$n$$$ lines, each containing exactly $$$n$$$ characters and consisting only of zeros and ones. These lines describe the values in the elements of the matrix. It is guaranteed that the sum of $$$n^2$$$ values over all test cases does not exceed $$$4 \cdot 10^6$$$.

For each test case, output the minimum number of burles you would have to pay to make the $$$A$$$ matrix unitary. In other words, print the minimum number of xor-operations it will take after applying cyclic shifts to the matrix for the $$$A$$$ matrix to become unitary.

NoteIn the first test case, you can do the following: first, shift all the rows down cyclically, then the main diagonal of the matrix will contain only "1". Then it will be necessary to apply xor-operation to the only "1" that is not on the main diagonal.In the second test case, you can make a unitary matrix by applying the operation $$$2$$$ — cyclic shift of rows upward twice to the matrix.

open Printf
open Char
open Scanf
module LL = Int64
let ( !! )  x  = LL.to_int x
let ( ++ ) x y = LL.add x y
let ( -- ) x y = LL.sub x y
let ( ** ) x y = LL.mul x y
let ( // ) x y = LL.div x y
let ( %% ) x y = LL.rem x y
let ( >> ) x y = (LL.compare x y) > 0
let ( << ) x y = (LL.compare x y) < 0
let ( == ) x y = (LL.compare x y) = 0
let rd_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let rd_ll _ = bscanf Scanning.stdin " %Ld " (fun x -> x)
let rd_arr n = Array.init n rd_ll
let rd_str _ = bscanf Scanning.stdin " %s " (fun x -> x)
let rd_mat n m = Array.init n rd_str

let diag i j n = (i - j + n) mod n
let c2i ch = int_of_char ch - int_of_char '0'
let solve n mat =
  let s = ref 0 in
  let cnt = Array.init n (fun _ -> 0) in
  for i=0 to n-1 do
    for j=0 to n-1 do
      let d = diag i j n in
      let c = cnt.(d) in
      let x = c2i mat.(i).[j] in
      cnt.(d) <- (c + x);
      s := !s + x;
    done;
  done;
  let best = (Array.fold_right max cnt 0) in
  let offD = !s - best in
    n - best + offD

let () =
  let t = rd_int () in
  for i=1 to t do
    let n = rd_int () in
    let mat = rd_mat n n in
    printf "%d\n" (solve n mat)
  done;

open Printf
open Char
open Scanf
module LL = Int64
let ( !! )  x  = LL.to_int x
let ( ++ ) x y = LL.add x y
let ( -- ) x y = LL.sub x y
let ( ** ) x y = LL.mul x y
let ( // ) x y = LL.div x y
let ( %% ) x y = LL.rem x y
let ( >> ) x y = (LL.compare x y) > 0
let ( << ) x y = (LL.compare x y) < 0
let ( == ) x y = (LL.compare x y) = 0
let rd_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let rd_ll _ = bscanf Scanning.stdin " %Ld " (fun x -> x)
let rd_arr n = Array.init n rd_ll
let rd_str _ = bscanf Scanning.stdin " %s " (fun x -> x)
let rd_mat n m = Array.init n rd_str

let diag i j n = (i - j + n) mod n
let c2i ch = int_of_char ch - int_of_char '0'
let solve n mat =
  let cnt = Array.init n (fun _ -> 0) in
  let rec loop ij sum =
    match ij with
    | (-1, _) -> sum
    | (i, j) ->
      let d = diag i j n in
      let c = cnt.(d) in
      let x = c2i mat.(i).[j] in
      let di = if j-1 < 0 then 1 else 0 in
      cnt.(d) <- (c + x);
      loop (i-di, (j-1+n) mod n) (sum + x)
  in
    let s = loop (n-1, n-1) 0 in
    let onD  = (Array.fold_right max cnt 0) in
    let offD = s - onD in
    n - onD + offD

let () =
  let t = rd_int () in
  for i=1 to t do
    let n = rd_int () in
    let mat = rd_mat n n in
    printf "%d\n" (solve n mat)
  done;


You are given two integers $$$l$$$ and $$$r$$$, $$$l\le r$$$. Find the largest possible value of $$$a \bmod b$$$ over all pairs $$$(a, b)$$$ of integers for which $$$r\ge a \ge b \ge l$$$.As a reminder, $$$a \bmod b$$$ is a remainder we get when dividing $$$a$$$ by $$$b$$$. For example, $$$26 \bmod 8 = 2$$$.

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ $$$(1\le t\le 10^4)$$$, denoting the number of test cases. Description of the test cases follows. The only line of each test case contains two integers $$$l$$$, $$$r$$$ ($$$1\le l \le r \le 10^9$$$).

For every test case, output the largest possible value of $$$a \bmod b$$$ over all pairs $$$(a, b)$$$ of integers for which $$$r\ge a \ge b \ge l$$$.

NoteIn the first test case, the only allowed pair is $$$(a, b) = (1, 1)$$$, for which $$$a \bmod b = 1 \bmod 1 = 0$$$.In the second test case, the optimal choice is pair $$$(a, b) = (1000000000, 999999999)$$$, for which $$$a \bmod b = 1$$$.

(* OCaml template *)
open Printf
open Scanf

(* Redefine operators for Int32 *)
(*
let ( + ) = Int32.add;;
let ( - ) = Int32.sub;;
let ( * ) = Int32.mul;;
let ( / ) = Int32.div;;
let ( % ) = Int32.rem;;
*)

(* Redefine operators for Int64 *)
let ( + ) = Int64.add;;
let ( - ) = Int64.sub;;
let ( * ) = Int64.mul;;
let ( / ) = Int64.div;;
let ( % ) = Int64.rem;;

(* Input *)
let read_int32 _ = bscanf Scanning.stdin "%ld " @@ fun x -> x;;
let read_int64 _ = bscanf Scanning.stdin "%Ld " @@ fun x -> x;;

(* Output *)
let print_int32 n = printf "%ld " n;;
let print_int32_endl n = printf "%ld\n" n;;
let print_int64 n = printf "%Ld " n;;
let print_int64_endl n = printf "%Ld\n" n;;

(* Utility functions *)
let comp f g x = f @@ g x;;
let rec fac n = if n = 0L then 1L else n * fac (n - 1L);;
let rec fib n = if n < 2L then n else fib (n - 2L) + fib (n - 1L);;
let sum = List.fold_left (+) 0L;;

(* Solve test case *)
let solve l r =
	if r < 2L * l then
		r - l
	else
		(r - 1L) / 2L;;

(* Main *)
let t = read_int ();;

for t' = 1 to t do
	let l = read_int64 () in
		let r = read_int64 () in
			print_int64_endl @@ solve l r
done

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

let () =
  let cases = read_int () in
  for case = 1 to cases do
    let (a, b) = read_pair () in
    let c = b/2+1 in
    let result =
    if c >= a then b mod c
    else b mod a
    in
      printf "%d\n" result
  done


You are given N points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.

The first line of input contains one integer number N (1 ≤ N ≤ 100 000) — the number of points. Each of the following N lines contain two integer numbers X and Y ( - 10 000 ≤ X, Y ≤ 10 000) — the coordinates of points. Two or more points may coincide.

The only line of output should contain the required sum of squares of distances between all pairs of points.

let (+) = Int64.add
let ( * ) = Int64.mul
let ( - ) = Int64.sub
let two = Int64.one + Int64.one
let one = Int64.one
let zero = Int64.zero

let solve =
  let n = Scanf.scanf "%Ld\n" (fun n -> n) in
  let readPoints() = Scanf.scanf "%Ld %Ld\n" (fun x y -> (x,y)) in
  let rec readInput i (accX,accY) =
    match i with
      | i when i = n -> (List.rev accX,List.rev accY)
      | i -> let (x,y) = readPoints() in
          readInput (i+one) ((x::accX),(y::accY))
  in
  let rec sumpoints lst sum sqsum i acc =
    match lst with
      | [] -> acc
      | x::xs -> let newval = ((i-one)*(x*x)-two*x*sum+sqsum) in
          sumpoints xs (sum+x) (sqsum+(x*x)) (i+one) (acc+newval)
  in
  let xs,ys = readInput zero ([],[]) in
    Printf.printf "%Ld\n" ((sumpoints xs zero zero one zero)+(sumpoints ys zero zero one zero))
;;

let (+) = Int64.add
let ( * ) = Int64.mul
let ( - ) = Int64.sub
let two = Int64.one + Int64.one
let one = Int64.one
let zero = Int64.zero

let solve =
  let n = Scanf.scanf "%Ld\n" (fun n -> n) in
  let readPoints() = Scanf.scanf "%Ld %Ld\n" (fun x y -> (x,y)) in
  let rec readInput i (accX,accY) =
    match i with
      | i when i = n -> (List.rev accX,List.rev accY)
      | i -> let (x,y) = readPoints() in
          readInput (i+one) ((x::accX),(y::accY))
  in
  let rec sumpoints lst sum sqsum i acc =
    match lst with
      | [] -> acc
      | x::xs -> let newval = ((i-one)*(x*x)-(two*x*sum)+sqsum) in
          sumpoints xs (sum+x) (sqsum+(x*x)) (i+one) (acc+newval)
  in
  let xs,ys = readInput zero ([],[]) in
    Printf.printf "%Ld\n" ((sumpoints xs zero zero one zero)+(sumpoints ys zero zero one zero))
;;

let solve =
  let n = Scanf.scanf "%d\n" (fun n -> n) in
  let readPoints() = Scanf.scanf "%d %d\n" (fun x y -> (x,y)) in
  let rec readInput i (accX,accY) =
    match i with
      | i when i = n -> (List.rev accX,List.rev accY)
      | i -> let (x,y) = readPoints() in
          readInput (i+1) ((x::accX),(y::accY))
  in
  let rec sumpoints lst sum sqsum i acc =
    match lst with
      | [] -> acc
      | x::xs -> let newval = ((i-1)*(x*x)-2*x*sum+sqsum) in
          sumpoints xs (sum+x) (sqsum+(x*x)) (i+1) (acc+newval)
  in
  let xs,ys = readInput 0 ([],[]) in
    Printf.printf "%d\n" ((sumpoints xs 0 0 1 0)+(sumpoints ys 0 0 1 0))
;;

let solve =
    let n = Scanf.scanf "%d\n" (fun n -> n) in
    let readPoints() = Scanf.scanf "%d %d\n" (fun x y -> (x,y)) in
    let rec readInput i (accX,accY) =
        match i with
            | i when i = n -> (List.rev accX,List.rev accY)
            | i -> let (x,y) = readPoints() in
                    readInput (i+1) ((x::accX),(y::accY))
    in
    let rec sumpoints lst sum sqsum i acc =
    match lst with
        | [] -> acc
        | x::xs -> let newval = ((i-1)*(x*x)-2*x*sum+sqsum) in
                    sumpoints xs (sum+x) (sqsum+(x*x)) (i+1) (acc+newval)
    in
    let xs,ys = readInput 0 ([],[]) in
    let result = (sumpoints xs 0 0 1 0)+(sumpoints ys 0 0 1 0) in
      Printf.printf "%d\n" result
;;


You have a string $$$s_1 s_2 \ldots s_n$$$ and you stand on the left of the string looking right. You want to choose an index $$$k$$$ ($$$1 \le k \le n$$$) and place a mirror after the $$$k$$$-th letter, so that what you see is $$$s_1 s_2 \ldots s_k s_k s_{k - 1} \ldots s_1$$$. What is the lexicographically smallest string you can see?A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:   $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$;  in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

The first line of input contains one integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$): the number of test cases. The next $$$t$$$ lines contain the description of the test cases, two lines per a test case. In the first line you are given one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$): the length of the string. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase English characters. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print the lexicographically smallest string you can see.

4
10
codeforces
9
cbacbacba
3
aaa
4
bbaa

NoteIn the first test case choose $$$k = 1$$$ to obtain "cc".In the second test case choose $$$k = 3$$$ to obtain "cbaabc".In the third test case choose $$$k = 1$$$ to obtain "aa".In the fourth test case choose $$$k = 1$$$ to obtain "bb".

open Printf
open Scanf

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

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

let () =
  let cases = read_int () in
  for case = 1 to cases do
    let n = read_int () in
    let a = read_string () in

    let rec findk k = if k = n-1 then n-1 else (
      if (a.[k] > a.[k+1]) || (k > 0 && (a.[k] >= a.[k+1])) then findk (k+1) else k
    ) in
    let k = findk 0 in
    for i=0 to k do printf "%c" a.[i] done;
    for i=k downto 0 do printf "%c" a.[i] done;
    print_newline()
  done

open Printf
open Scanf

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

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

let () =
  let cases = read_int () in
  for case = 1 to cases do
    let n = read_int () in
    let a = read_string () in

    let rec findk k = if k = n-1 then n-1 else (
      if a.[k] > a.[k+1] then findk (k+1) else k
    ) in
    let k = findk 0 in
    for i=0 to k do printf "%c" a.[i] done;
    for i=k downto 0 do printf "%c" a.[i] done;
    print_newline()
  done


The secondary diagonal of a square matrix is a diagonal going from the top right to the bottom left corner. Let's define an n-degree staircase as a square matrix n × n containing no squares above the secondary diagonal (the picture below shows a 5-degree staircase).   The squares of the n-degree staircase contain m sportsmen. A sportsman needs one second to move to a side-neighboring square of the staircase. Before the beginning of the competition each sportsman must choose one of the shortest ways to the secondary diagonal. After the starting whistle the competition begins and all sportsmen start moving along the chosen paths. When a sportsman reaches a cell of the secondary diagonal, he stops and moves no more. The competition ends when all sportsmen reach the secondary diagonal. The competition is considered successful if during it no two sportsmen were present in the same square simultaneously. Any square belonging to the secondary diagonal also cannot contain more than one sportsman. If a sportsman at the given moment of time leaves a square and another sportsman comes to it, then they are not considered to occupy the same square simultaneously. Note that other extreme cases (for example, two sportsmen moving towards each other) are impossible as the chosen ways are the shortest ones.You are given positions of m sportsmen on the staircase. Your task is to choose among them the maximum number of sportsmen for who the competition can be successful, that is, so that there existed such choice of shortest ways for the sportsmen at which no two sportsmen find themselves in the same square simultaneously. All other sportsmen that are not chosen will be removed from the staircase before the competition starts.

The first line contains two integers n and m (1 ≤ n, m ≤ 105). Then m lines contain coordinates of sportsmen on the staircase as pairs of integers ri, ci (1 ≤ ri, ci ≤ n, n - ci < ri), where ri is the number of the staircase row, ci is the number of the staircase column (to understand the principle of numbering rows and columns see the explanatory pictures). No two sportsmen stand on the same square of the staircase.

In the first line print the number of the chosen sportsmen. In the second line print the numbers of chosen sportsmen in any order, separating the numbers with spaces. If there are several answers, you are permitted to print any of them. The sportsmen are numbered starting from one in the order in which they are given in the input data.

NoteA note to the first sample.    The picture shows a three-degree staircase. The arrows show the shortest paths that the sportsmen choose.

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

(* 1:34  --- 2:42 *)

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

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

let row = Array.make n []
;;

for i=0 to m-1 do
  let r = n-(read_int()) in
  let c = read_int() -1 in
    row.(r) <- (c, r, i)::row.(r)
done

let alive = Array.make m false
let count = ref 0

let rec proc r s = if r=n then () else
  (* merge the current row r into the set *)
  (* process them in left to right order marking dead the ones in column < r *)
  (* when we come to one with a column >= r, that's the one that goes into the place *)
  let s = List.fold_left (fun ac e -> Sset.add e ac ) s row.(r) in
  let rec scan s = if Sset.is_empty s then s else
    let (cc, rr, ii) = Sset.min_elt s in
    let s = Sset.remove (cc,rr,ii) s in
      if cc>=r then (
	alive.(ii) <- true;
	count := !count +1;
	s;
      ) else scan s
  in
    proc (r+1) (scan s)

;;

proc 0 Sset.empty;
Printf.printf "%d\n" !count;
for i=0 to m-1 do
  if alive.(i) then Printf.printf "%d " (i+1)
done;
Printf.printf "\n"


You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints.

For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists.

NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$.

open Printf
open Str

let read_ints() =
  Array.map (int_of_string) (Array.of_list (Str.split (Str.regexp " +") (read_line())))

let main =
  let t = read_int() in
  for i = 1 to t do
    let tc = read_ints() in
    let x = tc.(0) in
    let y = tc.(1) in
    let n = tc.(2) in
    let r = n mod x in
    let m = n / x * x in
    printf "%d\n" (if y <= r then m + y else m - x + y)
  done


You have one chip and one chance to play roulette. Are you feeling lucky?

Print your bet. Your chip must be placed entirely within some square (not on an edge or a corner shared by adjacent squares).

let _ =
  let x = read_int () in
  if x mod 2 = 0 then
    Format.printf "even@."
  else
    Format.printf "odd@."

let _ =
  Format.printf "%s@." (read_line ());
  Format.printf "even@."


Little X has a tree consisting of n nodes (they are numbered from 1 to n). Each edge of the tree has a positive length. Let's define the distance between two nodes v and u (we'll denote it d(v, u)) as the sum of the lengths of edges in the shortest path between v and u. A permutation p is a sequence of n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n). Little X wants to find a permutation p such that sum  is maximal possible. If there are multiple optimal permutations, he wants to find the lexicographically smallest one. Help him with the task!

The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains three space separated integers ui,  vi, wi (1 ≤  ui,  vi ≤  n; 1 ≤  wi ≤  105), denoting an edge between nodes ui and vi with length equal to wi. It is guaranteed that these edges form a tree.

In the first line print the maximum possible value of the described sum. In the second line print n integers, representing the lexicographically smallest permutation.

(* define the queue data structure *)
(* which is a set of sorted lists, ordered by the first element of the list. *)
let complist a b = match (a,b) with (a::_,b::_) -> compare a b | _-> failwith "bogus list"
module Lset = Set.Make (struct type t = int list let compare = complist end)

(* define the tightness data structure *)
(* a set of pairs (O(i) + I(i), i), where i is a component number
   and O(i) is the remaining outdegree of the component and I(i) is
   the remaining indegree of the component.  A component i is going
   to be tight if the value of "total" = O(i) + I(i) *)
module Pset = Set.Make (struct type t = int*int let compare = compare end)

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)

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

open Printf
open Scanf

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

let () =
  let n = read_int () in
  let tree = Array.make n [] in

  for i=0 to n-2 do
    let u = read_int()-1 in
    let v = read_int()-1 in
    let w = long (read_int()) in

    tree.(u) <- (v,w)::tree.(u);
    tree.(v) <- (u,w)::tree.(v)
  done;

(* The center of a tree is a node, which if deleted, divides the tree
   into connected components none of which is larger than n/2. We need
   to find the center. *)

(*---------------------------- find the center ----------------------------*)
  let size = Array.make n 0 in
  let rec size_dfs p u =
    size.(u) <- List.fold_left (fun ac (v,_) -> if v=p then ac else ac + size_dfs u v) 1 tree.(u);
    size.(u)
  in
  ignore (size_dfs (-1) 0);

  let rec find_center p u =
    let i = List.fold_left (
      fun i (v,_) -> if v = p then i else if i<0 || size.(v) > size.(i) then v else i
    ) (-1) tree.(u) in

    if i<0 then failwith "failed to find center";
    if size.(i) > n/2 then find_center u i else u
  in

  let center = if n=1 then 0 else find_center (-1) 0 in

(*---------------------------- label all nodes with their appropriate component ----------------------------*)

  let comp = Array.make n 0 in  (* comp.(v) is the component number of vertex v *)
  let rec comp_dfs p u lab =
    comp.(u) <- lab;
    List.iter (fun (v,_) -> if v<>p then comp_dfs u v lab) tree.(u);
  in

  let ncomp = List.fold_left (fun ac (v,_) -> comp_dfs center v ac; ac+1) 1 tree.(center) in
  (* component 0 is just vertex center *)
  let center_component = 0 in

(*---------------------------- compute the total cost of the solution ----------------------------*)
  ignore (size_dfs (-1) center);  (* recompute sizes with center (instead of 0) being the root *)

  let rec cost_dfs p u =
    List.fold_left (fun ac (v,w) -> if v=p then ac else ac ++ (cost_dfs u v) ++ 2L**w**(long size.(v))) 0L tree.(u)
  in

  let solution_cost = cost_dfs (-1) center in

(* ---------------------------- *)

(* build the initial queue data structure *)
  let nodes = Array.make ncomp [] in
  for i=0 to n-1 do
    nodes.(comp.(i)) <- i::nodes.(comp.(i))
  done;

  for i=0 to ncomp-1 do
    nodes.(i) <- List.sort compare nodes.(i)
  done;

  let initial_queue = fold 0 (ncomp-1) (fun i ac -> (Lset.add nodes.(i)) ac) Lset.empty in

(* define primitives for working with our special priority queue, which is a set
   of sorted lists, ordered by the first element of the list. *)

  let getmin ls = (* return the minimum element of ls.  non-destructive *)
    List.hd (Lset.min_elt ls)
  in

  let deletemin ls =
    let l1 = Lset.min_elt ls in
    let ls = Lset.remove l1 ls in
    let tail = List.tl l1 in
    let x = List.hd l1 in
    nodes.(comp.(x)) <- tail;
    if tail = [] then ls else Lset.add tail ls
  in

  let deletemin_exclude ls c =
  (* delete the minimum not in the specified component *)
  (* return the pair (x,queue) *)
    if nodes.(c) = [] then (getmin ls, deletemin ls) else
      let ls_withoutc = Lset.remove nodes.(c) ls in
      let x = getmin ls_withoutc in
      let ls1 = deletemin ls_withoutc in
      let ls2 = Lset.add nodes.(c) ls1 in
      (x,ls2)
  in

  let deletemin_from_comp ls c =
  (* delete the minimum in the specified component *)
  (* return the pair (x,queue) *)
    let ls_withoutc = Lset.remove nodes.(c) ls in
    let x = List.hd nodes.(c) in
    nodes.(c) <- List.tl nodes.(c);
    let ls1 = if nodes.(c) = [] then ls_withoutc else Lset.add nodes.(c) ls_withoutc in
    (x,ls1)
  in

(* functions for dealing with the tightness data structure *)

  let lhs = Array.init ncomp (fun c -> 2 * (List.length nodes.(c))) in
  lhs.(center_component) <- 1;

  let initial_tight = fold 0 (ncomp-1) (fun i ac -> Pset.add (lhs.(i),i) ac) Pset.empty in

  let findtight tight total =
    (* assumes there are at least two things in tight *)
    (* returns a list consisting of either 0, 1, or 2 tight components. *)
    let (lhs1, c1) = Pset.max_elt tight in
    if lhs1 < total then [] else
      let (lhs2,c2) = Pset.max_elt (Pset.remove (lhs1,c1) tight) in
      if lhs2 < total then [c1] else [c1;c2]
  in

  let makemove tight i j =
  (* we're making a move to add an edge from O(i) to I(j) *)
  (* this updates the tightness data structure to reflect this change *)
    if i=j && i<>center_component then failwith "i=j";
    lhs.(i) <- lhs.(i) - 1;
    let tight = Pset.add (lhs.(i), i) (Pset.remove (lhs.(i)+1,i) tight) in
    if j=center_component then tight else (
      lhs.(j) <- lhs.(j) - 1;
      Pset.add (lhs.(j), j) (Pset.remove (lhs.(j)+1,j) tight)
    )
  in

(*---------------------------- compute the permutation ----------------------------*)

  let perm = Array.make n 0 in

  let rec scan i queue tight =
    if i=n-1 then (
      perm.(i) <- getmin queue;
    ) else (
      let total = n-i in  (* number of links left to be added *)
      let (x, queue) = if i <> center then
	  match findtight tight total with
	    | []                        -> deletemin_exclude queue comp.(i)
	    | [t1] when t1 = comp.(i)   -> deletemin_exclude queue comp.(i)
	    | [t1]                      -> deletemin_from_comp queue t1
	    | [t1;t2] ->                   let othercomp = if t1=comp.(i) then t2 else t1 in
				           deletemin_from_comp queue othercomp
	    | _ -> failwith "impossible"
	else
	  match findtight tight total with
	    | []                        -> (getmin queue, deletemin queue)
	    | [t1] when t1 = comp.(i)   -> (getmin queue, deletemin queue) (* probably impossible *)
	    | [t1]                      -> deletemin_from_comp queue t1
	    | [t1;t2] ->                   let othercomp = if t1=comp.(i) then t2 else t1 in
				           deletemin_from_comp queue othercomp (* probably impossible *)
	    | _ -> failwith "impossible"
      in
      perm.(i) <- x;
      let tight = makemove tight comp.(i) comp.(x) in
      scan (i+1) queue tight
    ) in

  ignore (scan 0 initial_queue initial_tight);

  printf "%Ld\n" solution_cost;
  for i=0 to n-1 do
    printf "%d%s" (perm.(i)+1) (if i=n-1 then "\n" else " ")
  done;

(* define the queue data structure *)
(* which is a set of sorted lists, ordered by the first element of the list. *)
let complist a b = match (a,b) with (a::_,b::_) -> compare a b | _-> failwith "bogus list"
module Lset = Set.Make (struct type t = int list let compare = complist end)

(* define the tightness data structure *)
(* a set of pairs (O(i) + I(i), i), where i is a component number
   and O(i) is the remaining outdegree of the component and I(i) is
   the remaining indegree of the component.  A component i is going
   to be tight if the value of "total" = O(i) + I(i) *)
module Pset = Set.Make (struct type t = int*int let compare = compare end)

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)

open Printf
open Scanf

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

let () =
  let n = read_int () in
  let tree = Array.make n [] in

  for i=0 to n-2 do
    let u = read_int()-1 in
    let v = read_int()-1 in
    let w = read_int() in

    tree.(u) <- (v,w)::tree.(u);
    tree.(v) <- (u,w)::tree.(v)
  done;

(* The center of a tree is a node, which if deleted, divides the tree
   into connected components none of which is larger than n/2. We need
   to find the center. *)

(*---------------------------- find the center ----------------------------*)
  let size = Array.make n 0 in
  let rec size_dfs p u =
    size.(u) <- List.fold_left (fun ac (v,_) -> if v=p then ac else ac + size_dfs u v) 1 tree.(u);
    size.(u)
  in
  ignore (size_dfs (-1) 0);

  let rec find_center p u =
    let i = List.fold_left (
      fun i (v,_) -> if v = p then i else if i<0 || size.(v) > size.(i) then v else i
    ) (-1) tree.(u) in

    if i<0 then failwith "failed to find center";
    if size.(i) > n/2 then find_center u i else u
  in

  let center = if n=1 then 0 else find_center (-1) 0 in

(*---------------------------- label all nodes with their appropriate component ----------------------------*)

  let comp = Array.make n 0 in  (* comp.(v) is the component number of vertex v *)
  let rec comp_dfs p u lab =
    comp.(u) <- lab;
    List.iter (fun (v,_) -> if v<>p then comp_dfs u v lab) tree.(u);
  in

  let ncomp = List.fold_left (fun ac (v,_) -> comp_dfs center v ac; ac+1) 1 tree.(center) in
  (* component 0 is just vertex center *)
  let center_component = 0 in

(*---------------------------- compute the total cost of the solution ----------------------------*)
  ignore (size_dfs (-1) center);  (* recompute sizes with center (instead of 0) being the root *)

  let rec cost_dfs p u =
    List.fold_left (fun ac (v,w) -> if v=p then ac else ac + (cost_dfs u v) + 2*w*size.(v)) 0 tree.(u)
  in

  let solution_cost = cost_dfs (-1) center in

(* ---------------------------- *)

(* build the initial queue data structure *)
  let nodes = Array.make ncomp [] in
  for i=0 to n-1 do
    nodes.(comp.(i)) <- i::nodes.(comp.(i))
  done;

  for i=0 to ncomp-1 do
    nodes.(i) <- List.sort compare nodes.(i)
  done;

  let initial_queue = fold 0 (ncomp-1) (fun i ac -> (Lset.add nodes.(i)) ac) Lset.empty in

(* define primitives for working with our special priority queue, which is a set
   of sorted lists, ordered by the first element of the list. *)

  let getmin ls = (* return the minimum element of ls.  non-destructive *)
    List.hd (Lset.min_elt ls)
  in

  let deletemin ls =
    let l1 = Lset.min_elt ls in
    let ls = Lset.remove l1 ls in
    let tail = List.tl l1 in
    let x = List.hd l1 in
    nodes.(comp.(x)) <- tail;
    if tail = [] then ls else Lset.add tail ls
  in

  let deletemin_exclude ls c =
  (* delete the minimum not in the specified component *)
  (* return the pair (x,queue) *)
    if nodes.(c) = [] then (getmin ls, deletemin ls) else
      let ls_withoutc = Lset.remove nodes.(c) ls in
      let x = getmin ls_withoutc in
      let ls1 = deletemin ls_withoutc in
      let ls2 = Lset.add nodes.(c) ls1 in
      (x,ls2)
  in

  let deletemin_from_comp ls c =
  (* delete the minimum in the specified component *)
  (* return the pair (x,queue) *)
    let ls_withoutc = Lset.remove nodes.(c) ls in
    let x = List.hd nodes.(c) in
    nodes.(c) <- List.tl nodes.(c);
    let ls1 = if nodes.(c) = [] then ls_withoutc else Lset.add nodes.(c) ls_withoutc in
    (x,ls1)
  in

(* functions for dealing with the tightness data structure *)

  let lhs = Array.init ncomp (fun c -> 2 * (List.length nodes.(c))) in
  lhs.(center_component) <- 1;

  let initial_tight = fold 0 (ncomp-1) (fun i ac -> Pset.add (lhs.(i),i) ac) Pset.empty in

  let findtight tight total =
    (* assumes there are at least two things in tight *)
    (* returns a list consisting of either 0, 1, or 2 tight components. *)
    let (lhs1, c1) = Pset.max_elt tight in
    if lhs1 < total then [] else
      let (lhs2,c2) = Pset.max_elt (Pset.remove (lhs1,c1) tight) in
      if lhs2 < total then [c1] else [c1;c2]
  in

  let makemove tight i j =
  (* we're making a move to add an edge from O(i) to I(j) *)
  (* this updates the tightness data structure to reflect this change *)
    if i=j && i<>center_component then failwith "i=j";
    lhs.(i) <- lhs.(i) - 1;
    let tight = Pset.add (lhs.(i), i) (Pset.remove (lhs.(i)+1,i) tight) in
    if j=center_component then tight else (
      lhs.(j) <- lhs.(j) - 1;
      Pset.add (lhs.(j), j) (Pset.remove (lhs.(j)+1,j) tight)
    )
  in

(*---------------------------- compute the permutation ----------------------------*)

  let perm = Array.make n 0 in

  let rec scan i queue tight =
    if i=n-1 then (
      perm.(i) <- getmin queue;
    ) else (
      let total = n-i in  (* number of links left to be added *)
      let (x, queue) = if i <> center then
	  match findtight tight total with
	    | []                        -> deletemin_exclude queue comp.(i)
	    | [t1] when t1 = comp.(i)   -> deletemin_exclude queue comp.(i)
	    | [t1]                      -> deletemin_from_comp queue t1
	    | [t1;t2] ->                   let othercomp = if t1=comp.(i) then t2 else t1 in
				           deletemin_from_comp queue othercomp
	    | _ -> failwith "impossible"
	else
	  match findtight tight total with
	    | []                        -> (getmin queue, deletemin queue)
	    | [t1] when t1 = comp.(i)   -> (getmin queue, deletemin queue) (* probably impossible *)
	    | [t1]                      -> deletemin_from_comp queue t1
	    | [t1;t2] ->                   let othercomp = if t1=comp.(i) then t2 else t1 in
				           deletemin_from_comp queue othercomp (* probably impossible *)
	    | _ -> failwith "impossible"
      in
      perm.(i) <- x;
      let tight = makemove tight comp.(i) comp.(x) in
      scan (i+1) queue tight
    ) in

  ignore (scan 0 initial_queue initial_tight);

  printf "%d\n" solution_cost;
  for i=0 to n-1 do
    printf "%d%s" (perm.(i)+1) (if i=n-1 then "\n" else " ")
  done;


Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished.In total, Nastya dropped $$$n$$$ grains. Nastya read that each grain weighs some integer number of grams from $$$a - b$$$ to $$$a + b$$$, inclusive (numbers $$$a$$$ and $$$b$$$ are known), and the whole package of $$$n$$$ grains weighs from $$$c - d$$$ to $$$c + d$$$ grams, inclusive (numbers $$$c$$$ and $$$d$$$ are known). The weight of the package is the sum of the weights of all $$$n$$$ grains in it.Help Nastya understand if this information can be correct. In other words, check whether each grain can have such a mass that the $$$i$$$-th grain weighs some integer number $$$x_i$$$ $$$(a - b \leq x_i \leq a + b)$$$, and in total they weigh from $$$c - d$$$ to $$$c + d$$$, inclusive ($$$c - d \leq \sum\limits_{i=1}^{n}{x_i} \leq c + d$$$).

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 1000)$$$  — the number of test cases.  The next $$$t$$$ lines contain descriptions of the test cases, each line contains $$$5$$$ integers: $$$n$$$ $$$(1 \leq n \leq 1000)$$$  — the number of grains that Nastya counted and $$$a, b, c, d$$$ $$$(0 \leq b < a \leq 1000, 0 \leq d < c \leq 1000)$$$  — numbers that determine the possible weight of one grain of rice (from $$$a - b$$$ to $$$a + b$$$) and the possible total weight of the package (from $$$c - d$$$ to $$$c + d$$$).

For each test case given in the input print "Yes", if the information about the weights is not inconsistent, and print "No" if $$$n$$$ grains with masses from $$$a - b$$$ to $$$a + b$$$ cannot make a package with a total mass from $$$c - d$$$ to $$$c + d$$$.

NoteIn the first test case of the example, we can assume that each grain weighs $$$17$$$ grams, and a pack $$$119$$$ grams, then really Nastya could collect the whole pack.In the third test case of the example, we can assume that each grain weighs $$$16$$$ grams, and a pack $$$128$$$ grams, then really Nastya could collect the whole pack.In the fifth test case of the example, we can be assumed that $$$3$$$ grains of rice weigh $$$2$$$, $$$2$$$, and $$$3$$$ grams, and a pack is $$$7$$$ grams, then really Nastya could collect the whole pack.In the second and fourth test cases of the example, we can prove that it is impossible to determine the correct weight of all grains of rice and the weight of the pack so that the weight of the pack is equal to the total weight of all collected grains.

(* Codeforces 1341 A Nastya and Rice train *)

(* you can use either gr or rdln but not both *)
let gr () = Scanf.scanf " %d" (fun i -> i);;
let grf () = Scanf.scanf " %f" (fun i -> i);;
let grl () = Scanf.scanf " %Ld" (fun i -> i);;
let rdln() = input_line stdin;;
(* let spli s = Str.split (Str.regexp " ") s;; *)
let printlisti li = List.iter (fun i -> (print_int i; print_string " ")) li;;
let printarri ai = Array.iter (fun i -> (print_int i; print_string " ")) ai;;
let debug = false;;

(* reading reversed list *)
let rec readlist n acc = match n with
	| 0 -> acc
	| _ -> readlist (n -1) (gr() :: acc);;
let printlisti li = List.iter (fun i -> (print_int i; print_string " ")) li;;
let printlists ls = List.iter (fun s -> (print_string s; print_string " ")) ls;;
let list_to_s li = (String.concat " " (List.map string_of_int li));;

let intersect al ar bl br =
	if al < bl then ar >= bl
	else if al <= br then true
	else false;;

let rec consistent n a b c d =
	let min = n * (a-b) in
	let max = n * (a+b) in
	let cons = intersect min max (c-d) (c+d) in
	(* let _ = Printf.printf "min max cons = %d %d %b\n" min max cons in *)
	cons;;

let do_one () =
  let n = gr () in
  let a = gr () in
  let b = gr () in
  let c = gr () in
  let d = gr () in
	let co = consistent n a b c d in
	let ans = if co then "Yes" else "No" in
	begin
    print_string ans;
    print_string "\n"
	end;;

let rec do_all t = match t with
	| 0 -> ()
	| _ ->
		begin
			do_one ();
			do_all (t-1)
		end;;

let main() =
	let t = gr () in
	do_all t;;

main();;


To get money for a new aeonic blaster, ranger Qwerty decided to engage in trade for a while. He wants to buy some number of items (or probably not to buy anything at all) on one of the planets, and then sell the bought items on another planet. Note that this operation is not repeated, that is, the buying and the selling are made only once. To carry out his plan, Qwerty is going to take a bank loan that covers all expenses and to return the loaned money at the end of the operation (the money is returned without the interest). At the same time, Querty wants to get as much profit as possible.The system has n planets in total. On each of them Qwerty can buy or sell items of m types (such as food, medicine, weapons, alcohol, and so on). For each planet i and each type of items j Qwerty knows the following: aij — the cost of buying an item;  bij — the cost of selling an item;  cij — the number of remaining items.It is not allowed to buy more than cij items of type j on planet i, but it is allowed to sell any number of items of any kind.Knowing that the hold of Qwerty's ship has room for no more than k items, determine the maximum profit which Qwerty can get.

The first line contains three space-separated integers n, m and k (2 ≤ n ≤ 10, 1 ≤ m, k ≤ 100) — the number of planets, the number of question types and the capacity of Qwerty's ship hold, correspondingly. Then follow n blocks describing each planet. The first line of the i-th block has the planet's name as a string with length from 1 to 10 Latin letters. The first letter of the name is uppercase, the rest are lowercase. Then in the i-th block follow m lines, the j-th of them contains three integers aij, bij and cij (1 ≤ bij < aij ≤ 1000, 0 ≤ cij ≤ 100) — the numbers that describe money operations with the j-th item on the i-th planet. The numbers in the lines are separated by spaces. It is guaranteed that the names of all planets are different.

Print a single number — the maximum profit Qwerty can get.

NoteIn the first test case you should fly to planet Venus, take a loan on 74 units of money and buy three items of the first type and 7 items of the third type (3·6 + 7·8 = 74). Then the ranger should fly to planet Earth and sell there all the items he has bought. He gets 3·9 + 7·9 = 90 units of money for the items, he should give 74 of them for the loan. The resulting profit equals 16 units of money. We cannot get more profit in this case.

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make_matrix n m 0 in
  let b = Array.make_matrix n m 0 in
  let c = Array.make_matrix n m 0 in
  let () =
    for i = 0 to n - 1 do
      let _name = Scanf.bscanf sb "%s " (fun s -> s) in
	for j = 0 to m - 1 do
	  a.(i).(j) <- Scanf.bscanf sb "%d " (fun s -> s);
	  b.(i).(j) <- Scanf.bscanf sb "%d " (fun s -> s);
	  c.(i).(j) <- Scanf.bscanf sb "%d " (fun s -> s);
	done
    done;
  in
  let res = ref 0 in
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	if i <> j then (
	  let d = Array.make m (0, 0) in
	    for l = 0 to m - 1 do
	      d.(l) <- (b.(j).(l) - a.(i).(l), c.(i).(l))
	    done;
	    Array.sort compare d;
	    let k = ref k in
	    let p = ref (m - 1) in
	    let r = ref 0 in
	      while !k > 0 && !p >= 0 do
		let (pr, c) = d.(!p) in
		  if pr > 0 then (
		    let c = min c !k in
		      k := !k - c;
		      r := !r + pr * c;
		  );
		  decr p;
	      done;
	      res := max !res !r
	)
      done
    done;
    Printf.printf "%d\n" !res


An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons — 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: "0124:5678:90ab:cdef:0124:5678:90ab:cdef". We'll call such format of recording an IPv6-address full.Besides the full record of an IPv6 address there is a short record format. The record of an IPv6 address can be shortened by removing one or more leading zeroes at the beginning of each block. However, each block should contain at least one digit in the short format. For example, the leading zeroes can be removed like that: "a56f:00d3:0000:0124:0001:f19a:1000:0000"  →  "a56f:d3:0:0124:01:f19a:1000:00". There are more ways to shorten zeroes in this IPv6 address.Some IPv6 addresses contain long sequences of zeroes. Continuous sequences of 16-bit zero blocks can be shortened to "::". A sequence can consist of one or several consecutive blocks, with all 16 bits equal to 0. You can see examples of zero block shortenings below:  "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::";  "a56f:0000:0000:0124:0001:0000:1234:0ff0"  →  "a56f::0124:0001:0000:1234:0ff0";  "a56f:0000:0000:0000:0001:0000:1234:0ff0"  →  "a56f:0000::0000:0001:0000:1234:0ff0";  "a56f:00d3:0000:0124:0001:0000:0000:0000"  →  "a56f:00d3:0000:0124:0001::0000";  "0000:0000:0000:0000:0000:0000:0000:0000"  →  "::". It is not allowed to shorten zero blocks in the address more than once. This means that the short record can't contain the sequence of characters "::" more than once. Otherwise, it will sometimes be impossible to determine the number of zero blocks, each represented by a double colon.The format of the record of the IPv6 address after removing the leading zeroes and shortening the zero blocks is called short.You've got several short records of IPv6 addresses. Restore their full record.

The first line contains a single integer n — the number of records to restore (1 ≤ n ≤ 100). Each of the following n lines contains a string — the short IPv6 addresses. Each string only consists of string characters "0123456789abcdef:". It is guaranteed that each short address is obtained by the way that is described in the statement from some full IPv6 address.

For each short IPv6 address from the input print its full record on a separate line. Print the full records for the short IPv6 addresses in the order, in which the short records follow in the input.

(* Codeforces 250B *)

let gr () = Scanf.scanf " %d" (fun i -> i);;
let rdln() = input_line stdin;;
let spli s = Str.split (Str.regexp " ") s;;

let rec fill0 s =
	if String.length s >= 4 then s
	else fill0 ("0" ^ s);;

let rec repeat0 n = match n with
	| 0 -> "0000"
	| _ -> "0000:" ^ repeat0 (n -1);;

let doTerm s ndiff = match s with
	| "Z" -> repeat0 ndiff
	| _ -> fill0 s;;

let rec priList ls sep = match ls with
	| [] -> "!!!ERROR!!!"
	| h :: [] -> h
	| h :: t -> h ^ sep ^ priList t sep;;

let main () =
	let sn = rdln() in
	let n = int_of_string sn in
	begin
		for i = 0 to (n-1) do
			let s = rdln() in
			let sz = Str.global_replace (Str.regexp "::") ":Z:" s in
			let ss = Str.split (Str.regexp ":") sz in
			let diff = 8 - List.length ss in
			let ssm = List.map (fun x -> doTerm x diff) ss in
			let prs = priList ssm ":" in
			print_string (prs ^ "\n")
		done
	end;;

main();;


Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.Dwarf Misha has already chosen the subject for his thesis: determining by two dwarven genomes, whether they belong to the same race. Two dwarves belong to the same race if we can swap two characters in the first dwarf's genome and get the second dwarf's genome as a result. Help Dwarf Misha and find out whether two gnomes belong to the same race or not.

The first line contains the first dwarf's genome: a non-empty string, consisting of lowercase Latin letters. The second line contains the second dwarf's genome: a non-empty string, consisting of lowercase Latin letters. The number of letters in each genome doesn't exceed 105. It is guaranteed that the strings that correspond to the genomes are different. The given genomes may have different length.

Print "YES", if the dwarves belong to the same race. Otherwise, print "NO".

Note  First example: you can simply swap two letters in string "ab". So we get "ba".  Second example: we can't change string "aa" into string "ab", because "aa" does not contain letter "b".

let a = read_line () in
let b = read_line () in
let x, y = ref [], ref [] in
let na = String.length a in
let nb = String.length b in
for i = 0 to min na nb - 1 do
  if a.[i] <> b.[i] then begin
    x := a.[i] :: !x;
    y := b.[i] :: !y
  end
done;
let m = List.length !x in
let sort = List.sort (fun a b -> Char.code a - Char.code b) in
print_endline (if na = nb && m = 2 && sort !x = sort !y
  then "YES" else "NO")

open String;;
let diff s a b =
        let l = ref [] in
         for i = 0 to length a - 1 do
                if a.[i] <> b.[i] then
                        l := (i) :: (!l)
                done;
        !l;;

let swap a h k =
        let n = a.[h] in
        a.[h] <- a.[k];
        a.[k] <- n;;

let ch l a b= match l with
        [] -> false
        |h:: t -> match t with
                [] -> false
                |k :: [] -> swap a h k;a = b
                |t :: k -> false
;;
let main _ =
        let a  = Scanf.scanf "%s\n" (fun a -> a) in
        let b  = Scanf.scanf "%s\n" (fun a -> a) in
           if length a <> length b
           then print_endline "NO"
           else
                        let l = diff [] a b in
                                if (ch l a b)
                                then print_endline "YES"
                                else print_endline "NO"
;;
main ();;

let solve a b =
  let rec loop lst1 lst2 cnt =
    match lst1 with
      | [] -> if cnt <= 2 then true else false
      | h :: t ->
	if h = List.hd lst2 then loop t (List.tl lst2) cnt
	else loop t (List.tl lst2) (cnt+1)
  in
  if List.sort compare a = List.sort compare b && loop a b 0 then "YES"
  else "NO"

let _ =
  let a = (Scanf.scanf " %s" (Str.split (Str.regexp ""))) in
  let b = (Scanf.scanf " %s" (Str.split (Str.regexp ""))) in
  Printf.printf "%s\n" (solve a b)

let solve a b =
  let sorted_a = List.sort compare a in
  let sorted_b = List.sort compare b in
  if sorted_a = sorted_b then "YES" else "NO"

let _ =
  let a = (Scanf.scanf " %s" (Str.split (Str.regexp ""))) in
  let b = (Scanf.scanf " %s" (Str.split (Str.regexp ""))) in
  Printf.printf "%s\n" (solve a b)