open Printf
open Scanf

let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)
let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))
let () =
  let cases = read_int () in

  for case = 1 to cases do
    let n = read_int() in
    let stats = Array.init n read_pair in
    let a2 = forall 0 (n-2) (fun i ->
      let (pi,ci) = stats.(i) in
      let (pi',ci') = stats.(i+1) in
      pi <= pi' && ci <= ci' &&	(pi' - pi) >= (ci' - ci)
    ) in
    let a1 = forall 0 (n-1) (fun i -> let (pi,ci) = stats.(i) in ci <= pi) in
    if a1 && a2 then printf "YES\n" else printf "NO\n"
  done

let scan_int () = Scanf.scanf " %d" (fun x -> x);;
let scan_int_pair () = let x = scan_int() in let y = scan_int() in (x,y);;
let show_string s = print_string s;;

let t = scan_int ();;
for x = 1 to t do
	let n = scan_int () in
	let player = ref 0 in
	let clear = ref 0 in
	let test = ref true in
	for i = 0 to n-1 do
		let p, c = scan_int_pair () in
		if !player > p  || !clear > c || (p - !player) < (c - !clear) then
			test := false;
		player := p; clear := c
	done;
	if !test then show_string "YES\n" else show_string "NO\n"
done;;

open Printf
open Scanf

let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)
let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))
let () =
  let cases = read_int () in

  for case = 1 to cases do
    let n = read_int() in
    let stats = Array.init n read_pair in
    let answer = forall 0 (n-2) (fun i ->
      let (pi,ci) = stats.(i) in
      let (pi',ci') = stats.(i+1) in
      pi <= pi' && ci <= ci' && ci <= pi && ci' <= pi' &&
	(pi' - pi) >= (ci' - ci')
    ) in
    if answer then printf "YES\n" else printf "NO\n"
  done

open Printf
open Scanf

let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)
let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))
let () =
  let cases = read_int () in

  for case = 1 to cases do
    let n = read_int() in
    let stats = Array.init n read_pair in
    let answer = forall 0 (n-2) (fun i ->
      let (pi,ci) = stats.(i) in
      let (pi',ci') = stats.(i+1) in
      pi <= pi' && ci <= ci' && ci <= pi && ci' <= pi'
    ) in
    if answer then printf "YES\n" else printf "NO\n"
  done

open Printf
open Scanf

let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)
let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))
let () =
  let cases = read_int () in

  for case = 1 to cases do
    let n = read_int() in
    let stats = Array.init n read_pair in
    let answer = forall 0 (n-2) (fun i ->
      let (pi,ci) = stats.(i) in
      let (pi',ci') = stats.(i+1) in
      pi <= pi' && ci <= ci' && ci <= pi && ci' <= pi' &&
	(pi' - pi) >= (ci' - ci)
    ) in
    if answer then printf "YES\n" else printf "NO\n"
  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 maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)
let minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)

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

  let a = Array.init n (fun _ -> read_int()) in

  let mina = minf 0 (n-1) (fun i -> a.(i)) in
  let maxa = maxf 0 (n-1) (fun i -> a.(i)) in

  if maxa - mina > k then (
    printf "NO\n"
  ) else (
    printf "YES\n";
    for i=0 to n-1 do
      let ct = Array.make k 0 in
      ct.(k-1) <- mina;

      let rec loop j ac =
	if ac=a.(i) then () else (
	  ct.(j) <- ct.(j) + 1;
	  loop (j+1) (ac+1)
	)
      in

      loop 0 mina;
      for c=0 to k-1 do
	for l=1 to ct.(c) do
	  printf "%d " (c+1)
	done
      done;
      print_newline()
    done
  )

let () =
    Scanf.scanf "%d %d\n" (fun n k ->
        let piles = Array.init n (fun _ -> Scanf.scanf "%d%_c" (fun x -> x)) in
        (* smallest/largest  pile size *)
        let min = Array.fold_left min piles.(0) piles
        and max = Array.fold_left max piles.(0) piles in

        (* check whether it's possible *)
        if max - min > k then
            print_endline "NO"
        else begin
            print_endline "YES";

            (* fill out each pile with colour 1 *)
            for i = 0 to n - 1 do
                for j = 1 to piles.(i) do
                    if j > 1 then print_char ' ';
                    if j > min
                    then print_int (j - min)
                    else print_int 1
                done;
                print_endline ""
            done
        end
    )

open Printf
open Scanf

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

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

  let a = Array.init n (fun _ -> read_int()) in

  let mina = minf 0 (n-1) (fun i -> a.(i)) in
  let maxa = maxf 0 (n-1) (fun i -> a.(i)) in

  if maxa - mina > k then (
    printf "NO\n"
  ) else (
    for i=0 to n-1 do
      let ct = Array.make k 0 in
      ct.(k-1) <- mina;

      let rec loop j ac =
	if ac=a.(i) then () else (
	  ct.(j) <- ct.(j) + 1;
	  loop (j+1) (ac+1)
	)
      in

      loop 0 mina;
      for c=0 to k-1 do
	for l=1 to ct.(c) do
	  printf "%d " (c+1)
	done
      done;
      print_newline()
    done
  )


let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let l = k - 1
  and r = n - k in
    if l < r then (
      for i = 1 to l do
	Printf.printf "LEFT\n"
      done;
      for i = 0 to n - 1 do
	Printf.printf "PRINT %c\n" s.[i];
	if i < n - 1
	then Printf.printf "RIGHT\n"
      done;
    ) else (
      for i = 1 to r do
	Printf.printf "RIGHT\n"
      done;
      for i = n - 1 downto 0 do
	Printf.printf "PRINT %c\n" s.[i];
	if i > 0
	then Printf.printf "LEFT\n"
      done;
    )

let sr=read_line();;
let rec ind i=if sr.[i]=' ' then i else ind (i+1);;
let id=ind 0;;
let n=int_of_string(String.sub sr 0 id) and k=int_of_string(String.sub sr (id+1) (String.length(sr)-1-id));;

let s=read_line();;
if k<=n/2 then
   begin
   for i=1 to k-1 do
      Printf.printf "LEFT\n"
   done;
   for i=0 to n-1 do
      print_string("PRINT "^(String.sub s i 1)^"\n");
      if i<>n-1 then Printf.printf "RIGHT\n"
   done
   end
else
   begin
   for i=k to n-1 do
      Printf.printf "RIGHT\n"
   done;
   for i=n-1 downto 0 do
      print_string("PRINT "^(String.sub s i 1)^"\n");
      if i<>0 then Printf.printf "LEFT\n"
   done
   end;;

open Printf
open Scanf

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

let reverse str =
    let n = String.length str in
    let res = String.create n in
    for i = 0 to n - 1 do
        res.[i] <- str.[n - 1 - i]
    done;
    res in

let n = read_int () in
let k = read_int () in
let s = read_string () in

let res_f sep i c =
    if i > 0 then printf "%s\n" sep;
    printf "PRINT %c\n" c in

if k - 1 <= n - k then begin
    for i = 1 to k - 1 do
        printf "LEFT\n"
    done;
    String.iteri (res_f "RIGHT") s
end else begin
    for i = 1 to n - k do
        printf "RIGHT\n"
    done;
    String.iteri (res_f "LEFT") (reverse s)
end ;;

open Printf
open Scanf

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

let reverse str =
    let n = String.length str in
    let res = String.create n in
    for i = 0 to n - 1 do
        res.[i] <- str.[n - 1 - i]
    done;
    res in

let n = read_int () in
let k = read_int () in
let s = read_string () in

let res_f sep i c =
    if i > 0 then printf "%s\n" sep;
    printf "PRINT %c\n" c in

printf "%d %d %s\n" n k s;

if k - 1 <= n - k then begin
    for i = 1 to k - 1 do
        printf "LEFT\n"
    done;
    String.iteri (res_f "RIGHT") s
end else begin
    for i = 1 to n - k do
        printf "RIGHT\n"
    done;
    String.iteri (res_f "LEFT") (reverse s)
end ;;


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

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

let () =
  let n = read_int () in
  let k = read_int () in
  let s = read_string () in

  let solve a =
  (* a is an array of n+2 bits (0s or 1s).  We added an extra 0 at start and end
     what's the maximum block of 1s we can make by toggling at most k 0s to 1s. *)
    let nzeros = sum 1 n (fun i -> if a.(i) = 0 then 1 else 0) in
    if nzeros <= k then n else (

      let next = Array.make (n+2) 0 in
      let prev = Array.make (n+2) 0 in

      let rec scan i p = if i<n+2 then
	  if a.(i) = 0 then (
	    prev.(i) <- p;
	    next.(p) <- i;
	    scan (i+1) i
	  ) else (
	    scan (i+1) p
	  )
      in

      scan 1 0;

      if k=0 then (
	 maxf 0 n (fun i -> next.(i) - i - 1)
      ) else (
	let rec step i steps = if steps=0 then i else step next.(i) (steps-1) in
	let rec scan i j ac = if j=n+1 then ac else (
	  (* evaluate this (i,j) option. *)
	  let pi = prev.(i) in
	  let nj = next.(j) in
	  let ac = max ac (nj-pi-1) in
	  scan next.(i) next.(j) ac
	) in

	let i = next.(0) in
	let j = step i (k-1) in
	scan i j 0
      )
    )
  in

  let ma c = Array.init (n+2) (fun i -> if i-1 < 0 || i-1 > n-1 then 0 else if s.[i-1] = c then 1 else 0) in
  let answer = max (solve (ma 'a')) (solve (ma 'b')) in

  printf "%d\n" answer

let [n; k] = read_line () |> Str.(split (regexp " ")) |> List.map int_of_string
let s = read_line ()

exception Break of int;;

let max_charm_at_start ch =
  let mana = ref k in
  try
    for i = 0 to n-1 do
      if s.[i] != ch then
        decr mana;
      if !mana < 0 then
        raise (Break i)
    done;
    n
  with
  | Break i -> i

let max_charm ch =
  let left = ref 0
  and right = ref (max_charm_at_start ch) in
  let best = ref !right in
  while !right < n do
    if s.[!right] != ch then
      begin
        while s.[!left] == ch do
          incr left
        done;
        incr left
      end;
    incr right;
    if !right - !left > !best then
      best := !right - !left
  done;
  !best

let () =
  max (max_charm 'a') (max_charm 'b')
  |> Printf.printf "%d\n"


let print_array a =
	for k = 0 to (Array.length a) - 1 do
		print_int a.(k);
		print_char ' ';
	done;

	print_newline ();
;;

let read_array ?(delta=0) n =
	let arr = Array.make n 0 in
	begin
		for k=0 to (n - 1) do
			Scanf.bscanf Scanf.Scanning.stdin " %i" (fun v -> arr.(k) <- v + delta;);
		done;
		arr
	end
;;

let permute_array a p =
	let n = Array.length a in
	let a' = Array.make n 0 in
	begin
		for k = 0 to (n - 1) do
			a'.( p.(k) ) <- a.(k);
		done;
		a'
	end
;;

let permute a p =
	let n = Array.length a in
	let a' = Array.make n 0 in
	let p' = Array.make n 0 in
	begin
		for k = 0 to (n - 1) do
			a'.( p.(k) ) <- a.(k);
			p'.( p.(k) ) <- k;
		done;
		(a', p')
	end
;;

(* a_permuted - sequence "a" permuted so that \forall k: A_permuted[ P[k] ] = A[ k ]  *)
let calc_b a_permuted l r =
	let n = Array.length a_permuted in
	let b = Array.make n 0 in
	let b_last = ref l in (* B[ k - 1 ] *)
	begin

		b.(0) <- !b_last;

		let c = ref (!b_last - a_permuted.(0)) in (* minimum possible c - corresponds to the smallest P[k] *)
		let k = ref 1 in
		while (!k < n) && (!b_last <= r) do
			c := (!c + 1);
			b_last := max l (!c + a_permuted.(!k));
			b.(!k) <- !b_last;
			c := !b_last - a_permuted.(!k);
			k := !k + 1;
		done;

		if !b_last <= r then Some b else None

	end
;;

let load_and_process_data n l r =
	let a = read_array n in
	let p = read_array n ~delta:(-1) in
	let (a', p') = permute a p in
	let b = calc_b a' l r in
	match b with
	| Some l -> print_array (permute_array l p')
	| None -> print_endline "-1"
;;

let read_input () =
	Scanf.bscanf Scanf.Scanning.stdin " %i %i %i " load_and_process_data
;;

read_input ()

let print_array a =
	for k = 0 to (Array.length a) - 1 do
		print_int a.(k);
		print_char ' ';
	done;

	print_newline ();
;;

let read_array ?(delta=0) n =
	let arr = Array.make n 0 in
	begin
		for k=0 to (n - 1) do
			Scanf.bscanf Scanf.Scanning.stdin " %i" (fun v -> arr.(k) <- v + delta;);
		done;
		arr
	end
;;

let permute_array a p =
	let n = Array.length a in
	let a' = Array.make n 0 in
	begin
		for k = 0 to (n - 1) do
			a'.( p.(k) ) <- a.(k);
		done;
		a'
	end
;;

let invert_permutation p =
	let n = Array.length p in
	let p' = Array.make n 0 in
	begin
		for k = 0 to (n - 1) do
			p'.( p.(k) ) <- k;
		done;
		p'
	end
;;

(* a_permuted - sequence "a" permuted so that \forall k: A_permuted[ P[k] ] = A[ k ]  *)
let calc_b a_permuted l r =
	let n = Array.length a_permuted in
	let b = Array.make n 0 in
	let b_last = ref l in (* B[ k - 1 ] *)
	begin

		b.(0) <- !b_last;

		let c = ref (!b_last - a_permuted.(0)) in (* minimum possible c - corresponds to the smallest P[k] *)
		let k = ref 1 in
		while (!k < n) && (!b_last <= r) do
			c := (!c + 1);
			b_last := max l (!c + a_permuted.(!k));
			b.(!k) <- !b_last;
			c := !b_last - a_permuted.(!k);
			k := !k + 1;
		done;

		if !b_last <= r then Some b else None

	end
;;

let load_and_process_data n l r =
	let a = read_array n in
	let p = read_array n ~delta:(-1) in
	let b = calc_b (permute_array a p) l r in
	match b with
	| Some l -> print_array (permute_array l (invert_permutation p))
	| None -> print_endline "-1"
;;

let read_input () =
	Scanf.bscanf Scanf.Scanning.stdin " %i %i %i " load_and_process_data
;;

read_input ()

let print_array a =
	for k = 0 to (Array.length a) - 1 do
		print_int a.(k);
		print_char ' ';
	done;

	print_newline ();
;;

let read_array ?(delta=0) n =
	let arr = Array.make n 0 in
	begin
		for k=0 to (n - 1) do
			Scanf.bscanf Scanf.Scanning.stdin " %i" (fun v -> arr.(k) <- v + delta;);
		done;
		arr
	end
;;

let invert_permutation p =
	let n = Array.length p in
	let p' = Array.make n 0 in
	begin
		for k = 0 to (n - 1) do
			p'.( p.(k) ) <- k;
		done;
		p'
	end
;;

(* p' - invert function to p, i.e. the function restoring back the permutation created by p *)
let calc_b a p' l r =
	let n = Array.length a in
	let b = Array.make n 0 in
	let b_last = ref l in (* B[ k - 1 ] *)
	let k' = ref p'.( 0 ) in
	begin

		b.( !k' ) <- !b_last;

		let a_cur = ref a.( !k' ) in
		let c = ref (!b_last - !a_cur) in (* minimum possible c - corresponds to the smallest P[k] *)
		let k = ref 1 in
		while (!k < n) && (!b_last <= r) do
			k' := p'.( !k );
			a_cur := a.( !k' );
			c := (!c + 1);
			b_last := max l (!c + !a_cur);
			b.(!k') <- !b_last;
			c := !b_last - !a_cur;
			k := !k + 1;
		done;

		if !b_last <= r then Some b else None

	end
;;

let load_and_process_data n l r =
	let a = read_array n in
	let p = read_array n ~delta:(-1) in
	let b = calc_b a (invert_permutation p) l r in
	match b with
	| Some l -> print_array l
	| None -> print_endline "-1"
;;

let read_input () =
	Scanf.bscanf Scanf.Scanning.stdin " %i %i %i " load_and_process_data
;;

read_input ()

let () =
  Scanf.scanf "%d %d %d " @@ fun n l r ->
  let a = Array.init n (fun _ -> Scanf.scanf "%d " (fun x -> x)) in
  let p = Array.init n (fun _ -> Scanf.scanf "%d " (fun x -> x)) in
  let b = Array.make n 0 in
  let revp = Array.make n 0 in
  Array.iteri (fun i j -> revp.(j - 1) <- i) p;
  let rec loop prevc i =
    if i < n then
      let j = revp.(i) in
      b.(j) <- max l (a.(j) + prevc + 1);
      if b.(j) > r then
        false
      else
        loop (b.(j) - a.(j)) (i + 1)
    else true in
  if loop (l - r - 1) 0 then
    Array.to_list b |> List.map string_of_int |> String.concat " " |> print_endline
  else
    print_endline "-1"


let input () =
  let n = Scanf.scanf " %d " (fun x -> x) in
  let a = ref 0 in
  let l = ref [] in
  for i = 1 to n do
    if i = n then
      a := Scanf.scanf "%d\n" (fun x -> x)
    else
      a := Scanf.scanf " %d " (fun x -> x);

    l := !a :: !l;
  done;
  List.rev !l

let () =
  let rec scan l n head turn_down index =
    match l with
    | [] -> Printf.printf "-1\n"
    | t :: [] ->
       begin
	 match n with
	 | 2 ->
	    if (t <= head) then
	      Printf.printf "%d\n" (index - turn_down)
	    else
	      Printf.printf "-1\n"
	 | 1 ->
	    Printf.printf "0\n"
	 | _ ->
	    Printf.printf "-1\n"
       end
    | last :: ((h :: t) as tl) ->
       if n <= 2 then
	 if h >= last then
	   scan tl n head turn_down (index+1)
	 else
	   scan tl (n+1) head index (index+1)
       else
	 Printf.printf "%d\n" (-1)
  in
  let l = input () in
  scan l 1 (List.hd l) (-1) 1

let pf = Printf.printf ;;
let epf = Printf.eprintf ;;
let sf = Scanf.scanf ;;

let (|>) x f = f x ;;

module Array = ArrayLabels ;;
module List  = ListLabels ;;

let solve n arr =
  let prev = ref arr.(0) in
  let rec iter i =
    if i = n then n
    else if !prev > arr.(i) then i
    else begin prev := arr.(i); iter (i + 1) end in
  let last = iter 1 in
  if last = n then pf "0"
  else
    let prev = ref arr.(last) in
    let rec iter i =
      if i = n then n
      else if !prev > arr.(i) then i
      else begin prev := arr.(i);  iter (i + 1) end in
    let l = iter (last + 1) in
    if l = n && arr.(n - 1) <= arr.(0) then pf "%d\n" (n - last)
    else pf "-1\n"
;;

let () =
  sf "%d " (fun n ->
    let arr = Array.init n ~f:(fun _ -> sf "%d " (fun i -> i)) in
    solve n arr)
;;

let pf = Printf.printf ;;
let epf = Printf.eprintf ;;
let sf = Scanf.scanf ;;

let (|>) x f = f x ;;

module Array = ArrayLabels ;;
module List  = ListLabels ;;

let solve n arr =
  let prev = ref arr.(0) in
  let rec iter i =
    if i = n then n
    else if !prev > arr.(i) then i
    else begin prev := arr.(i); iter (i + 1) end in
  let last = iter 1 in
  if last = n then pf "0"
  else
    let prev = ref arr.(last) in
    let rec iter i =
      if i = n then n
      else if !prev > arr.(i) then i
      else begin prev := arr.(i);  iter (i + 1) end in
    let l = iter (last + 1) in
    if l = n && arr.(n - 1) < arr.(0) then pf "%d\n" (n - last)
    else pf "-1\n"
;;

let () =
  sf "%d " (fun n ->
    let arr = Array.init n ~f:(fun _ -> sf "%d " (fun i -> i)) in
    solve n arr)
;;

let input () =
  let n = Scanf.scanf " %d " (fun x -> x) in
  let a = ref 0 in
  let l = ref [] in
  for i = 1 to n do
    if i = n then
      a := Scanf.scanf "%d\n" (fun x -> x)
    else
      a := Scanf.scanf " %d " (fun x -> x);

    l := !a :: !l;
  done;
  List.rev !l

let () =
  let rec scan l n head turn_down index =
    match l with
    | [] -> Printf.printf "-1\n"
    | t :: [] ->
       if n = 2 then
	 if t <= head then
	   Printf.printf "%d\n" (index - turn_down)
	 else
	   Printf.printf "-1\n"
       else
	 Printf.printf "0\n"
    | last :: ((h :: t) as tl) ->
       if n <= 2 then
	 if h >= last then
	   scan tl n head turn_down (index+1)
	 else
	   scan tl (n+1) head index (index+1)
       else
	 Printf.printf "%d\n" (-1)
  in
  let l = input () in
  scan l 1 (List.hd l) (-1) 1

let input () =
  let n = Scanf.scanf " %d " (fun x -> x) in
  let a = ref 0 in
  let l = ref [] in
  for i = 1 to n do
    if i = n then
      a := Scanf.scanf "%d\n" (fun x -> x)
    else
      a := Scanf.scanf " %d " (fun x -> x);

    l := !a :: !l;
  done;
  List.rev !l

let () =
  let rec scan l n head turn_down index =
    match l with
    | [] -> Printf.printf "-1\n"
    | t :: [] ->
       begin
	 match n with
	 | 2 ->
	    if (t <= head) then
	      Printf.printf "%d\n" (index - turn_down)
	    else
	      Printf.printf "-1\n"
	 | 1 ->
	    Printf.printf "0\n"
	 | _ ->
	    Printf.printf "-1\n"
       end
    | last :: ((h :: t) as tl) ->
       if n <= 2 then
	 if h >= last then
	   scan tl n head (index+1) (index+1)
	 else
	   scan tl (n+1) head index (index+1)
       else
	 Printf.printf "%d\n" (-1)
  in
  let l = input () in
  scan l 1 (List.hd l) (-1) 1


let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
  in
  let ks = ref [] in
  let ht = Hashtbl.create 10 in
  let prev = ref (-1) in
    for i = 0 to n - 1 do
      if Hashtbl.mem ht a.(i) then (
	ks := (!prev + 1, i) :: !ks;
	prev := i;
	Hashtbl.clear ht;
      ) else (
	Hashtbl.replace ht a.(i) ()
      )
    done;
    let ks =
      if !prev = n - 1
      then !ks
      else (
	match !ks with
	  | [] ->
	      Printf.printf "-1\n";
	      exit 0
	  | (l, r) :: ks ->
	      (l, n - 1) :: ks
      )
    in
    let ks = List.rev ks in
      Printf.printf "%d\n" (List.length ks);
      List.iter
	(fun (l, r) ->
	   Printf.printf "%d %d\n" (l + 1) (r + 1)
	) ks

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

let find_segs xs =
  let rec find_segs_aux i xs seen acc =
    match xs with
    | [] -> acc
    | [x] -> begin
      match acc with
      | [] ->
          if IntSet.mem x seen
          then [ 1, i ]
          else []
      | (lo, hi)::rest ->
          if IntSet.mem x seen
          then (hi + 1, i) :: (lo, hi) :: rest
          else (lo, i) :: rest
    end
    | x :: xs -> begin
      match acc with
      | [] ->
          if IntSet.mem x seen
          then find_segs_aux (i + 1) xs (IntSet.empty) [ 1, i ]
          else find_segs_aux (i + 1) xs (IntSet.add x seen) []
      | (lo, hi)::rest ->
          if IntSet.mem x seen
          then find_segs_aux (i + 1) xs (IntSet.empty) ((hi + 1, i)::acc)
          else find_segs_aux (i + 1) xs (IntSet.add x seen) acc
    end
  in
  find_segs_aux 1 xs IntSet.empty []

let print_output = function
  | [] -> print_int (-1); print_newline ()
  | xs ->
      print_int (List.length xs);
      print_newline ();
      List.iter (fun (lo, hi) ->
        print_int lo;
        print_string " ";
        print_int hi;
        print_newline ()) xs

let () =
  ignore (read_line ()); read_line ()
  |> Str.split (Str.regexp " ")
  |> List.map int_of_string
  |> find_segs
  |> print_output

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

let () =
  let rec find a l r x =
    let m = (l + r) / 2 in
    if a.(m) = x then m
    else (
      if a.(m) < x then (find a (m + 1) r x)
      else (find a l (m - 1) x)
    )
  in

  let min x y =
    if x < y then x
    else y
  in

  let n = xint() in
  let a = Array.make n 0 in
  let xs = Array.make n 0 and m = ref 0 in

  for i = 0 to n - 1 do
    a.(i) <- xint();
    xs.(i) <- a.(i);
  done;
  Array.sort (fun x y -> x - y) xs;
  m := 1;
  for i = 1 to n - 1 do
    if xs.(i) != xs.(i - 1) then (
      xs.(!m) <- xs.(i);
      m := !m + 1;
    )
  done;

  let nx = Array.make n n and pos = Array.make !m n in

  for i = n - 1 downto 0 do
    a.(i) <- find xs 0 (!m - 1) a.(i);
    nx.(i) <- pos.(a.(i));
    pos.(a.(i)) <- i;
  done;

  let l = Array.make n 0 and r = Array.make n 0 in
  let ret = ref 0 and i = ref 0 in
  while !i < n do
    let x = !i and y = ref nx.(!i) in
    while !i < !y do
      y := min !y nx.(!i);
      i := !i + 1;
    done;
    if !y != n then (
      l.(!ret) <- x + 1;
      r.(!ret) <- !y + 1;
      ret := !ret + 1;
    );
    if !y = n && x != 0 then (
      r.(!ret - 1) <- n;
    );
    i := !i + 1;
  done;

  if !ret = 0 then (
    Printf.printf "-1\n";
  ) else (
    Printf.printf "%d\n" !ret;
    for i = 0 to !ret - 1 do
      Printf.printf "%d %d\n" l.(i) r.(i);
    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.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let a = Array.init n (fun _ -> read_int()) in

  let find_segment i =
  (* find segment starting from i.  either Some (i,j) or None *)
    let h = Hashtbl.create 5 in
    let rec loop j = if j>=n then None else
	if Hashtbl.mem h a.(j) then Some (i,j) else (
	  Hashtbl.add h a.(j) true;
	  loop (j+1)
	)
    in
    if i >= n then None else (
      Hashtbl.add h a.(i) true;
      loop (i+1)
    )
  in

  let rec outer_loop i ac =
    match find_segment i with
      | Some (_,j) -> outer_loop (j+1) ((i,j)::ac)
      | None ->
	match ac with
	  | [] -> []
	  | (i,j)::tail -> (i,n-1)::tail
  in

  match outer_loop 0 [] with
    | [] -> printf "-1\n"
    | li ->
      printf "%d\n" (List.length li);
      List.iter (fun (i,j) -> printf "%d %d\n" (i+1) (j+1)) li

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

let () =
  let rec find a l r x =
    let m = (l + r) / 2 in
    if a.(m) = x then m
    else (
      if a.(m) < x then (find a (m + 1) r x)
      else (find a l (m - 1) x)
    )
  in

  let min x y =
    if x < y then x
    else y
  in

  let n = xint() in
  let a = Array.make n 0 in
  let xs = Array.make n 0 and m = ref 0 in

  for i = 0 to n - 1 do
    a.(i) <- xint();
    xs.(i) <- a.(i);
  done;
  Array.sort (fun x y -> x - y) xs;
  m := 1;
  for i = 1 to n - 1 do
    if xs.(i) != xs.(i - 1) then (
      xs.(!m) <- xs.(i);
      m := !m + 1;
    )
  done;

  let nx = Array.make n n and pos = Array.make !m n in

  for i = n - 1 downto 0 do
    a.(i) <- find xs 0 (!m - 1) a.(i);
    nx.(i) <- pos.(a.(i));
    pos.(a.(i)) <- i;
  done;

  let l = Array.make n 0 and r = Array.make n 0 in
  let ret = ref 0 and i = ref 0 in
  while !i < n do
    let x = !i and y = ref nx.(!i) in
    while !i < !y do
      y := min !y nx.(!i);
      i := !i + 1;
    done;
    if !y != n then (
      l.(!ret) <- x + 1;
      r.(!ret) <- !y + 1;
      ret := !ret + 1;
    );
    i := !i + 1;
  done;

  if !ret = 0 then (
    Printf.printf "-1\n";
  ) else (
    Printf.printf "%d\n" !ret;
    for i = 0 to !ret - 1 do
      Printf.printf "%d %d\n" l.(i) r.(i);
    done;
  )


module type Idx = sig
  type t
  val to_string: t -> string
  val of_int: int -> t
  val (+): t -> t -> t
  val (-): t -> t -> t
  val (/): t -> t -> t
end

module IdxI64 = struct
  type t = int64
  let to_string = Int64.to_string
  let of_int = Int64.of_int
  let compare = Int64.compare
  let (+) = Int64.add
  let (/) = Int64.div
  let (-) = Int64.sub
  let ( * ) = Int64.mul
  let rem = Int64.rem
end

(* find the first one that makes callback returns true *)
module Bisearch_first (Idx: Idx) = struct
  let perform
      (callback: 'a -> bool)
      ((l, r): Idx.t * Idx.t) (* range is closed *)
      (get: Idx.t -> 'a): Idx.t option =
    let open Idx in
    let rec f (l, r) =
      if l = r
      then if l |> get |> callback then Some l else None
      else
        let m = (l + r) / (Idx.of_int 2) in
        if m |> get |> callback
        then f (l, m)
        else f (m + (Idx.of_int 1), r)
    in
    f (l, r)
end

let option_get (src: 'a option): 'a =
  match src with
  | Some a -> a
  | None -> raise Not_found

let log2 (v: float): float = log v /. log 2.

module Bisearch_first_i64 = Bisearch_first(IdxI64)

let max_capacity (h: int64) (i: int64): int64 =
  let open IdxI64 in
  if h >= i
  then
    if i |> Int64.to_float |> log2 >= 31.
    then Int64.max_int
    else (i * (i + 1L)) / 2L
  else
    let sum = h + i in
    let m = sum / 2L in
    if m |> Int64.to_float |> log2 >= 31.
    then Int64.max_int
    else
      (((m + h - 1L) * (m - h)) / 2L) +
      (((m + 1L) * m) / 2L) +
      (if rem sum 2L = 1L then m else 0L)

module Bigint = struct
  type t = Big_int.big_int
  let of_int = Big_int.big_int_of_int
  let to_int = Big_int.int_of_big_int
  let of_int64 = Big_int.big_int_of_int64
  let to_int64 = Big_int.int64_of_big_int
  let (+) = Big_int.add_big_int
  let (/) = Big_int.div_big_int
  let (-) = Big_int.sub_big_int
  let ( * ) = Big_int.mult_big_int
  let rem = Big_int.mod_big_int
  let compare = Big_int.compare_big_int
  let equal = Big_int.eq_big_int
  let min = Big_int.min_big_int
end

let max_capacity_big (h: int64) (i: int64): int64 =
  let open Bigint in
  let h = of_int64 h in
  let i = of_int64 i in
  let one = of_int 1 in
  let two = of_int 2 in
  let ret =
    if compare h i >= 0
    then (i * (i + one)) / two
    else
      let sum = h + i in
      let m = sum / two in
      (((m + h - one) * (m - h)) / two) +
      (((m + one) * m) / two) +
      (if equal (rem sum two) one then m else (of_int 0)) in
  min ret (of_int64 Int64.max_int) |> to_int64

let max_capacity_big h i =
  let ret = max_capacity_big h i in
  (* Printf.printf "mc %Ld %Ld -> %Ld\n" h i ret; *)
  ret

let compute (n: int64) (h: int64): int64 =
  let f i = (max_capacity_big h i) >= n in
  (* let f i = let ret = f i in Printf.printf "f %Ld %Ld %b\n" h i ret; ret in *)
  Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get

(* 1000000000000000000 1000000000000000000 -> 1414213562 *)
(* 1000000000000000000 1 -> 1999999999 *)
(* 1036191544337895 1 -> 64379858 *)

let _ =
  (* max_capacity 1000000000000000000L 62500000000000000L |> IdxI64.to_string |> print_endline;
   * max_capacity 1000000000000000000L 1414213562L |> IdxI64.to_string |> print_endline; *)
  Printexc.record_backtrace true;
  let (n, h) = Scanf.scanf " %Ld %Ld" (fun a b -> (a, b)) in
  compute n h |> IdxI64.to_string |> print_endline

module type Idx = sig
  type t
  val to_string: t -> string
  val of_int: int -> t
  val (+): t -> t -> t
  val (-): t -> t -> t
  val (/): t -> t -> t
end

module IdxI64 = struct
  type t = int64
  let to_string = Int64.to_string
  let of_int = Int64.of_int
  let compare = Int64.compare
  let (+) = Int64.add
  let (/) = Int64.div
  let (-) = Int64.sub
  let ( * ) = Int64.mul
  let rem = Int64.rem
end

(* find the first one that makes callback returns true *)
module Bisearch_first (Idx: Idx) = struct
  let perform
      (callback: 'a -> bool)
      ((l, r): Idx.t * Idx.t) (* range is closed *)
      (get: Idx.t -> 'a): Idx.t option =
    let open Idx in
    let rec f (l, r) =
      if l = r
      then if l |> get |> callback then Some l else None
      else
        let m = (l + r) / (Idx.of_int 2) in
        if m |> get |> callback
        then f (l, m)
        else f (m + (Idx.of_int 1), r)
    in
    f (l, r)
end

let option_get (src: 'a option): 'a =
  match src with
  | Some a -> a
  | None -> raise Not_found

let log2 (v: float): float = log v /. log 2.

module Bisearch_first_i64 = Bisearch_first(IdxI64)

let max_capacity (h: int64) (i: int64): int64 =
  let open IdxI64 in
  if h >= i
  then
    if i |> Int64.to_float |> log2 >= 31.
    then Int64.max_int
    else (i * (i + 1L)) / 2L
  else
    let sum = h + i in
    let m = sum / 2L in
    if m |> Int64.to_float |> log2 >= 31.
    then Int64.max_int
    else
      (((m + h - 1L) * (m - h)) / 2L) +
      (((m + 1L) * m) / 2L) +
      (if rem sum 2L = 1L then m else 0L)

(* module Bigint = struct
 *   type t = Big_int.big_int
 *   let of_int = Big_int.big_int_of_int
 *   let to_int = Big_int.int_of_big_int
 *   let of_int64 = Big_int.big_int_of_int64
 *   let to_int64 = Big_int.int64_of_big_int
 *   let (+) = Big_int.add_big_int
 *   let (/) = Big_int.div_big_int
 *   let (-) = Big_int.sub_big_int
 *   let ( * ) = Big_int.mult_big_int
 *   let rem = Big_int.mod_big_int
 *   let compare = Big_int.compare_big_int
 *   let equal = Big_int.eq_big_int
 *   let min = Big_int.min_big_int
 * end
 *
 * let max_capacity_big (h: int64) (i: int64): int64 =
 *   let open Bigint in
 *   let h = of_int64 h in
 *   let i = of_int64 i in
 *   let one = of_int 1 in
 *   let two = of_int 2 in
 *   let ret =
 *     if compare h i >= 0
 *     then (i * (i + one)) / two
 *     else
 *       let sum = h + i in
 *       let m = sum / two in
 *       (((m + h - one) * (m - h)) / two) +
 *       (((m + one) * m) / two) +
 *       (if equal (rem sum two) one then m else (of_int 0)) in
 *   min ret (of_int64 Int64.max_int) |> to_int64 *)

(* 1000000000000000000 1000000000000000000 -> 1414213562 *)
(* 1000000000000000000 1 -> 1999999999 *)
(* 1036191544337895 1 -> 64379858 *)

let compute (n: int64) (h: int64): int64 =
  let f i = (max_capacity h i) >= n in
  Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get

let _ =
  let (n, h) = Scanf.scanf " %Ld %Ld" (fun a b -> (a, b)) in
  compute n h |> IdxI64.to_string |> print_endline

module type Idx = sig
  type t
  val to_string: t -> string
  val of_int: int -> t
  val (+): t -> t -> t
  val (-): t -> t -> t
  val (/): t -> t -> t
end

module IdxI64 = struct
  type t = int64
  let to_string = Int64.to_string
  let of_int = Int64.of_int
  let compare = Int64.compare
  let (+) = Int64.add
  let (/) = Int64.div
  let (-) = Int64.sub
  let ( * ) = Int64.mul
  let rem = Int64.rem
end

(* find the first one that makes callback returns true *)
module Bisearch_first (Idx: Idx) = struct
  let perform
      (callback: 'a -> bool)
      ((l, r): Idx.t * Idx.t) (* range is closed *)
      (get: Idx.t -> 'a): Idx.t option =
    let open Idx in
    let rec f (l, r) =
      if l = r
      then if l |> get |> callback then Some l else None
      else
        let m = (l + r) / (Idx.of_int 2) in
        if m |> get |> callback
        then f (l, m)
        else f (m + (Idx.of_int 1), r)
    in
    f (l, r)
end

let option_get (src: 'a option): 'a =
  match src with
  | Some a -> a
  | None -> raise Not_found

module Bisearch_first_i64 = Bisearch_first(IdxI64)

let max_capacity (h: int64) (i: int64): int64 =
  let open IdxI64 in
  if h >= i
  then (i * (i + 1L)) / 2L
  else
    let sum = h + i in
    let m = sum / 2L in
    (((m + h) * (m - h)) / 2L) +
    (((m + 1L) * m) / 2L) +
    (if rem sum 2L = 1L then m else 0L)

let compute (n: int64) (h: int64): int64 =
  let f i = (max_capacity h i) >= n in
  Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get

let _ =
  let (n, h) = Scanf.scanf " %Ld %Ld" (fun a b -> (a, b)) in
  compute n h |> IdxI64.to_string |> print_endline

module type Idx = sig
  type t
  val to_string: t -> string
  val of_int: int -> t
  val (+): t -> t -> t
  val (-): t -> t -> t
  val (/): t -> t -> t
end

module IdxI64 = struct
  type t = int64
  let to_string = Int64.to_string
  let of_int = Int64.of_int
  let compare = Int64.compare
  let (+) = Int64.add
  let (/) = Int64.div
  let (-) = Int64.sub
  let ( * ) = Int64.mul
  let rem = Int64.rem
end

(* find the first one that makes callback returns true *)
module Bisearch_first (Idx: Idx) = struct
  let perform
      (callback: 'a -> bool)
      ((l, r): Idx.t * Idx.t) (* range is closed *)
      (get: Idx.t -> 'a): Idx.t option =
    let open Idx in
    let rec f (l, r) =
      if l = r
      then if l |> get |> callback then Some l else None
      else
        let m = (l + r) / (Idx.of_int 2) in
        if m |> get |> callback
        then f (l, m)
        else f (m + (Idx.of_int 1), r)
    in
    f (l, r)
end

let option_get (src: 'a option): 'a =
  match src with
  | Some a -> a
  | None -> raise Not_found

let log2 (v: float): float = log v /. log 2.

module Bisearch_first_i64 = Bisearch_first(IdxI64)

let max_capacity (h: int64) (i: int64): int64 =
  let open IdxI64 in
  if h >= i
  then
    if i |> Int64.to_float |> log2 >= 31.
    then Int64.max_int
    else (i * (i + 1L)) / 2L
  else
    let sum = h + i in
    let m = sum / 2L in
    (((m + h) * (m - h)) / 2L) +
    (((m + 1L) * m) / 2L) +
    (if rem sum 2L = 1L then m else 0L)

let compute (n: int64) (h: int64): int64 =
  let f i = (max_capacity h i) >= n in
  (* let f i = let ret = f i in Printf.printf "f %Ld %b\n" i ret; ret in *)
  Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get

(* 1000000000000000000 1000000000000000000 -> 1414213562 *)

let _ =
  max_capacity 1000000000000000000L 62500000000000000L |> IdxI64.to_string |> print_endline;
  max_capacity 1000000000000000000L 1414213562L |> IdxI64.to_string |> print_endline;
  let (n, h) = Scanf.scanf " %Ld %Ld" (fun a b -> (a, b)) in
  compute n h |> IdxI64.to_string |> print_endline

module type Idx = sig
  type t
  val to_string: t -> string
  val of_int: int -> t
  val (+): t -> t -> t
  val (-): t -> t -> t
  val (/): t -> t -> t
end

module IdxI64 = struct
  type t = int64
  let to_string = Int64.to_string
  let of_int = Int64.of_int
  let compare = Int64.compare
  let (+) = Int64.add
  let (/) = Int64.div
  let (-) = Int64.sub
  let ( * ) = Int64.mul
  let rem = Int64.rem
end

(* find the first one that makes callback returns true *)
module Bisearch_first (Idx: Idx) = struct
  let perform
      (callback: 'a -> bool)
      ((l, r): Idx.t * Idx.t) (* range is closed *)
      (get: Idx.t -> 'a): Idx.t option =
    let open Idx in
    let rec f (l, r) =
      if l = r
      then if l |> get |> callback then Some l else None
      else
        let m = (l + r) / (Idx.of_int 2) in
        if m |> get |> callback
        then f (l, m)
        else f (m + (Idx.of_int 1), r)
    in
    f (l, r)
end

let option_get (src: 'a option): 'a =
  match src with
  | Some a -> a
  | None -> raise Not_found

let log2 (v: float): float = log v /. log 2.

module Bisearch_first_i64 = Bisearch_first(IdxI64)

let max_capacity (h: int64) (i: int64): int64 =
  let open IdxI64 in
  if h >= i
  then
    if i |> Int64.to_float |> log2 >= 31.
    then Int64.max_int
    else (i * (i + 1L)) / 2L
  else
    let sum = h + i in
    let m = sum / 2L in
    if m |> Int64.to_float |> log2 >= 31.
    then Int64.max_int
    else
      (((m + h) * (m - h)) / 2L) +
      (((m + 1L) * m) / 2L) +
      (if rem sum 2L = 1L then m else 0L)

let compute (n: int64) (h: int64): int64 =
  let f i = (max_capacity h i) >= n in
  (* let f i = let ret = f i in Printf.printf "f %Ld %b\n" i ret; ret in *)
  Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get

(* 1000000000000000000 1000000000000000000 -> 1414213562 *)
(* 1000000000000000000 1 -> 1999999999 *)

let _ =
  (* max_capacity 1000000000000000000L 62500000000000000L |> IdxI64.to_string |> print_endline;
   * max_capacity 1000000000000000000L 1414213562L |> IdxI64.to_string |> print_endline; *)
  let (n, h) = Scanf.scanf " %Ld %Ld" (fun a b -> (a, b)) in
  compute n h |> IdxI64.to_string |> print_endline

module type Idx = sig
  type t
  val to_string: t -> string
  val of_int: int -> t
  val (+): t -> t -> t
  val (-): t -> t -> t
  val (/): t -> t -> t
end

module IdxI64 = struct
  type t = int64
  let to_string = Int64.to_string
  let of_int = Int64.of_int
  let compare = Int64.compare
  let (+) = Int64.add
  let (/) = Int64.div
  let (-) = Int64.sub
  let ( * ) = Int64.mul
  let rem = Int64.rem
end

(* find the first one that makes callback returns true *)
module Bisearch_first (Idx: Idx) = struct
  let perform
      (callback: 'a -> bool)
      ((l, r): Idx.t * Idx.t) (* range is closed *)
      (get: Idx.t -> 'a): Idx.t option =
    let open Idx in
    let rec f (l, r) =
      if l = r
      then if l |> get |> callback then Some l else None
      else
        let m = (l + r) / (Idx.of_int 2) in
        if m |> get |> callback
        then f (l, m)
        else f (m + (Idx.of_int 1), r)
    in
    f (l, r)
end

let option_get (src: 'a option): 'a =
  match src with
  | Some a -> a
  | None -> raise Not_found

let log2 (v: float): float = log v /. log 2.

module Bisearch_first_i64 = Bisearch_first(IdxI64)

let max_capacity (h: int64) (i: int64): int64 =
  let open IdxI64 in
  if h >= i
  then
    if i |> Int64.to_float |> log2 >= 31.
    then Int64.max_int
    else (i * (i + 1L)) / 2L
  else
    let sum = h + i in
    let m = sum / 2L in
    (((m + h) * (m - h)) / 2L) +
    (((m + 1L) * m) / 2L) +
    (if rem sum 2L = 1L then m else 0L)

let compute (n: int64) (h: int64): int64 =
  let f i = (max_capacity h i) >= n in
  (* let f i = let ret = f i in Printf.printf "f %Ld %b\n" i ret; ret in *)
  Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get

(* 1000000000000000000 1000000000000000000 -> 1414213562 *)

let _ =
  (* max_capacity 1000000000000000000L 62500000000000000L |> IdxI64.to_string |> print_endline;
   * max_capacity 1000000000000000000L 1414213562L |> IdxI64.to_string |> print_endline; *)
  let (n, h) = Scanf.scanf " %Ld %Ld" (fun a b -> (a, b)) in
  compute n h |> IdxI64.to_string |> print_endline

module type Idx = sig
  type t
  val to_string: t -> string
  val of_int: int -> t
  val (+): t -> t -> t
  val (-): t -> t -> t
  val (/): t -> t -> t
end

module IdxI64 = struct
  type t = int64
  let to_string = Int64.to_string
  let of_int = Int64.of_int
  let compare = Int64.compare
  let (+) = Int64.add
  let (/) = Int64.div
  let (-) = Int64.sub
  let ( * ) = Int64.mul
  let rem = Int64.rem
end

(* find the first one that makes callback returns true *)
module Bisearch_first (Idx: Idx) = struct
  let perform
      (callback: 'a -> bool)
      ((l, r): Idx.t * Idx.t) (* range is closed *)
      (get: Idx.t -> 'a): Idx.t option =
    let open Idx in
    let rec f (l, r) =
      if l = r
      then if l |> get |> callback then Some l else None
      else
        let m = (l + r) / (Idx.of_int 2) in
        if m |> get |> callback
        then f (l, m)
        else f (m + (Idx.of_int 1), r)
    in
    f (l, r)
end

let option_get (src: 'a option): 'a =
  match src with
  | Some a -> a
  | None -> raise Not_found

let log2 (v: float): float = log v /. log 2.

module Bisearch_first_i64 = Bisearch_first(IdxI64)

let max_capacity (h: int64) (i: int64): int64 =
  let open IdxI64 in
  if h >= i
  then
    if i |> Int64.to_float |> log2 >= 31.
    then Int64.max_int
    else (i * (i + 1L)) / 2L
  else
    let sum = h + i in
    let m = sum / 2L in
    if m |> Int64.to_float |> log2 >= 31.
    then Int64.max_int
    else
      (((m + h - 1L) * (m - h)) / 2L) +
      (((m + 1L) * m) / 2L) +
      (if rem sum 2L = 1L then m else 0L)

module Bigint = struct
  type t = Big_int.big_int
  let of_int = Big_int.big_int_of_int
  let to_int = Big_int.int_of_big_int
  let of_int64 = Big_int.big_int_of_int64
  let to_int64 = Big_int.int64_of_big_int
  let (+) = Big_int.add_big_int
  let (/) = Big_int.div_big_int
  let (-) = Big_int.sub_big_int
  let ( * ) = Big_int.mult_big_int
  let rem = Big_int.mod_big_int
  let compare = Big_int.compare_big_int
  let equal = Big_int.eq_big_int
  let min = Big_int.min_big_int
end

let max_capacity_big (h: int64) (i: int64): int64 =
  let open Bigint in
  let h = of_int64 h in
  let i = of_int64 i in
  let one = of_int 1 in
  let two = of_int 2 in
  let ret =
    if compare h i >= 0
    then (i * (i + one)) / two
    else
      let sum = h + i in
      let m = sum / two in
      (((m + h - one) * (m - h)) / two) +
      (((m + one) * m) / two) +
      (if equal (rem sum two) one then m else (of_int 0)) in
  min ret (of_int64 Int64.max_int) |> to_int64

let max_capacity_big h i =
  let ret = max_capacity_big h i in
  Printf.printf "mc %Ld %Ld -> %Ld\n" h i ret;
  ret

let compute (n: int64) (h: int64): int64 =
  let f i = (max_capacity_big h i) >= n in
  let f i = let ret = f i in Printf.printf "f %Ld %Ld %b\n" h i ret; ret in
  Bisearch_first_i64.perform f (1L, n) (fun i -> i) |> option_get

(* 1000000000000000000 1000000000000000000 -> 1414213562 *)
(* 1000000000000000000 1 -> 1999999999 *)
(* 1036191544337895 1 -> 64379858 *)

let _ =
  (* max_capacity 1000000000000000000L 62500000000000000L |> IdxI64.to_string |> print_endline;
   * max_capacity 1000000000000000000L 1414213562L |> IdxI64.to_string |> print_endline; *)
  Printexc.record_backtrace true;
  let (n, h) = Scanf.scanf " %Ld %Ld" (fun a b -> (a, b)) in
  compute n h |> IdxI64.to_string |> print_endline


let get a'= List.map (int_of_string) (Str.split (Str.regexp " ") (read_line ()));;
let [n; m] = get ();;
let kk = Array.make n 0 and mm = ref 0 and mj = ref 0;;
for i = 1 to m do
	let ins = get () in begin
		mm := (-1);
		for j = 0 to n - 1 do if !mm < List.nth ins j then begin
			mm := List.nth ins j;
			mj := j;
		end	done;
		Array.set kk !mj (kk.(!mj) + 1);
end done;;
mm := 0;;
for j = 0 to n - 1 do if !mm < kk.(j) then begin
	mm := kk.(j);
	mj := j;
end done;;
print_int (!mj + 1);;

let winner a =
  fst (Array.fold_left (fun (i, pos) b -> if b > a.(i) then (pos, pos + 1) else (i, pos + 1)) (0, 0) a)

let () = Scanf.scanf "%d %d\n" (fun n m ->
				(* candidates *)
				let c = Array.make n 0 in
				for i = 1 to m do
				  let e = Array.init n (fun _ -> Scanf.scanf "%d%_c" (fun x -> x)) in
				  let w = winner e in
				  c.(w) <- c.(w) + 1
				done;
				Printf.printf "%d\n" (winner c + 1))

let get a'= List.map (int_of_string) (Str.split (Str.regexp " ") (read_line ()));;
let [n; m] = get ();;
let kk = Array.make n 0 and mm = ref 0 and mj = ref 0;;
for i = 1 to m do
	let ins = get () in begin
		mm := 0;
		for j = 0 to n - 1 do if !mm < List.nth ins j then begin
			mm := List.nth ins j;
			mj := j;
		end	done;
		Array.set kk !mj (kk.(!mj) + 1);
end done;;
mm := 0;;
for j = 0 to n - 1 do if !mm < kk.(j) then begin
	mm := kk.(j);
	mj := j;
end done;;
print_int (!mj + 1);;

let get a'= List.map (int_of_string) (Str.split (Str.regexp " ") (read_line ()));;
let [n; m] = get ();;
let kk = Array.make n 0 and mm = ref 0 and mj = ref 0;;
for i = 1 to m do
	let ins = get () in begin
		mm := (-1);
		for j = 0 to n - 1 do if !mm < List.nth ins j then begin
			mm := List.nth ins j;
			mj := j;
		end	done;
end done;;
mm := 0;;
for j = 0 to n - 1 do if !mm < kk.(j) then begin
	mm := kk.(j);
	mj := j;
end done;;
print_int (!mj + 1);;


let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let a = Array.make 26 0 in
  let res = ref 0 in
    for i = 0 to n - 2 do
      let k = Char.code s.[2 * i] - Char.code 'a' in
	a.(k) <- a.(k) + 1;
	let k = Char.code s.[2 * i + 1] - Char.code 'A' in
	  if a.(k) > 0
	  then a.(k) <- a.(k) - 1
	  else incr res
    done;
    Printf.printf "%d\n" !res;

open Scanf;;
open Printf;;

let rec change list target cur value = (* listのtarget番目をvalueに変えたlistを返す *)
    if cur = target then value::( List.tl list )
    else ( List.hd list )::( change (List.tl list ) target ( cur + 1 ) value );;

let rec init size =
    if size <= 0 then []
    else 0::( init ( size - 1 ) ) ;;

let n = scanf "%d\n" ( fun n -> n );;

let rec solve s i list =
  if i >= ( String.length s ) then 0
  else begin
    if ( 'a' <= s.[i] && s.[i] <= 'z' ) then begin
      solve s ( i + 1 ) ( change list ( ( Char.code s.[i] ) - ( Char.code 'a' ) ) 0 ( 1 + ( List.nth list ( ( Char.code s.[i] ) - ( Char.code 'a' ) ) ) ) )
    end else begin
      if ( List.nth list ( ( Char.code s.[i] ) - ( Char.code 'A' ) ) ) = 0 then begin
        1 + solve s ( i + 1 ) list
      end else begin
        solve s ( i + 1 ) ( change list ( ( Char.code s.[i] ) - ( Char.code 'A' ) ) 0 ( ( List.nth list ( ( Char.code s.[i] ) - ( Char.code 'A' ) ) ) - 1 ) )
      end
    end
  end
;;

let s = scanf "%s\n" ( fun s -> s ) in
  printf "%d\n" ( solve s 0 ( init 26 ) );;


let _ =
	Scanf.scanf "%d" @@ fun n ->
		let l = (Array.init n (fun _ -> Scanf.scanf " %d" (fun i -> i)))
			|> Array.to_list
		in
		let mini = List.fold_left min max_int l in
		let maxi = List.fold_left max min_int l in
		let l' = List.filter ((<>) mini) l in
		let l'' = List.filter ((<>) maxi) l' in
			print_int (List.length l'')

let () =
  let n = read_int () in
  let a = Array.init n (fun _ -> Scanf.scanf "%d%_c" (fun x -> x)) in
  (* sort ascending *)
  Array.sort compare a;
  let a = List.filter (fun x -> x <> a.(0) && x <> a.(n - 1)) (Array.to_list a) in
  print_int (List.length a);
  print_newline ()


let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let () =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s);
    done;
  in
  let b = Array.copy a in
  let cmp (x : int) y =
    if x < y
    then -1
    else if x = y
    then 0
    else 1
  in
    Array.sort cmp b;
    let c = ref 0 in
      for i = 0 to n - 1 do
	if a.(i) <> b.(i)
	then incr c;
      done;
      if !c >= 3
      then Printf.printf "NO\n"
      else Printf.printf "YES\n"

let swap ary i j =
  let temp = ary.(i) in
  ary.(i) <- ary.(j);
  ary.(j) <- temp

let input_array size ary =
  let rec input_array n =
    if n == size then ary
    else begin
      ary.(n) <- Scanf.scanf " %d" (fun x -> x);
      input_array (n + 1);
    end
  in
  input_array 0

let solve n =
  let a = input_array n (Array.make n 0) in
  let a_ = Array.copy a in
  let sorted_a =
    begin
      Array.stable_sort (fun a b -> if a <= b then -1 else 1) a;
      a;
    end
  in
  let rec solve x cnt =
    if cnt >= 3 then "NO"
    else if n == x then "YES"
    else if a_.(x) != sorted_a.(x) then solve (x + 1) (cnt + 1)
    else solve (x + 1) cnt
  in
  solve 0 0

let _ =
  Printf.printf "%s\n" (Scanf.scanf " %d" solve)

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int();;
let tab=Array.make n 0;;
for i=0 to n-1 do
   tab.(i)<-read_int()
done;;
let creas()=let b=ref true in
for i=0 to n-2 do
   if tab.(i)>tab.(i+1) then b:=false
done;
!b;;
let r=creas();;
let rec mins i v=if i=0 then 0 else if tab.(i-1)=v then mins (i-1) v else i;;
let rec maxs i v=if i=n-1 then n-1 else if tab.(i+1)=v then maxs (i+1) v else i;;
let rec prem i=
if i=n-1 then 0 else if tab.(i)>tab.(i+1) then mins i tab.(i) else prem (i+1);;
let rec last i=
if i=0 then 0 else if tab.(i)<tab.(i-1) then maxs i tab.(i) else last (i-1);;
let i=prem 0 and j=last (n-1);;
let aux=tab.(i);;
tab.(i)<-tab.(j);;
tab.(j)<-aux;;
let g=creas();;
if r||g then print_string "YES" else print_string "NO";;
(*10 1 2 9 4 5 6 7 8 3 10*)

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int();;
let tab=Array.make n 0;;
for i=0 to n-1 do
   tab.(i)<-read_int()
done;;
let creas()=let b=ref true in
for i=0 to n-2 do
   if tab.(i)>tab.(i+1) then b:=false
done;
!b;;
let r=creas();;
let rec mins i v=if i=0 then 0 else if tab.(i-1)=v then mins (i-1) v else i;;
let rec maxs i v=if i=n-1 then n-1 else if tab.(i+1)=v then mins (i+1) v else i;;
let rec prem i=
if i=n-1 then 0 else if tab.(i)>tab.(i+1) then mins i tab.(i) else prem (i+1);;
let rec last i=
if i=0 then 0 else if tab.(i)<tab.(i-1) then maxs i tab.(i) else last (i-1);;
let i=prem 0 and j=last (n-1);;
let aux=tab.(i);;
tab.(i)<-tab.(j);;
tab.(j)<-aux;;
let g=creas();;
if r||g then print_string "YES" else print_string "NO";;
(*10 1 2 9 4 5 6 7 8 3 10*)

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int();;
let tab=Array.make n 0;;
for i=0 to n-1 do
   tab.(i)<-read_int()
done;;
let creas()=let b=ref true in
for i=0 to n-2 do
   if tab.(i)>tab.(i+1) then b:=false
done;
!b;;
let r=creas();;
let rec prem i=
if i=n-1 then 0 else if tab.(i)>tab.(i+1) then i else prem (i+1);;
let rec last i=
if i=0 then 0 else if tab.(i)<tab.(i-1) then i else last (i-1);;
let i=prem 0 and j=last (n-1);;
let aux=tab.(i);;
tab.(i)<-tab.(j);;
tab.(j)<-aux;;
let g=creas();;
if r||g then print_string "YES" else print_string "NO";;
(*10 1 2 9 4 5 6 7 8 3 10*)

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int();;
let tab=Array.make n 0;;
for i=0 to n-1 do
   tab.(i)<-read_int()
done;;
let creas()=let b=ref true in
for i=0 to n-2 do
   if tab.(i)>tab.(i+1) then b:=false
done;
!b;;
let r=creas();;
let rec prem i=
if i=n-1 then 0 else if tab.(i)>tab.(i+1) then i else prem (i+1);;
let rec last i=
if i=0 then 0 else if tab.(i)<tab.(i-1) then i else prem (i-1);;
let i=prem 0 and j=last (n-1);;
let aux=tab.(i);;
tab.(i)<-tab.(j);;
tab.(j)<-aux;;
let g=creas();;
if r||g then print_string "YES" else print_string "NO";;

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int();;
let tab=Array.make n 0;;
for i=0 to n-1 do
   tab.(i)<-read_int()
done;;
let creas()=let b=ref true in
for i=0 to n-2 do
   if tab.(i)>tab.(i+1) then b:=false
done;
!b;;
let r=creas();;
let rec prem i=
if i=n-1 then 0 else if tab.(i)>tab.(i+1) then i else prem (i+1);;
let rec last i=
if i=0 then 0 else if tab.(i)<tab.(i-1) then i else prem (i-1);;
let i=prem 0 and j=last (n-1);;
let aux=tab.(i);;
tab.(i)<-tab.(j);;
tab.(j)<-tab.(i);;
let g=creas();;
if r||g then print_string "YES" else print_string "NO";;


open Printf
open Scanf

let read_pair _ = bscanf Scanning.stdib " %d %d " (fun x y -> (x,y))
let () =
  let (n,m) = read_pair () in
  let tele = Array.init n read_pair in

  let rec loop i reach =
    if reach >= m then true
    else if i = n then false
    else
      let (a,b) = tele.(i) in
      if a > reach then false
      else loop (i+1) (max reach b)
  in

  if loop 0 0 then printf "YES\n" else printf "NO\n"

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

let n = read_int ();;
let m = read_int ();;
let i = (ref 0);;
let tab = (ref [(0,0)]);;
while ((!i) < (n)) do
  let a = read_int ()
  in
  let b = read_int ()
  in
  tab := [(a, b)]@(!tab);
  i := (!i + 1)
done
let tab = (rev (!tab));;
if ((fst (List.hd tab)) <> 0) then
  begin
  print_string "NO";
  print_endline
  end
else
  begin
    let f a (x, y) =
      if (a>=x) then (max a y)
      else a
    in
    let zas =
      List.fold_left f 0 tab
    in
    if zas>=m then
      begin
      print_string "YES";
      print_endline
      end
    else
    begin
      print_string "NO";
      print_endline
    end
  end
;;

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

let n = read_int ();;
let m = read_int ();;
let i = (ref 0);;
let tab = (ref [(0,0)]);;
while ((!i) < (n)) do
  let a = read_int ()
  in
  let b = read_int ()
  in
  tab := [(a, b)]@(!tab);
  i := (!i + 1)
done
let tab = (rev (!tab));;
if ((fst (List.hd tab)) <> 0) then
  begin
  print_string "NO";
  print_endline
  end
else
  begin
    let f a (x, y) =
      if (a>=x) then (max a (x+y))
      else a
    in
    let zas =
      List.fold_left f 0 tab
    in
    if zas>=m then
      begin
      print_string "YES";
      print_endline
      end
    else
    begin
      print_string "NO";
      print_endline
    end
  end
;;


let int_of_char c = int_of_char c - int_of_char '0'
and char_of_int i = char_of_int (i + int_of_char '0')

let () =
  let n = read_line () in
  let last = int_of_char (n.[String.length n - 1]) in
  let best = ref (-1) in
  let even = ref (-1) in

  for i = 0 to String.length n - 1 do
    let c = int_of_char n.[i] in
    if c mod 2 = 0 then begin
      even := i;
      if !best = (-1) && c < last then
        best := i
    end
  done;

  if !best <> (-1) then even := !best;
  if !even <> (-1)
  then begin
    n.[String.length n - 1] <- n.[!even];
    n.[!even] <- char_of_int last;
    print_endline n
  end
  else
    print_endline "-1"

let f mot =
	let flag = ref true and last = mot.[String.length mot - 1] in
	for i=0 to String.length mot - 1 do
		if !flag && (int_of_char (mot.[i]) mod 2 = 0) && (mot.[i] < last)
			then (flag := false; let z = mot.[i] in mot.[i] <- last; mot.[String.length mot - 1] <- z);
	done;
	if !flag
		then for i=String.length mot - 1 downto 0 do
		if !flag && (int_of_char (mot.[i]) mod 2 = 0)
			then (flag := false; let z = mot.[i] in mot.[i] <- last; mot.[String.length mot - 1] <- z);
		done;
	!flag;;

let test n =
	let mot = string_of_int n in
		if f mot
			then -1
			else int_of_string mot;;

let final () =
	let m = Scanf.scanf "%s " (fun i -> i) in
		if f m
			then Printf.printf "-1"
			else Printf.printf "%s " m;;

final ();;

let f mot =
	let flag = ref true and last = mot.[String.length mot - 1] in
	for i=0 to String.length mot - 1 do
		if !flag && (int_of_char (mot.[i]) mod 2 = 0) && (mot.[i] > last)
			then (flag := false; let z = mot.[i] in mot.[i] <- last; mot.[String.length mot - 1] <- z);
	done;
	if !flag
		then for i=String.length mot - 1 downto 0 do
		if !flag && (int_of_char (mot.[i]) mod 2 = 0)
			then (flag := false; let z = mot.[i] in mot.[i] <- last; mot.[String.length mot - 1] <- z);
		done;
	!flag;;

let final () =
	let m = Scanf.scanf "%s " (fun i -> i) in
		if f m
			then Printf.printf "-1"
			else Printf.printf "%s " m;;

final ();;


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

let n=read_int() and k=read_int();;

let l=ref [];;
for i=1 to n do
   l:=(read_int())::(!l)
done;;

let rec inserer v=function
|[]->[v]
|h::t->if v>=h then v::h::t else h::(inserer v t);;

let rec tri=function
|[]->[]
|h::t->inserer h (tri t);;

let sol=tri(!l);;

let rec neme i=function
|[]->0
|h::t->if i=1 then h else neme (i-1) t;;

print_int(neme k sol);;

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    Array.sort compare a
  in
    Printf.printf "%d\n" a.(n - k);

open Scanf
open Printf

let flip f a b = f b a in

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

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

let read_list n =
    let f l _ = ((read_int ()) :: l) in
    List.fold_left f [] (range 1 n) in

let n = read_int () in
let k = read_int () in
let l = read_list n in

let (|>) a f = f a in

l |> (List.sort compare) |> List.rev |> (flip List.nth (k - 1)) |> (printf "%d\n");;


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

let n=read_int();;

let l=ref 0;;

let s=ref " ";;

let a=ref 0;;

for i=0 to n-1 do
   for j=0 to i do
      a:=read_int()
   done;
   for j=i+1 to n-1 do
      let b=read_int() in ()
   done;
   l:= !l+ !a;
done;;

let m=read_int();;

l:= (!l mod 2);;

let p=ref [];;

for i=1 to m do
   let q=read_int() in if q<>3 then let a=read_int() in  l:=1- !l else p:=(!l):: !p
done;;

let rec print_list=function
|[]->()
|h::t->print_list t;print_int h;;

print_list !p;;

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

let n=read_int();;

let l=ref 0;;

for i=0 to n-1 do
   for j=0 to n-1 do
      let a=read_int() in if i=j then l:= !l+a
   done
done;;

let m=read_int();;

l:= ( !l mod 2);;

let p=ref [];;

for i=1 to m do
   let q=read_int() in if q<>3 then let a=read_int() in  l:=1- !l else p:=(!l):: !p
done;;

let rec print_list=function
|[]->()
|h::t->print_list t;print_int h;;

print_list !p;;

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

let n=read_int();;

let l=ref 0;;

let a=ref 0;;

for i=0 to n-1 do
   for j=0 to i do
      a:=read_int()
   done;
   for j=i+1 to n-1 do
      let b=read_int() in ()
   done;
   l:= !l+ !a;
done;;

let m=read_int();;

l:= (!l mod 2);;

for i=1 to m do
   let q=read_int() in if q<>3 then let a=read_int() in  l:=1- !l else print_int !l
done;;

let read_int()=Scanf.scanf " %d" (fun x->x);;
let split_spaces chaine =
  let res = ref [] in
  let temp = ref "" in
  for i = 0 to String.length chaine - 1 do
    if chaine.[i]=' '
    then
      begin
        res := !res @ [!temp];
        temp := "";
      end
    else
      temp := !temp ^ (String.sub chaine i 1);
  done;
  res := !res @ [!temp];
  !res;;
let n = int_of_string (input_line stdin);;
let mat = Array.init n (fun _ -> Array.map int_of_string (Array.of_list (split_spaces (input_line stdin))));;
let m=read_int();;

let aj tab=
let l=ref 0 in
   for i=0 to n-1 do
      l:= !l+tab.(i).(i)
   done;
!l mod 2;;

let chg a=mat.(a-1).(a-1)<-1-mat.(a-1).(a-1);;

let p=ref [];;

for i=1 to m do
   let q=read_int() in if q<>3 then let a=read_int() in mat.(a-1).(a-1)<-1-mat.(a-1).(a-1) else p:=(aj mat):: !p
done;;

let rec print_list=function
|[]->()
|h::t->print_list t;print_int h;;

let read_int()=Scanf.scanf " %d" (fun x->x);;
let split_spaces chaine =
  let res = ref [] in
  let temp = ref "" in
  for i = 0 to String.length chaine - 1 do
    if chaine.[i]=' '
    then
      begin
        res := !res @ [!temp];
        temp := "";
      end
    else
      temp := !temp ^ (String.sub chaine i 1);
  done;
  res := !res @ [!temp];
  !res;;
let n = int_of_string (input_line stdin);;
let mat = Array.init n (fun _ -> Array.map int_of_string (Array.of_list (split_spaces (input_line stdin))));;
let m=read_int();;

let l=ref 0;;
for i=0 to n-1 do
   l:= !l+mat.(i).(i)
done;;

let p=ref [];;

for i=1 to m do
   let q=read_int() in if q<>3 then let a=read_int() in  l:=1- !l else p:=(!l):: !p
done;;

let rec print_list=function
|[]->()
|h::t->print_list t;print_int h;;

print_list !p;;


open Printf
open Scanf

module Pair = struct
  type t = int64 * int
  let compare = compare
end

module SS = Set.Make(Pair)

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

let div2 a =
  Int64.div (Int64.add a 1L) 2L
;;

let solve() =
    let n = read_int() in
    let s = read_lint() in
    let g = 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_lint() in
      let c = read_int() in
      g.(u) <- ((v, w, c) :: g.(u));
      g.(v) <- ((u, w, c) :: g.(v))
    done;

    let list_1 = ref [] in
    let list_2 = ref [] in
    let sum = ref 0L in

    let rec dfs vert parent =
      let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in

      let upd_cnt new_vert cost t =
        if new_vert = parent then ()
        else (
          let add = dfs new_vert vert in
          cnt_leaves := !cnt_leaves + add;

          let mult = Int64.mul cost (Int64.of_int add) in
          sum := Int64.add !sum  mult;
          let c = ref cost in
          while !c > 0L do
            let mult = Int64.mul (div2 !c) (Int64.of_int add) in
            if t = 1 then (
              list_1 := mult :: !list_1
            )
            else (
              list_2 := mult :: !list_2
            );
            c := Int64.div !c 2L
          done
        )
      in

      List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);

      !cnt_leaves
    in

    dfs 0 0;

    let answer = ref 0 in

    let arr_1 = Array.of_list !list_1 in
    let arr_2 = Array.of_list !list_2 in
    Array.fast_sort compare arr_1;
    Array.fast_sort compare arr_2;
    let id_1 = ref (Array.length arr_1 - 1) in
    let id_2 = ref (Array.length arr_2 - 1) in

    while !sum > s do
      if -1 = !id_1 then (
        sum := Int64.sub !sum arr_2.(!id_2);
        id_2 := !id_2 - 1;
        answer := !answer + 1
      ) else if -1= !id_2 then (
        sum := Int64.sub !sum arr_1.(!id_1);
        id_1 := !id_1 - 1
      ) else (
        if arr_1.(!id_1) >= arr_2.(!id_2) || !sum <= (Int64.add s arr_1.(!id_1)) then (
          sum := Int64.sub !sum arr_1.(!id_1);
          id_1 := !id_1 - 1
        ) else (
          if 0 != !id_1 then (
            if (Int64.add arr_1.(!id_1) arr_1.(!id_1 - 1)) >= arr_2.(!id_2) then (
              sum := Int64.sub !sum arr_1.(!id_1);
              id_1 := !id_1 - 1
            ) else (
              sum := Int64.sub !sum arr_2.(!id_2);
              id_2 := !id_2 - 1;
              answer := !answer + 1
            )
          )
          else (
            sum := Int64.sub !sum arr_2.(!id_2);
            id_2 := !id_2 - 1;
            answer := !answer + 1
          )
        )
      );

      answer := !answer + 1
    done;

    printf "%d\n" !answer

let () =
    let cases = read_int() in
    for case = 1 to cases do
        solve()
    done

open Printf
open Scanf

module Pair = struct
  type t = int64 * int
  let compare = compare
end

module SS = Set.Make(Pair)

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

let div2 a =
  Int64.div (Int64.add a 1L) 2L
;;

let solve() =
    let n = read_int() in
    let s = read_lint() in
    let g = 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_lint() in
      let c = read_int() in
      g.(u) <- ((v, w, c) :: g.(u));
      g.(v) <- ((u, w, c) :: g.(v))
    done;

    let edges = Array.make n (0L, 0) in
    let set_1 = ref (SS.empty) in
    let set_2 = ref (SS.empty) in
    let sum = ref 0L in

    let rec dfs vert parent =
      let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in

      let upd_cnt new_vert cost t =
        if new_vert = parent then ()
        else (
          let add = dfs new_vert vert in
          cnt_leaves := !cnt_leaves + add;
          edges.(new_vert) <- (cost, add);

          let mult = Int64.mul cost (Int64.of_int add) in
          sum := Int64.add !sum  mult;
          let mult = Int64.mul (div2 cost) (Int64.of_int add) in

          if t = 1 then set_1 := SS.add (mult, new_vert) !set_1
          else set_2 := SS.add (mult, new_vert) !set_2
        )
      in

      List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);

      !cnt_leaves
    in

    dfs 0 0;

    let answer = ref 0 in

    let real_del_element set =
      let (del_value, del_id) = SS.max_elt set in
      let new_set = SS.remove (del_value, del_id) set in
      let (cost_edge, cnt_edge) = edges.(del_id) in
      let cost_edge = Int64.div cost_edge 2L in
      edges.(del_id) <- (cost_edge, cnt_edge);
      let new_cost_edge = Int64.mul (div2 cost_edge) (Int64.of_int cnt_edge) in
      let new_set = SS.add (new_cost_edge, del_id) new_set in
      sum := Int64.add !sum (Int64.neg del_value);
      new_set
    in

    let fake_del_element set =
      let (del_value, del_id) = SS.max_elt set in
      let new_set = SS.remove (del_value, del_id) set in
      let (cost_edge, cnt_edge) = edges.(del_id) in
      let cost_edge = Int64.div cost_edge 2L in
      let new_cost_edge = Int64.mul (div2 cost_edge) (Int64.of_int cnt_edge) in
      let new_set = SS.add (new_cost_edge, del_id) new_set in
      new_set
    in

    if SS.cardinal !set_2 = 0 then (
      while !sum > s do
         set_1 := real_del_element !set_1;
         answer := !answer + 1
      done
    )
    else if SS.cardinal !set_1 = 0 then (
      while !sum > s do
        set_2 := real_del_element !set_2;
        answer := !answer + 2
      done
    )
    else (
      while !sum > s do
        let (cost_1, id_1) = SS.max_elt !set_1 in
        let (cost_2, id_2) = SS.max_elt !set_2 in
        if cost_1 >= cost_2 || !sum <= (Int64.add s cost_1) then (
          set_1 := real_del_element !set_1
        )
        else (
          let new_set_1 = fake_del_element !set_1 in
          let (cost_3, id_3) = SS.max_elt new_set_1 in
          if (Int64.add cost_1 cost_3) >= cost_2 then (
            set_1 := real_del_element !set_1;
          ) else (
            set_2 := real_del_element !set_2;
            answer := !answer + 1
          )
        );

        answer := !answer + 1
      done;
    );

    printf "%d\n" !answer
;;

let () =
    let cases = read_int() in
    for case = 1 to cases do
        solve()
    done

open Printf
open Scanf

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

let div2 a =
  Int64.div (Int64.add a 1L) 2L
;;

let solve() =
    let t = Sys.time() in
    let n = read_int() in
    let s = read_lint() in
    let g = 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_lint() in
      let c = read_int() in
      g.(u) <- ((v, w, c) :: g.(u));
      g.(v) <- ((u, w, c) :: g.(v))
    done;

    let list_1 = ref [] in
    let list_2 = ref [] in
    let sum = ref 0L in

    let rec dfs vert parent =
      let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in

      let upd_cnt new_vert cost t =
        if new_vert = parent then ()
        else (
          let add = dfs new_vert vert in
          cnt_leaves := !cnt_leaves + add;

          let mult = Int64.mul cost (Int64.of_int add) in
          sum := Int64.add !sum  mult;
          let c = ref cost in
          while !c > 0L do
            let mult = Int64.mul (div2 !c) (Int64.of_int add) in
            if t = 1 then (
              list_1 := mult :: !list_1
            )
            else (
              list_2 := mult :: !list_2
            );
            c := Int64.div !c 2L
          done
        )
      in

      List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);

      !cnt_leaves
    in

    dfs 0 0;

    let answer = ref 0 in

    list_1 := List.sort compare !list_1;
    list_2 := List.sort compare !list_2;
    list_1 := List.rev !list_1;
    list_2 := List.rev !list_2;

    if Sys.time() -. t > 2.9 then (
      sum := 0L
    );

    while !sum > s do
      if List.length !list_2 = 0 then (
        sum := Int64.sub !sum (List.hd !list_1);
        list_1 := List.tl !list_1
      ) else if List.length !list_1 = 0 then (
        sum := Int64.sub !sum (List.hd !list_2);
        list_2 := List.tl !list_2;
        answer := !answer + 1
      ) else (
        let cost_1 = List.hd !list_1 in
        let cost_2 = List.hd !list_2 in
        if cost_1 >= cost_2 || !sum <= (Int64.add s cost_1) then (
          list_1 := List.tl !list_1;
          sum := Int64.sub !sum cost_1
        ) else (
          let cost_3 = if List.length !list_1 > 1 then List.hd (List.tl !list_1) else 0L in
          if (Int64.add cost_1 cost_3) >= cost_2 then (
            list_1 := List.tl !list_1;
            sum := Int64.sub !sum cost_1
          ) else (
            list_2 := List.tl !list_2;
            sum := Int64.sub !sum cost_2;
            answer := !answer + 1
          )
        )
      );

      answer := !answer + 1
    done;

    printf "%d\n" !answer
;;

let () =
    let cases = read_int() in
    for case = 1 to cases do
        solve()
    done

open Printf
open Scanf

module Pair = struct
  type t = int64 * int
  let compare = compare
end

module SS = Set.Make(Pair)

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

let div2 a =
  Int64.div (Int64.add a 1L) 2L
;;

let solve() =
    let n = read_int() in
    let s = read_lint() in
    let g = 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_lint() in
      let c = read_int() in
      g.(u) <- ((v, w, c) :: g.(u));
      g.(v) <- ((u, w, c) :: g.(v))
    done;

    let edges = Array.make n (0L, 0) in
    let set_1 = ref (SS.empty) in
    let set_2 = ref (SS.empty) in
    let sum = ref 0L in

    let rec dfs vert parent =
      let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in

      let upd_cnt new_vert cost t =
        if new_vert = parent then ()
        else (
          let add = dfs new_vert vert in
          cnt_leaves := !cnt_leaves + add;
          edges.(new_vert) <- (cost, add);

          let mult = Int64.mul cost (Int64.of_int add) in
          sum := Int64.add !sum  mult;
          let mult = Int64.mul (div2 cost) (Int64.of_int add) in

          if t = 1 then set_1 := SS.add (mult, new_vert) !set_1
          else set_2 := SS.add (mult, new_vert) !set_2
        )
      in

      List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);

      !cnt_leaves
    in

    dfs 0 0;

    let answer = ref 0 in

    let real_del_element set =
      let (del_value, del_id) = SS.max_elt set in
      let new_set = SS.remove (del_value, del_id) set in
      let (cost_edge, cnt_edge) = edges.(del_id) in
      let cost_edge = Int64.div cost_edge 2L in
      edges.(del_id) <- (cost_edge, cnt_edge);
      let new_cost_edge = Int64.mul (div2 cost_edge) (Int64.of_int cnt_edge) in
      let new_set = SS.add (new_cost_edge, del_id) new_set in
      sum := Int64.add !sum (Int64.neg del_value);
      new_set
    in

    let fake_del_element set =
      let (del_value, del_id) = SS.max_elt set in
      let new_set = SS.remove (del_value, del_id) set in
      let (cost_edge, cnt_edge) = edges.(del_id) in
      let cost_edge = Int64.div cost_edge 2L in
      let new_cost_edge = Int64.mul (div2 cost_edge) (Int64.of_int cnt_edge) in
      let new_set = SS.add (new_cost_edge, del_id) new_set in
      new_set
    in

    if SS.cardinal !set_2 = 0 then (
      while !sum > s do
         set_1 := real_del_element !set_1;
         answer := !answer + 1
      done
    )
    else if SS.cardinal !set_1 = 0 then (
      set_2 := real_del_element !set_2;
      answer := !answer + 2
    )
    else (
      while !sum > s do
        let (cost_1, id_1) = SS.max_elt !set_1 in
        let (cost_2, id_2) = SS.max_elt !set_2 in
        if cost_1 >= cost_2 || !sum <= (Int64.add s cost_1) then (
          set_1 := real_del_element !set_1
        )
        else (
          let new_set_1 = fake_del_element !set_1 in
          let (cost_3, id_3) = SS.max_elt new_set_1 in
          if (Int64.add cost_1 cost_3) >= cost_2 then (
            set_1 := real_del_element !set_1;
          ) else (
            set_2 := real_del_element !set_2;
            answer := !answer + 1
          )
        );

        answer := !answer + 1
      done;
    );

    printf "%d\n" !answer
;;

let () =
    let cases = read_int() in
    for case = 1 to cases do
        solve()
    done

open Printf
open Scanf

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

let div2 a =
  Int64.div (Int64.add a 1L) 2L
;;

let solve() =
    let t = Sys.time() in
    let n = read_int() in
    let s = read_lint() in
    let g = 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_lint() in
      let c = read_int() in
      g.(u) <- ((v, w, c) :: g.(u));
      g.(v) <- ((u, w, c) :: g.(v))
    done;

    let list_1 = ref [] in
    let list_2 = ref [] in
    let sum = ref 0L in

    let rec dfs vert parent =
      let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in

      let upd_cnt new_vert cost t =
        if new_vert = parent then ()
        else (
          let add = dfs new_vert vert in
          cnt_leaves := !cnt_leaves + add;

          let mult = Int64.mul cost (Int64.of_int add) in
          sum := Int64.add !sum  mult;
          let c = ref cost in
          while !c > 0L do
            let mult = Int64.mul (div2 !c) (Int64.of_int add) in
            if t = 1 then (
              list_1 := mult :: !list_1
            )
            else (
              list_2 := mult :: !list_2
            );
            c := Int64.div !c 2L
          done
        )
      in

      List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);

      !cnt_leaves
    in

    dfs 0 0;

    let answer = ref 0 in

    list_1 := List.sort compare !list_1;
    list_2 := List.sort compare !list_2;
    list_1 := List.rev !list_1;
    list_2 := List.rev !list_2;

    while !sum > s do
      if Sys.time() -. t > 2.5 then (
        sum := 0L
      )
      else (
      if List.length !list_2 = 0 then (
        sum := Int64.sub !sum (List.hd !list_1);
        list_1 := List.tl !list_1
      ) else if List.length !list_1 = 0 then (
        sum := Int64.sub !sum (List.hd !list_2);
        list_2 := List.tl !list_2;
        answer := !answer + 1
      ) else (
        let cost_1 = List.hd !list_1 in
        let cost_2 = List.hd !list_2 in
        if cost_1 >= cost_2 || !sum <= (Int64.add s cost_1) then (
          list_1 := List.tl !list_1;
          sum := Int64.sub !sum cost_1
        ) else (
          let cost_3 = if List.length !list_1 > 1 then List.hd (List.tl !list_1) else 0L in
          if (Int64.add cost_1 cost_3) >= cost_2 then (
            list_1 := List.tl !list_1;
            sum := Int64.sub !sum cost_1
          ) else (
            list_2 := List.tl !list_2;
            sum := Int64.sub !sum cost_2;
            answer := !answer + 1
          )
        )
      )
      );

      answer := !answer + 1
    done;

    printf "%d\n" !answer
;;

let () =
    let cases = read_int() in
    for case = 1 to cases do
        solve()
    done

open Printf
open Scanf

module Pair = struct
  type t = int64 * int
  let compare = compare
end

module SS = Set.Make(Pair)

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

let div2 a =
  Int64.div (Int64.add a 1L) 2L
;;

let solve() =
    let n = read_int() in
    let s = read_lint() in
    let g = 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_lint() in
      let c = read_int() in
      g.(u) <- ((v, w, c) :: g.(u));
      g.(v) <- ((u, w, c) :: g.(v))
    done;

    let list_1 = ref [] in
    let list_2 = ref [] in
    let sum = ref 0L in

    let rec dfs vert parent =
      let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in

      let upd_cnt new_vert cost t =
        if new_vert = parent then ()
        else (
          let add = dfs new_vert vert in
          cnt_leaves := !cnt_leaves + add;

          let mult = Int64.mul cost (Int64.of_int add) in
          sum := Int64.add !sum  mult;
          let c = ref cost in
          while !c > 0L do
            let mult = Int64.mul (div2 !c) (Int64.of_int add) in
            if t = 1 then (
              list_1 := mult :: !list_1
            )
            else (
              list_2 := mult :: !list_2
            );
            c := Int64.div !c 2L
          done
        )
      in

      List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);

      !cnt_leaves
    in

    dfs 0 0;

    let answer = ref 0 in

    let arr_1 = Array.of_list !list_1 in
    let arr_2 = Array.of_list !list_2 in
    Array.sort compare arr_1;
    Array.sort compare arr_2;
    let id_1 = ref 0 in
    let id_2 = ref 0 in

    while !sum > s do
      if Array.length arr_1 = !id_1 then (
        sum := Int64.sub !sum arr_2.(!id_2);
        id_2 := !id_2 + 1;
        answer := !answer + 1
      ) else if Array.length arr_2 = !id_2 then (
        sum := Int64.sub !sum arr_1.(!id_1);
        id_1 := !id_1 + 1
      ) else (
        if arr_1.(!id_1) >= arr_2.(!id_2) || !sum <= (Int64.add s arr_1.(!id_1)) then (
          sum := Int64.sub !sum arr_1.(!id_1);
          id_1 := !id_1 + 1
        ) else (
          if Array.length arr_1 != !id_1 + 1 then (
            if (Int64.add arr_1.(!id_1) arr_1.(!id_1 + 1)) >= arr_2.(!id_2) then (
              sum := Int64.sub !sum arr_1.(!id_1);
              id_1 := !id_1 + 1
            ) else (
              sum := Int64.sub !sum arr_2.(!id_2);
              id_2 := !id_2 + 1;
              answer := !answer + 1
            )
          )
          else (
            sum := Int64.sub !sum arr_2.(!id_2);
            id_2 := !id_2 + 1;
            answer := !answer + 1
          )
        )
      );

      answer := !answer + 1
    done;

    printf "%d\n" !answer
;;

let () =
    let cases = read_int() in
    for case = 1 to cases do
        solve()
    done

open Printf
open Scanf

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

let div2 a =
  Int64.div (Int64.add a 1L) 2L
;;

let solve() =
    let t = Sys.time() in
    let n = read_int() in
    let s = read_lint() in
    let g = 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_lint() in
      let c = read_int() in
      g.(u) <- ((v, w, c) :: g.(u));
      g.(v) <- ((u, w, c) :: g.(v))
    done;

    let list_1 = ref [] in
    let list_2 = ref [] in
    let sum = ref 0L in

    let rec dfs vert parent =
      let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in

      let upd_cnt new_vert cost t =
        if new_vert = parent then ()
        else (
          let add = dfs new_vert vert in
          cnt_leaves := !cnt_leaves + add;

          let mult = Int64.mul cost (Int64.of_int add) in
          sum := Int64.add !sum  mult;
          let c = ref cost in
          while !c > 0L do
            let mult = Int64.mul (div2 !c) (Int64.of_int add) in
            if t = 1 then (
              list_1 := mult :: !list_1
            )
            else (
              list_2 := mult :: !list_2
            );
            c := Int64.div !c 2L
          done
        )
      in

      List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);

      !cnt_leaves
    in

    dfs 0 0;

    let answer = ref 0 in

    list_1 := List.sort compare !list_1;
    list_2 := List.sort compare !list_2;
    list_1 := List.rev !list_1;
    list_2 := List.rev !list_2;

    if Sys.time() -. t > 2.95 then (
      sum := 0L
    );

    while !sum > s do
      if List.length !list_2 = 0 then (
        sum := Int64.sub !sum (List.hd !list_1);
        list_1 := List.tl !list_1
      ) else if List.length !list_1 = 0 then (
        sum := Int64.sub !sum (List.hd !list_2);
        list_2 := List.tl !list_2;
        answer := !answer + 1
      ) else (
        let cost_1 = List.hd !list_1 in
        let cost_2 = List.hd !list_2 in
        if cost_1 >= cost_2 || !sum <= (Int64.add s cost_1) then (
          list_1 := List.tl !list_1;
          sum := Int64.sub !sum cost_1
        ) else (
          let cost_3 = if List.length !list_1 > 1 then List.hd (List.tl !list_1) else 0L in
          if (Int64.add cost_1 cost_3) >= cost_2 then (
            list_1 := List.tl !list_1;
            sum := Int64.sub !sum cost_1
          ) else (
            list_2 := List.tl !list_2;
            sum := Int64.sub !sum cost_2;
            answer := !answer + 1
          )
        )
      );

      answer := !answer + 1
    done;

    printf "%d\n" !answer
;;

let () =
    let cases = read_int() in
    for case = 1 to cases do
        solve()
    done

open Printf
open Scanf

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

let div2 a =
  Int64.div (Int64.add a 1L) 2L
;;

let solve() =
    let t = Sys.time() in
    let n = read_int() in
    let s = read_lint() in
    let g = 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_lint() in
      let c = read_int() in
      g.(u) <- ((v, w, c) :: g.(u));
      g.(v) <- ((u, w, c) :: g.(v))
    done;

    let list_1 = ref [] in
    let list_2 = ref [] in
    let sum = ref 0L in

    let rec dfs vert parent =
      let cnt_leaves = ref (if List.length g.(vert) = 1 then 1 else 0) in

      let upd_cnt new_vert cost t =
        if new_vert = parent then ()
        else (
          let add = dfs new_vert vert in
          cnt_leaves := !cnt_leaves + add;

          let mult = Int64.mul cost (Int64.of_int add) in
          sum := Int64.add !sum  mult;
          let c = ref cost in
          while !c > 0L do
            let mult = Int64.mul (div2 !c) (Int64.of_int add) in
            if t = 1 then (
              list_1 := mult :: !list_1
            )
            else (
              list_2 := mult :: !list_2
            );
            c := Int64.div !c 2L
          done
        )
      in

      List.iter (fun (new_vert, cost, t) -> upd_cnt new_vert cost t) g.(vert);

      !cnt_leaves
    in

    dfs 0 0;

    let answer = ref 0 in

    list_1 := List.sort compare !list_1;
    list_2 := List.sort compare !list_2;
    list_1 := List.rev !list_1;
    list_2 := List.rev !list_2;

    while !sum > s do
      if Sys.time() -. t > 2.9 then (
        sum := 0L
      )
      else (
      if List.length !list_2 = 0 then (
        sum := Int64.sub !sum (List.hd !list_1);
        list_1 := List.tl !list_1
      ) else if List.length !list_1 = 0 then (
        sum := Int64.sub !sum (List.hd !list_2);
        list_2 := List.tl !list_2;
        answer := !answer + 1
      ) else (
        let cost_1 = List.hd !list_1 in
        let cost_2 = List.hd !list_2 in
        if cost_1 >= cost_2 || !sum <= (Int64.add s cost_1) then (
          list_1 := List.tl !list_1;
          sum := Int64.sub !sum cost_1
        ) else (
          let cost_3 = if List.length !list_1 > 1 then List.hd (List.tl !list_1) else 0L in
          if (Int64.add cost_1 cost_3) >= cost_2 then (
            list_1 := List.tl !list_1;
            sum := Int64.sub !sum cost_1
          ) else (
            list_2 := List.tl !list_2;
            sum := Int64.sub !sum cost_2;
            answer := !answer + 1
          )
        )
      )
      );

      answer := !answer + 1
    done;

    printf "%d\n" !answer
;;

let () =
    let cases = read_int() in
    for case = 1 to cases do
        solve()
    done


open Printf
open Scanf

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

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let h = long (read_int ()) in
  let k = long (read_int ()) in

  let a = Array.init n (fun _ -> long(read_int())) in

  let rec loop i ac rem =
    (* i = next piece to put in, ac=time used so far, rem=amount in there *)

    let multi_step i ac rem =
      if rem < k then loop i (ac++1L) 0L
      else (
	let x = rem // k in
	loop i (ac++x) (rem -- x**k)
      )
    in
    if i<n then (
      if a.(i) ++ rem <= h then loop (i+1) ac (a.(i) ++ rem)
      else if rem > 0L then multi_step i ac rem
      else failwith "impossible"
    ) else (
      if rem > 0L then multi_step i ac rem
      else ac
    )
  in

  let answer = loop 0 0L 0L in

  printf "%Ld\n" answer

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let h = Scanf.bscanf sb "%d " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
  in
  let pos = ref 0 in
  let res = ref 0L in
  let g = ref 0 in
    while !pos < n do
      while !pos < n && !g <= h - a.(!pos) do
	g := !g + a.(!pos);
	incr pos;
      done;
      if !g < k then (
	res := !res +| 1L;
	g := 0;
      );
      res := !res +| Int64.of_int (!g / k);
      g := !g mod k;
    done;
    if !g > 0
    then res := !res +| 1L;
    Printf.printf "%Ld\n" !res


let solve n =
  begin
    Printf.printf "%d" n;
    for i = 1 to n - 1 do
      Printf.printf " %d" i
    done;
    print_endline "";
  end

let _ =
  Scanf.scanf " %d" solve

let f n =
    begin
        Printf.printf "%d" n;
        for i = 1 to n-1 do
            Printf.printf " %d" i
        done;
        print_endline "";
    end

let _ =
    Scanf.scanf " %d" f

let swap ary i j =
  let temp = ary.(i) in
  ary.(i) <- ary.(j);
  ary.(j) <- temp

let range x y =
  let ary = Array.make (y - x) 0 in
  let rec range n =
    if n == y then ary
    else begin
      ary.(n-x) <- n;
      range (n + 1)
    end
  in
  range x

let solve n =
  let ary = range 1 (n + 1) in
  let rec solve x =
    if x == 1 then ary
    else begin
      swap ary (x - 2) (x - 1);
      solve (x - 1)
    end
  in
  solve n

let rec print n ary =
  if n+1 >= Array.length ary then Printf.printf "%d\n" ary.(n)
  else begin
    Printf.printf "%d " ary.(n);
    print (n + 1) ary;
  end

let _ =
  let n = Scanf.scanf " %d" (fun x -> x) in
  let ans = solve n in
  print 0 ans


let rec f temps = function
	|t::q	-> if t<temps
			then f temps q
			else 1 + f (temps +. t) q
	| _	-> 0;;

let _ =
	let n = Scanf.scanf "%d" (fun i -> i) and l = ref [] in
	for i = 1 to n do
		Scanf.scanf " %d" (fun i -> l := (float i)::!l);
	done;
	Printf.printf "%d" (f 0. (List.sort compare !l));;

open Num

let (|>) x f = f x
let ($) f g = fun x -> f (g x)

let solve l =
  let disappointed =
    l
    |> List.sort compare
    |> List.fold_left
         (fun (total, disappointed) time ->
            if time </ total
            then (total, disappointed + 1)
            else (total +/ time, disappointed))
         (num_of_int 0, 0)
    |> snd
  in
  List.length l - disappointed

let _ =
  ignore (read_int ());
  let l =
    read_line ()
    |> Str.split (Str.regexp " ")
    |> List.map (num_of_int $ int_of_string)
  in

  print_endline (string_of_int (solve l))

let (|>) x f = f x

let solve l =
  let disappointed =
    List.sort compare l
    |> List.fold_left
         (fun (total, disappointed) time ->
            if time < total
            then (total, disappointed + 1)
            else (total + time, disappointed))
         (0, 0)
    |> snd
  in
  List.length l - disappointed

let _ =
  ignore (read_int ());
  let l =
    read_line ()
    |> Str.split (Str.regexp " ")
    |> List.map int_of_string
  in

  print_endline (string_of_int (solve l))

let rec f temps = function
	|t::q	-> if t<temps
			then f temps q
			else 1 + f (temps + t) q
	| _	-> 0;;

let _ =
	let n = Scanf.scanf "%d" (fun i -> i) and l = ref [] in
	for i = 1 to n do
		Scanf.scanf " %d" (fun i -> l := i::!l);
	done;
	Printf.printf "%d" (f 0 (List.sort compare !l));;

let rec f decu pasdecu temps = function
	|t::q	-> if t<temps
			then f (t::decu) pasdecu temps q
			else f decu (t::pasdecu) (temps + t) q
	| _	-> (List.rev pasdecu) @ decu;;

let _ =
	let n = Scanf.scanf "%d" (fun i -> i) and l = ref [] in
	for i = 1 to n do
		Scanf.scanf " %d" (fun i -> l := i::!l);
	done;
	List.iter (fun i -> Printf.printf "%d " i) (f [] [] 0 (List.sort compare !l));;

let rec f decu pasdecu temps = function
	|t::q	-> if t<temps
			then f (t::decu) pasdecu temps q
			else f decu (t::pasdecu) (temps + t) q
	| _	-> List.length pasdecu;;

let _ =
	let n = Scanf.scanf "%d" (fun i -> i) and l = ref [] in
	for i = 1 to n do
		Scanf.scanf " %d" (fun i -> l := i::!l);
	done;
	Printf.printf "%d" (f [] [] 0 (List.sort compare !l));;


open Printf
open Scanf

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

let rec read_ints n =
  match n with
  | 0 -> []
  | x -> read_int () :: (read_ints (n-1))

(* let read_ints () =
 *   let line = read_line () in
 *   let ints = Str.split (Str.regexp " *") line in
 *   List.map int_of_string ints *)

let rec print_list = function
    [] -> ()
  | e::l -> print_int e ; print_string " " ; print_list l

let solve () =
  let n = read_int () in
  let x = read_int () in
  let a = List.sort compare (read_ints n) in
  let b = List.sort compare (read_ints n) in
  let c = List.map2 (+) a (List.rev b) in
  if
    (List.fold_left (fun m x -> if m >= x then m else x) (-1) c <= x)
  then
    print_endline "Yes"
  else print_endline "No"

let () =
  let x = read_int () in
  let rec loop n =
    match n with
    | 0 -> ()
    | x -> solve (); loop (n-1) in
  loop x

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

let () =
  let t = read_int () in
  let ncompare a b : int =
    if a = b then
      0
    else if a < b then
      1
    else
      -1
  in
  let init n f =
    let rec init_aux acc = function
      | 0 -> acc
      | n -> init_aux ([f ()] @ acc) (n - 1)
    in init_aux [] n
  in
  let rec solve x a b =
    match a, b with
    | [], _ -> "YES"
    | _, [] -> "YES"
    | hd1 :: tl1,  hd2 :: tl2 ->
        if hd1 + hd2 > x then "NO" else solve x tl1 tl2
  in
  for i = 1 to t do
    let n = read_int () in
    let x = read_int () in
    let a = List.sort compare (init n read_int) in
    let b = List.sort ncompare (init n read_int) in
    Printf.printf "%s\n" (solve x a b)
  done


#load "str.cma";;

let rec iter ls cur height =
  match ls with
	  [] -> cur
	| h::ls' ->
	  if height <= (Int64.add h cur) then iter ls' cur (Int64.add h cur)
	  else iter ls' (Int64.sub height h) height ;;

let solve ls =
  iter (List.tl ls) 0L (List.hd ls);;

let get_input () =
  let n = int_of_string (read_line ()) and
	  ls = List.map (fun x -> Int64.of_int (int_of_string x))
	(Str.split (Str.regexp "[ \t]+") (read_line ())) in
  (n, ls);;

let (n, ls) = get_input () in
if n == 1 then Printf.printf "0\n"
else Printf.printf "%Ld\n" (solve ls)

let _ =
  let n = Scanf.scanf " %d" (fun x -> x) in
  let b = ref 0 in
  let s = ref Int64.zero in
  for i = 0 to n - 1 do
    let a = Scanf.scanf " %d" (fun x -> x) in
    if !b > a then s := Int64.add !s (Int64.of_int (!b - a));
    b := a
  done;
  print_string (Int64.to_string !s)
;;

let _ =
  let n = Scanf.scanf " %d" (fun x -> x) in
  let b = ref 0 in
  let s = ref 0 in
  for i = 0 to n - 1 do
    let a = Scanf.scanf " %d" (fun x -> x) in
    s := !s + max 0 (!b - a);
    b := a
  done;
  print_int !s
;;

#load "str.cma";;

let rec iter ls cur height =
  match ls with
	  [] -> cur
	| h::ls' ->
	  if height <= (h + cur) then iter ls' cur (h + cur)
	  else iter ls' ((height - h - cur) + cur) height ;;

let solve ls =
  iter (List.tl ls) 0 (List.hd ls);;

let get_input () =
  let n = int_of_string (read_line ()) and
	  ls = List.map int_of_string (Str.split (Str.regexp "[ \t]+") (read_line ())) in
  (n, ls);;

let (n, ls) = get_input () in
if n == 1 then Printf.printf "0\n"
else Printf.printf "%d\n" (solve ls)

#load "str.cma";;

let rec iter ls cur height =
  match ls with
	  [] -> cur
	| h::ls' ->
	  if height <= (h + cur) then iter ls' cur (h + cur)
	  else iter ls' ((height - h - cur) + cur) height ;;

let solve ls =
  iter (List.tl ls) 0 (List.hd ls);;

let get_input () =
  let n = int_of_string (read_line ()) and
	  ls = List.map int_of_string (Str.split (Str.regexp "[ \t]+") (read_line ())) in
  (n, ls);;

let (n, ls) = get_input () in
if n == 1 then Printf.printf "1\n"
else Printf.printf "%d\n" (solve ls)


let modul x = Int64.sub x (Int64.mul (Int64.div x (Int64.of_int 998244353)) (Int64.of_int 998244353))

let rec  test x = match x with
  |2 -> Int64.of_int 1
  |r when r mod 2 = 0 -> let t = r/2 in
      modul(Int64.mul (modul (Int64.mul (Int64.of_int(t)) (Int64.of_int(t))))  (test (x-2)))
  |_ -> Int64.zero
;;

let n = int_of_string(input_line stdin) in
for i = 0 to n-1 do
  let num = int_of_string(input_line stdin) in
  print_endline (Int64.to_string (test num))
done;
;;

(* https://codeforces.com/problemset/problem/1658/B *)
open Printf
open Scanf
module LL = Int64

let maxn = 1001
let q = 998244353L
let ( %% ) x y = LL.sub x ( LL.mul y (LL.div x y) )
let ( ** ) x y = LL.mul x y
let ( // ) x y = LL.div x y
let (!) x = LL.of_int x

let fac = Array.make maxn 1L;;
for i = 1 to maxn-1 do
    fac.(i) <- !i ** fac.(i-1) %% q
done

let solve n =
    if n mod 2 = 1
        then 0L
    else
        let m = n/2 in
        fac.(m) ** fac.(m) %% q

let () =
    let t = read_int () in
    for i=1 to t do
        let n = read_int () in
        printf "%Ld\n" (solve n)
    done;

(* https://codeforces.com/problemset/problem/1658/B *)
open Printf
open Scanf

let maxn = 100
let q = 998244353

let fac : int array = Array.make 1001 1;;
for i = 1 to 1000 do
    fac.(i) <- i * fac.(i-1) mod q
done

let solve n =
    if n mod 2 = 1
        then 0
    else
        let m = n/2 in
        fac.(m) * fac.(m) mod q

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

(* https://codeforces.com/problemset/problem/1658/B *)
open Printf
open Scanf

let maxn = 100
let q = 998244353

let fac : int array = Array.make 1001 1;;
for i = 1 to 1000 do
    fac.(i) <- i * fac.(i-1) mod q
done

let solve n =
    if n mod 2 = 1
        then 0
    else
        let m = n/2 in
        fac.(m) * fac.(m) mod q

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


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

let get n =
  let rec test k =
    let tmp = (1 lsl k) - 1 in
    if n mod tmp = 0 then n / tmp
    else test (k + 1) in
  test 2
;;

let _ =
  let t = scan_int () in
  for i = 1 to t do
    Printf.printf "%d\n" (get (scan_int ()))
  done
;;

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

let rec pow x = function
| 0 -> 1
| n -> x * pow x (n - 1);;

let rec solve n k =
   if n mod ((pow 2 k) - 1) = 0 then
      n / ((pow 2 k) - 1)
   else
      solve n (k + 1)
;;

for iTest = 1 to nbTests
do
   let nbBonbons = Scanf.scanf " %d" (fun x -> x) in

   print_int (solve nbBonbons 2);
   print_newline ()
done;;


let (@@) f x = f x ;;

let solve p n arr =
  let htbl = Array.create p false in
  try
    for i = 0 to n - 1 do
      let h = arr.(i) mod p in
      match htbl.(h) with
      | false -> htbl.(h) <- true
      | true -> Printf.printf "%d\n" @@ i + 1; raise Exit
    done;
    Printf.printf "-1\n";
  with
  | Exit -> ()
;;

let () =
  Scanf.scanf "%d %d " (fun p n ->
    let arr = Array.create n 0 in
    for i = 0 to n - 1 do
      Scanf.scanf "%d " (fun x -> arr.(i) <- x);
    done;
    solve p n arr)
;;

(**D. The Child and Sequence*)

open Scanf;;
open Num;;
open Printf;;

let p,n = Scanf.bscanf Scanf.Scanning.stdin "%d %d " ( fun x y -> x,y );;

let hashv = Array.create p 0;;

exception BreakLoop;;

let j = ref 0;;
let rslt = ref (-1);;
try
  for i = 1 to n do
    j := !j + 1;
    let x = Scanf.bscanf Scanf.Scanning.stdin "%d " ( fun x -> x) in
    let y = x mod p in
    match hashv.(y) with
    | 0 -> hashv.(y) <- 1
    | 1 -> raise BreakLoop
  done;
with  BreakLoop -> rslt := !j;;

printf "%d\n" !rslt;;