Alice is visiting New York City. To make the trip fun, Alice will take photos of the city skyline and give the set of photos as a present to Bob. However, she wants to find the set of photos with maximum beauty and she needs your help. There are $$$n$$$ buildings in the city, the $$$i$$$-th of them has positive height $$$h_i$$$. All $$$n$$$ building heights in the city are different. In addition, each building has a beauty value $$$b_i$$$. Note that beauty can be positive or negative, as there are ugly buildings in the city too. A set of photos consists of one or more photos of the buildings in the skyline. Each photo includes one or more buildings in the skyline that form a contiguous segment of indices. Each building needs to be in exactly one photo. This means that if a building does not appear in any photo, or if a building appears in more than one photo, the set of pictures is not valid. The beauty of a photo is equivalent to the beauty $$$b_i$$$ of the shortest building in it. The total beauty of a set of photos is the sum of the beauty of all photos in it. Help Alice to find the maximum beauty a valid set of photos can have.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$), the number of buildings on the skyline.  The second line contains $$$n$$$ distinct integers $$$h_1, h_2, \ldots, h_n$$$ ($$$1 \le h_i \le n$$$). The $$$i$$$-th number represents the height of building $$$i$$$. The third line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$-10^9 \le b_i \le 10^9$$$). The $$$i$$$-th number represents the beauty of building $$$i$$$.

Print one number representing the maximum beauty Alice can achieve for a valid set of photos of the skyline.

NoteIn the first example, Alice can achieve maximum beauty by taking five photos, each one containing one building. In the second example, Alice can achieve a maximum beauty of $$$10$$$ by taking four pictures: three just containing one building, on buildings $$$1$$$, $$$2$$$ and $$$5$$$, each photo with beauty $$$-3$$$, $$$4$$$ and $$$7$$$ respectively, and another photo containing building $$$3$$$ and $$$4$$$, with beauty $$$2$$$. In the third example, Alice will just take one picture of the whole city.In the fourth example, Alice can take the following pictures to achieve maximum beauty: photos with just one building on buildings $$$1$$$, $$$2$$$, $$$8$$$, $$$9$$$, and $$$10$$$, and a single photo of buildings $$$3$$$, $$$4$$$, $$$5$$$, $$$6$$$, and $$$7$$$.

open Printf
open Scanf

let ( ++ ) a b = Int64.add a b
let long x = Int64.of_int x

let minfty = Int64.of_float (-1e18)

let make_fenwick_tree n =
  (Array.make (n+1) minfty, n)

let put_in_tree (a,n) i x =
(* put x into the fenwick tree at position i, which is currently minfty *)
  let rec loop i = if i>0 then (
    a.(i) <- max a.(i) x;
    loop (i - (i land (-i)))
  ) in
  loop (i+1)

let range_suffix (a,n) j =
  let rec loop i ac = if i > n then ac else (
    loop (i + (i land (-i))) (max ac a.(i))
  ) in
  loop (j+1) minfty

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

let () =
  let n = read_int () in
  let h = Array.init n read_int in
  let b = Array.init n read_long in

  let v = Array.make n 0L in
  let s = Array.make n (-1) in

  let rec scan li i = if i < n then
    match li with
      | [] -> scan [i] (i+1)
      | hd::t ->
	if h.(hd) > h.(i) then scan t i else (
	  s.(i) <- hd;
	  scan (i::li) (i+1)
	)
  in

  scan [] 0;

  let ft = make_fenwick_tree n in

  v.(0) <- b.(0);
  put_in_tree ft 0 v.(0);

  for i=1 to n-1 do
    v.(i) <-
      if s.(i) = -1 then max b.(i) (b.(i) ++ range_suffix ft 0)
      else max v.(s.(i)) (b.(i) ++ range_suffix ft (s.(i)));
    put_in_tree ft i v.(i)
  done;

  printf "%Ld\n" v.(n-1)


Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).q events are about to happen (in chronological order). They are of three types:  Application x generates a notification (this new notification is unread).  Thor reads all notifications generated so far by application x (he may re-read some notifications).  Thor reads the first t notifications generated by phone applications (notifications generated in first t events of the first type). It's guaranteed that there were at least t events of the first type before this event. Please note that he doesn't read first t unread notifications, he just reads the very first t notifications generated on his phone and he may re-read some of them in this operation. Please help Thor and tell him the number of unread notifications after each event. You may assume that initially there are no notifications in the phone.

The first line of input contains two integers n and q (1 ≤ n, q ≤ 300 000) — the number of applications and the number of events to happen. The next q lines contain the events. The i-th of these lines starts with an integer typei — type of the i-th event. If typei = 1 or typei = 2 then it is followed by an integer xi. Otherwise it is followed by an integer ti (1 ≤ typei ≤ 3, 1 ≤ xi ≤ n, 1 ≤ ti ≤ q).

Print the number of unread notifications after each event.

NoteIn the first sample:  Application 3 generates a notification (there is 1 unread notification).  Application 1 generates a notification (there are 2 unread notifications).  Application 2 generates a notification (there are 3 unread notifications).  Thor reads the notification generated by application 3, there are 2 unread notifications left. In the second sample test:  Application 2 generates a notification (there is 1 unread notification).  Application 4 generates a notification (there are 2 unread notifications).  Application 2 generates a notification (there are 3 unread notifications).  Thor reads first three notifications and since there are only three of them so far, there will be no unread notification left.  Application 3 generates a notification (there is 1 unread notification).  Application 3 generates a notification (there are 2 unread notifications).

open Printf
open Scanf

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

  let alist = Array.make (n+1) [] in
  let alert = Array.make (q+1) 0 in

  let rec loop i t ngen ncleared clearedto =
    if i > 0 then printf "%d\n" (ngen - ncleared);
    if i < q then
      match read_int() with
	| 1 ->
	  let x = read_int () in
	  alert.(t) <- 1;
	  alist.(x) <- t :: alist.(x);
	  loop (i+1) (t+1) (ngen+1) ncleared clearedto
	| 2 ->
	  let x = read_int () in
	  let nc = List.fold_left (
	    fun nc t ->
	      let nc = nc + alert.(t) in
	      alert.(t) <- 0;
	      nc
	  ) 0 alist.(x)
	  in
	  alist.(x) <- [];
	  loop (i+1) t ngen (ncleared + nc) clearedto
	| 3 ->
	  let tt = read_int() in
	  let cc = ref 0 in
	  for y = clearedto to tt-1 do
	    cc := alert.(y) + !cc;
	    alert.(y) <- 0;
	  done;
	  let clearedto = max clearedto tt in
	  loop (i+1) t ngen (ncleared + !cc) clearedto
	| _ -> failwith "bad input"
  in

  loop 0 0 0 0 0


Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed at the entrance to the reading room. It records the events of the form "reader entered room", "reader left room". Every reader is assigned a registration number during the registration procedure at the library — it's a unique integer from 1 to 106. Thus, the system logs events of two forms:  "+ ri" — the reader with registration number ri entered the room;  "- ri" — the reader with registration number ri left the room. The first launch of the system was a success, it functioned for some period of time, and, at the time of its launch and at the time of its shutdown, the reading room may already have visitors.Significant funds of the budget of Berland have been spent on the design and installation of the system. Therefore, some of the citizens of the capital now demand to explain the need for this system and the benefits that its implementation will bring. Now, the developers of the system need to urgently come up with reasons for its existence.Help the system developers to find the minimum possible capacity of the reading room (in visitors) using the log of the system available to you.

The first line contains a positive integer n (1 ≤ n ≤ 100) — the number of records in the system log. Next follow n events from the system journal in the order in which the were made. Each event was written on a single line and looks as "+ ri" or "- ri", where ri is an integer from 1 to 106, the registration number of the visitor (that is, distinct visitors always have distinct registration numbers). It is guaranteed that the log is not contradictory, that is, for every visitor the types of any of his two consecutive events are distinct. Before starting the system, and after stopping the room may possibly contain visitors.

Print a single integer — the minimum possible capacity of the reading room.

NoteIn the first sample test, the system log will ensure that at some point in the reading room were visitors with registration numbers 1, 1200 and 12001. More people were not in the room at the same time based on the log. Therefore, the answer to the test is 3.

open Printf
open Scanf

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

let () =
  let n = read_int () in

  let inc = Array.make n 0 in
  let id = Array.make n 0 in

  for i=0 to n-1 do
    inc.(i) <- if read_string() = "-" then -1 else 1;
    id.(i) <- read_int()
  done;

  let rogue = ref [] in

  let h = Hashtbl.create 10 in

  for i=0 to n-1 do
    if not (Hashtbl.mem h id.(i)) then (
      Hashtbl.replace h id.(i) true;
      if inc.(i) = -1 then rogue := id.(i) :: !rogue
    )
  done;

  let rec make_events ac i = if i=n then List.rev ac else
      make_events (id.(i) :: ac) (i+1)
  in

  let events = (!rogue) @ (make_events [] 0) in

  let h = Hashtbl.create 10 in

  let rec scan ev maxsize =
    match ev with [] -> maxsize
      | id::tail ->
	if Hashtbl.mem h id then (
	  Hashtbl.remove h id;
	  scan tail maxsize
	) else (
	  Hashtbl.replace h id true;
	  scan tail (max maxsize (Hashtbl.length h))
	)
  in

  let answer = scan events 0 in

  printf "%d\n" answer;

let () = Scanf.scanf "%d\n" (fun n ->
    let a = Array.make 1_000_000 false in
    let cur = ref 0 and best = ref 0 in
    for i = 1 to n do
        Scanf.scanf "%c %d\n" (fun c x ->
            if c = '-' && not a.(x - 1)
            then incr best
            else begin
                a.(x - 1) <- c = '+';
                if a.(x - 1) then begin
                    incr cur;
                    best := max !best !cur
                end else decr cur
            end)
    done;

    Printf.printf "%d\n" !best)


There are n boxes with colored balls on the table. Colors are numbered from 1 to n. i-th box contains ai balls, all of which have color i. You have to write a program that will divide all balls into sets such that:  each ball belongs to exactly one of the sets,  there are no empty sets,  there is no set containing two (or more) balls of different colors (each set contains only balls of one color),  there are no two sets such that the difference between their sizes is greater than 1. Print the minimum possible number of sets.

The first line contains one integer number n (1 ≤ n ≤ 500). The second line contains n integer numbers a1, a2, ... , an (1 ≤ ai ≤ 109).

Print one integer number — the minimum possible number of sets.

NoteIn the first example the balls can be divided into sets like that: one set with 4 balls of the first color, two sets with 3 and 4 balls, respectively, of the second color, and two sets with 4 balls of the third color.

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

let _ =
  let isqrt n = int_of_float (sqrt (float_of_int n)) in
  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;
    Array.sort compare a;
  in
  let m = isqrt a.(0) in
  let res = ref 1000000000000000000L in
  let calc k =
    try
      let t = ref 0L in
	for i = 0 to n - 1 do
	  let q = (a.(i) - 1) / (k + 1) + 1 in
	  let r = q * (k + 1) - a.(i) in
	    if q >= r
	    then t := !t +| Int64.of_int q
	    else raise Not_found
	done;
(*Printf.printf "calc %d %Ld\n" k !t;*)
	res := min !res !t
    with
      | Not_found -> ()
  in
    for i = 1 to m do
      calc i
    done;
    for i = 1 to m do
      calc (a.(0) / i);
      if a.(0) / i - 1 > 0
      then calc (a.(0) / i - 1);
    done;
    Printf.printf "%Ld\n" !res

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

let _ =
  let isqrt n = int_of_float (sqrt (float_of_int n)) in
  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;
    Array.sort compare a;
  in
  let m = isqrt a.(0) in
  let res = ref 1000000000000000000L in
  let calc k =
    try
      let t = ref 0L in
	for i = 0 to n - 1 do
	  let q = a.(i) / k in
	  let r = a.(i) mod k in
	    if q >= r
	    then t := !t +| Int64.of_int q
	    else raise Not_found
	done;
(*Printf.printf "calc %d %Ld\n" k !t;*)
	res := min !res !t
    with
      | Not_found -> ()
  in
    for i = 1 to m do
      calc i
    done;
    for i = 1 to m do
      calc (a.(0) / i);
      if a.(0) / i - 1 > 0
      then calc (a.(0) / i - 1);
    done;
    Printf.printf "%Ld\n" !res


An array is sorted if it has no inversionsA Young BoyYou are given an array of $$$n$$$ positive integers $$$a_1,a_2,\ldots,a_n$$$. In one operation you do the following:   Choose any integer $$$x$$$.  For all $$$i$$$ such that $$$a_i = x$$$, do $$$a_i := 0$$$ (assign $$$0$$$ to $$$a_i$$$). Find the minimum number of operations required to sort the array in non-decreasing order.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$). The second line of each test case contains $$$n$$$ positive integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le n$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print one integer — the minimum number of operations required to sort the array in non-decreasing order.

NoteIn the first test case, you can choose $$$x = 3$$$ for the operation, the resulting array is $$$[0, 0, 2]$$$.In the second test case, you can choose $$$x = 1$$$ for the first operation and $$$x = 3$$$ for the second operation, the resulting array is $$$[0, 0, 0, 0]$$$.

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

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

let () =
  let t = read_int () in

  for _ = 1 to t do
    let n = read_int () in
    let a = read_array read_int n in
    let pos = A.make (n + 1) (-1) in
    A.iteri (fun i x -> pos.(x) <- i) a;

    let i = ref (n - 2) in
    while !i >= 0 && a.(!i) <= a.(!i + 1) do i := !i - 1 done;
    let decr_pos = !i + 1 in
    if (decr_pos = 0) then
      pf "0\n"
    else begin
      let diff = Array.make (n + 1) false in
      let cnt = ref 0 in
      let mx = ref 0 in
      i := 0;
      while !i < n do
        mx := max !mx pos.(a.(!i));
        if (not diff.(a.(!i))) then cnt := !cnt + 1;
        diff.(a.(!i)) <- true;
        if !i = !mx && !mx + 1 >= decr_pos then begin
          pf "%d\n" !cnt;
          i := n;
        end;
        i := !i + 1;
      done
    end
  done

let get_num () =
  let rec f acc =
    try
      let c = input_byte stdin in
      if int_of_char '0' <= c && c <= int_of_char '9' then
        f ((acc * 10) + c - int_of_char '0')
      else if acc > 0 then Some acc
      else None
    with End_of_file -> if acc > 0 then Some acc else None
  in
  f 0

module Int_Set = Set.Make (struct
  type t = int

  let compare = compare
end)

let solve_case () =
  match get_num () with
  | Some n ->
      let rec f i set pending prev =
        if i = n then set
        else
          let i = i + 1 in
          match get_num () with
          | Some a ->
              let a = if Int_Set.mem a set then 0 else a in
              if a < prev then
                let set = Int_Set.union set pending in
                f i set (Int_Set.singleton a) a
              else f i set (Int_Set.add a pending) a
          | _ -> exit 1
      in
      let s = f 0 Int_Set.empty Int_Set.empty 0 in
      let s = Int_Set.remove 0 s in
      let fold_f a x = x + 1 in
      let ans = Int_Set.fold fold_f s 0 in
      print_int ans
  | _ -> exit 1

let () =
  match get_num () with
  | Some t ->
      let rec f i =
        if i = 0 then ()
        else
          let () = solve_case () in
          let () = print_newline () in
          f (i - 1)
      in
      f t
  | _ -> exit 1


Recently, Duff has been practicing weight lifting. As a hard practice, Malek gave her a task. He gave her a sequence of weights. Weight of i-th of them is 2wi pounds. In each step, Duff can lift some of the remaining weights and throw them away. She does this until there's no more weight left. Malek asked her to minimize the number of steps.  Duff is a competitive programming fan. That's why in each step, she can only lift and throw away a sequence of weights 2a1, ..., 2ak if and only if there exists a non-negative integer x such that 2a1 + 2a2 + ... + 2ak = 2x, i. e. the sum of those numbers is a power of two.Duff is a competitive programming fan, but not a programmer. That's why she asked for your help. Help her minimize the number of steps.

The first line of input contains integer n (1 ≤ n ≤ 106), the number of weights. The second line contains n integers w1, ..., wn separated by spaces (0 ≤ wi ≤ 106 for each 1 ≤ i ≤ n), the powers of two forming the weights values.

Print the minimum number of steps in a single line.

NoteIn the first sample case: One optimal way would be to throw away the first three in the first step and the rest in the second step. Also, it's not possible to do it in one step because their sum is not a power of two.In the second sample case: The only optimal way is to throw away one weight in each step. It's not possible to do it in less than 4 steps because there's no subset of weights with more than one weight and sum equal to a power of two.

let () = Scanf.scanf "%d\n" (fun n ->
    let w = Array.init n (fun _ -> Scanf.scanf "%d%_c" (fun x -> x)) in
    let s = Array.make 2_000_000 false in
    let on = ref 0 in

    let rec insert a =
        if s.(a) then begin
            s.(a) <- false;
            decr on;
            insert (a + 1)
        end else begin
            s.(a) <- true;
            incr on
        end
    in

    for i = 0 to n - 1 do
        insert w.(i)
    done;

    Printf.printf "%d\n" !on)

let _ =
  let sb = Scanf.Scanning.stdib in
  let m = 1000030 in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    Array.sort compare a;
    let b = Array.make m false in
      for i = 0 to n - 1 do
	let pos = ref a.(i) in
	  while b.(!pos) do
	    b.(!pos) <- false;
	    incr pos;
	  done;
	  b.(!pos) <- true
      done;
      let res = ref 0 in
	for i = 0 to m - 1 do
	  if b.(i)
	  then incr res
	done;
	Printf.printf "%d\n" !res

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

let () =
  let m = 1_000_100 in
  let a = Array.make m 0 in
  let n = read_int() in
  for i = 1 to n do
    let x = read_int() in
    a.(x) <- a.(x) + 1
  done;
  let rec go i carry acc =
    if i = m then acc
    else go (i+1) ((carry + a.(i)) / 2) (acc + ((carry + a.(i)) mod 2))
  in
  Printf.printf "%d\n" (go 0 0 0);;

let () = Scanf.scanf "%d\n" (fun n ->
let maxw = 1000100 in
let fr = Array.init (maxw+10) (fun _ -> 0) in

let rec read_loop i =
	if i < n then
	begin
		let w = (Scanf.scanf "%d%_c" (fun x -> x)) in fr.(w) <- succ fr.(w);
		read_loop (i+1)
	end
in read_loop 0;

let rec solve_loop i rem needed_steps =
	if i <= maxw then
		let total = rem + fr.(i) in
		solve_loop (i+1) (total/2) (needed_steps + (total mod 2))
	else
		Printf.printf "%d\n" needed_steps
in solve_loop 0 0 0);;

let () = Scanf.scanf "%d\n" (fun n ->
let maxw = 1000100 in
let fr = Array.init (maxw+10) (fun _ -> 0) in

let rec read_loop i =
	if i < n then
	begin
		let w = (Scanf.scanf "%d%_c" (fun x -> x)) in Array.set fr w (succ (Array.get fr w));
		read_loop (i+1)
	end
in read_loop 0;

let rec solve_loop i rem needed_steps =
	if i <= maxw then
		let total = rem + fr.(i) in
		solve_loop (i+1) (total/2) (needed_steps + (total mod 2))
	else
		Printf.printf "%d\n" needed_steps
in solve_loop 0 0 0);;

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    let b = Array.make n 0 in
    let pos = ref 0 in
      b.(0) <- a.(0);
      for i = 1 to n - 1 do
	incr pos;
	b.(!pos) <- a.(i);
	while !pos > 0 && b.(!pos) = b.(!pos - 1) do
	  decr pos;
	  b.(!pos) <- b.(!pos) + 1
	done;
      done;
      Printf.printf "%d\n" (!pos + 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
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    Array.sort compare a;
    let b = Array.make n 0 in
    let pos = ref 0 in
      b.(0) <- a.(0);
      for i = 1 to n - 1 do
	incr pos;
	b.(!pos) <- a.(i);
	while !pos > 0 && b.(!pos) = b.(!pos - 1) do
	  decr pos;
	  b.(!pos) <- b.(!pos) + 1
	done;
      done;
      Printf.printf "%d\n" (!pos + 1)


You are given two binary strings $$$a$$$ and $$$b$$$ of the same length. You can perform the following two operations on the string $$$a$$$:  Swap any two bits at indices $$$i$$$ and $$$j$$$ respectively ($$$1 \le i, j \le n$$$), the cost of this operation is $$$|i - j|$$$, that is, the absolute difference between $$$i$$$ and $$$j$$$.  Select any arbitrary index $$$i$$$ ($$$1 \le i \le n$$$) and flip (change $$$0$$$ to $$$1$$$ or $$$1$$$ to $$$0$$$) the bit at this index. The cost of this operation is $$$1$$$. Find the minimum cost to make the string $$$a$$$ equal to $$$b$$$. It is not allowed to modify string $$$b$$$.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^6$$$) — the length of the strings $$$a$$$ and $$$b$$$. The second and third lines contain strings $$$a$$$ and $$$b$$$ respectively. Both strings $$$a$$$ and $$$b$$$ have length $$$n$$$ and contain only '0' and '1'.

Output the minimum cost to make the string $$$a$$$ equal to $$$b$$$.

NoteIn the first example, one of the optimal solutions is to flip index $$$1$$$ and index $$$3$$$, the string $$$a$$$ changes in the following way: "100" $$$\to$$$ "000" $$$\to$$$ "001". The cost is $$$1 + 1 = 2$$$.The other optimal solution is to swap bits and indices $$$1$$$ and $$$3$$$, the string $$$a$$$ changes then "100" $$$\to$$$ "001", the cost is also $$$|1 - 3| = 2$$$.In the second example, the optimal solution is to swap bits at indices $$$2$$$ and $$$3$$$, the string $$$a$$$ changes as "0101" $$$\to$$$ "0011". The cost is $$$|2 - 3| = 1$$$.

open Printf open Scanf
module MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end
module MyInt64 = struct
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v)) let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v) let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done
	let string_of_list ?(separator=" ") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls "" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls

	let repm from_ to_ m_init fbod =
		let i,f,m = ref ~|from_,ref true,ref m_init in
		while !i <= ~|to_ && !f do
			match fbod (~~| !i) !m with
			| `Break -> f := false
			| `Break_m m' -> (f := false; m := m')
			| `Ok m' -> (i := !i +$ 1; m := m')
		done; !m
	let (@@@) = (@) let (@) a i = a.(~|i)
end open MyInt64
let () =
	let n = get_i64 0 in
	let s,t = scanf " %s %s" (fun u v -> u,v)
	in let s,t = char_list_of_string s,char_list_of_string t
	in let s,t = Array.of_list s,Array.of_list t
	in
	let ans,i = ref 0L,ref 0L
	in
	while !i < n do let j = !i in
		if s @ j <> t @ j then (
			if j+1L < n
			&& s @ j+1L = t @ j && s @ j = t @ j+1L then (
				(* adjacent swap : cost = 1 *)
				i += 2L
			) else (
				(* flip : cost = 1 *)
				i += 1L
			);
			ans += 1L
		) else i += 1L
	done;
	!ans |> printf "%Ld\n"


Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice!Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to play a simple game. All n people who came to the barbecue sat in a circle (thus each person received a unique index bi from 0 to n - 1). The person number 0 started the game (this time it was Vasya). All turns in the game were numbered by integers starting from 1. If the j-th turn was made by the person with index bi, then this person acted like that:  he pointed at the person with index (bi + 1) mod n either with an elbow or with a nod (x mod y is the remainder after dividing x by y);  if j ≥ 4 and the players who had turns number j - 1, j - 2, j - 3, made during their turns the same moves as player bi on the current turn, then he had drunk a glass of juice;  the turn went to person number (bi + 1) mod n. The person who was pointed on the last turn did not make any actions.The problem was, Vasya's drunk too much juice and can't remember the goal of the game. However, Vasya's got the recorded sequence of all the participants' actions (including himself). Now Vasya wants to find out the maximum amount of juice he could drink if he played optimally well (the other players' actions do not change). Help him.You can assume that in any scenario, there is enough juice for everybody.

The first line contains a single integer n (4 ≤ n ≤ 2000) — the number of participants in the game. The second line describes the actual game: the i-th character of this line equals 'a', if the participant who moved i-th pointed at the next person with his elbow, and 'b', if the participant pointed with a nod. The game continued for at least 1 and at most 2000 turns.

Print a single integer — the number of glasses of juice Vasya could have drunk if he had played optimally well.

NoteIn both samples Vasya has got two turns — 1 and 5. In the first sample, Vasya could have drunk a glass of juice during the fifth turn if he had pointed at the next person with a nod. In this case, the sequence of moves would look like "abbbb". In the second sample Vasya wouldn't drink a single glass of juice as the moves performed during turns 3 and 4 are different.

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

let input_string =
    Scanf.scanf "%s " (fun x -> x)
;;

let solve moves member_count =
    let rec solve_aux i ret =
        if i < String.length moves then begin
            if i >= 3 && moves.[i-1] == moves.[i-2]
                        && moves.[i-2] == moves.[i-3] then
                solve_aux (i+member_count) (ret+1)
            else
                solve_aux (i+member_count) ret
        end else ret
    in solve_aux 0 0
;;

let member_count = input_int in
let moves = input_string in
Printf.printf "%d\n" (solve moves member_count);

(* betaveros's polyglot adventure *)

let people = int_of_string (read_line ());;
let moves = read_line ();;

let canDrink s i = s.[i-1] == s.[i-2] && s.[i-2] == s.[i-3];;

let rec addDrinkCount s n i accum =
	if i >= String.length s then accum
	else addDrinkCount s n (i + n) (
		accum + if canDrink s i then 1 else 0);;

let solution = addDrinkCount moves people people 0 in
	print_endline (string_of_int solution);;

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

let input_string =
    Scanf.scanf "%s " (fun x -> x)
;;

let solve moves member_count =
    let rec solve_aux i ret =
        if i < String.length moves then begin
            if i >= 3 && moves.[i-1] == moves.[i-2]
                        && moves.[i-2] == moves.[i-3] then
                solve_aux (i+1) (ret+1)
            else
                solve_aux (i+1) ret
        end else ret
    in solve_aux 0 0
;;

let member_count = input_int in
let moves = input_string in
Printf.printf "%d\n" (solve moves member_count);


You are playing a variation of game 2048. Initially you have a multiset $$$s$$$ of $$$n$$$ integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset.During each operation you choose two equal integers from $$$s$$$, remove them from $$$s$$$ and insert the number equal to their sum into $$$s$$$.For example, if $$$s = \{1, 2, 1, 1, 4, 2, 2\}$$$ and you choose integers $$$2$$$ and $$$2$$$, then the multiset becomes $$$\{1, 1, 1, 4, 4, 2\}$$$.You win if the number $$$2048$$$ belongs to your multiset. For example, if $$$s = \{1024, 512, 512, 4\}$$$ you can win as follows: choose $$$512$$$ and $$$512$$$, your multiset turns into $$$\{1024, 1024, 4\}$$$. Then choose $$$1024$$$ and $$$1024$$$, your multiset turns into $$$\{2048, 4\}$$$ and you win.You have to determine if you can win this game.You have to answer $$$q$$$ independent queries.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 100$$$) – the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of elements in multiset. The second line of each query contains $$$n$$$ integers $$$s_1, s_2, \dots, s_n$$$ ($$$1 \le s_i \le 2^{29}$$$) — the description of the multiset. It is guaranteed that all elements of the multiset are powers of two.

For each query print YES if it is possible to obtain the number $$$2048$$$ in your multiset, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer).

NoteIn the first query you can win as follows: choose $$$512$$$ and $$$512$$$, and $$$s$$$ turns into $$$\{1024, 64, 1024\}$$$. Then choose $$$1024$$$ and $$$1024$$$, and $$$s$$$ turns into $$$\{2048, 64\}$$$ and you win.In the second query $$$s$$$ contains $$$2048$$$ initially.

let rec insert x = function
  | [] -> [x]
  | y::l when y < x -> y::(insert x l)
  |  _ as l -> x::l

let rec check l =
  match l with
  | [] -> false
  | x::l when x = 2048 -> true
  | y::l when y > 2048 -> false
  | [x] -> x = 2048
  | x::y::l -> if x = y then
      check (insert (y * 2) l)
    else
      check (y::l)

let _ =
  let n = int_of_string (input_line stdin) in
  for i = 1 to n do
    let _ = int_of_string (input_line stdin) in
    let l = List.map int_of_string @@ Str.split (Str.regexp " ") (input_line stdin) in
    if check (List.sort compare l) then
      Format.printf "YES@."
    else
      Format.printf "NO@."
  done

let rec check l =
  match l with
  | [] -> false
  | x::l when x = 2048 -> true
  | y::l when y > 2048 -> false
  | [x] -> x = 2048
  | x::y::l -> if x = y then
      check ((y * 2)::l)
    else
      check (y::l)

let _ =
  let n = int_of_string (input_line stdin) in
  for i = 1 to n do
    let _ = int_of_string (input_line stdin) in
    let l = List.map int_of_string @@ Str.split (Str.regexp " ") (input_line stdin) in
    if check (List.sort compare l) then
      Format.printf "YES@."
    else
      Format.printf "NO@."
  done


— Do you have a wish?  — I want people to stop gifting each other arrays.O_o and Another Young BoyAn array of $$$n$$$ positive integers $$$a_1,a_2,\ldots,a_n$$$ fell down on you from the skies, along with a positive integer $$$k \le n$$$.You can apply the following operation at most $$$k$$$ times:   Choose an index $$$1 \le i \le n$$$ and an integer $$$1 \le x \le 10^9$$$. Then do $$$a_i := x$$$ (assign $$$x$$$ to $$$a_i$$$). Then build a complete undirected weighted graph with $$$n$$$ vertices numbered with integers from $$$1$$$ to $$$n$$$, where edge $$$(l, r)$$$ ($$$1 \le l < r \le n$$$) has weight $$$\min(a_{l},a_{l+1},\ldots,a_{r})$$$.You have to find the maximum possible diameter of the resulting graph after performing at most $$$k$$$ operations.The diameter of a graph is equal to $$$\max\limits_{1 \le u < v \le n}{\operatorname{d}(u, v)}$$$, where $$$\operatorname{d}(u, v)$$$ is the length of the shortest path between vertex $$$u$$$ and vertex $$$v$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le k \le n$$$). The second line of each test case contains $$$n$$$ positive integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print one integer — the maximum possible diameter of the graph after performing at most $$$k$$$ operations.

NoteIn the first test case, one of the optimal arrays is $$$[2,4,5]$$$.The graph built on this array:   $$$\operatorname{d}(1, 2) = \operatorname{d}(1, 3) = 2$$$ and $$$\operatorname{d}(2, 3) = 4$$$, so the diameter is equal to $$$\max(2,2,4) = 4$$$.

type right_link = Sibling of sized_atom | Child of tree
and atom = { value : int; left_child : tree; right_link : right_link }
and tree = Empty | Node of sized_atom
and sized_atom = { atom : atom; size : int }

let print_tree tree =
  let rec build_floors floors tree rank =
    match tree with
    | Empty -> (floors, rank)
    | Node { atom = node; _ } ->
        let top, below =
          match floors with top :: below -> (top, below) | _ -> ([], [])
        in
        let rec f below atom rank top =
          let below, rank = build_floors below atom.left_child rank in
          let top = (atom.value, rank) :: top in
          let rank = rank + 1 in
          match atom.right_link with
          | Sibling { atom = sibling; _ } -> f below sibling rank top
          | Child child ->
              let below, rank = build_floors below child rank in
              (below, rank, top)
        in
        let below, rank, top = f below node rank top in
        (top :: below, rank)
  in
  let floors, _ = build_floors [] tree 1 in
  let rec f floors =
    match floors with
    | [] -> ()
    | floor :: floors ->
        let floor = List.rev floor in
        let rec g i floor =
          match floor with
          | [] -> ()
          | (value, rank) :: remainder ->
              let (), floor =
                if rank = i then (print_int value, remainder)
                else (print_char ' ', floor)
              in
              g (i + 1) floor
        in
        let () = g 1 floor in
        let () = print_newline () in
        f floors
  in

  f floors

let rec fold tree f acc =
  match tree with
  | Empty -> acc
  | Node { atom; _ } ->
      let rec g atom acc =
        let acc = fold atom.left_child f acc in
        let acc = f atom.value acc in
        match atom.right_link with
        | Sibling { atom; _ } -> g atom acc
        | Child tree -> fold tree f acc
      in
      g atom acc

let traverse tree f = fold tree f ()

type excess = ExcessZero | ExcessOne

let tree_size tree = match tree with Empty -> 0 | Node node -> node.size

let make_sized atom =
  let size =
    tree_size atom.left_child + 1
    +
    match atom.right_link with
    | Sibling sibling -> sibling.size
    | Child child -> tree_size child
  in
  { atom; size }

(* The index of the first element is zero *)
let rec get_nth tree n =
  match tree with
  | Empty -> failwith "Out of bounds"
  | Node { atom = node; _ } -> (
      let b = tree_size node.left_child in
      if n < b then get_nth node.left_child n
      else if n = b then node.value
      else
        let n = n - b - 1 in
        match node.right_link with
        | Sibling sibling -> get_nth (Node sibling) n
        | Child tree -> get_nth tree n)

let raise_left_child node =
  match node.left_child with
  | Empty -> assert false
  | Node { atom = new_node; _ } ->
      let rec f atom =
        match atom.right_link with
        | Child child ->
            let new_sibling = make_sized { node with left_child = child } in
            make_sized { atom with right_link = Sibling new_sibling }
        | Sibling sibling ->
            make_sized { atom with right_link = Sibling (f sibling.atom) }
      in
      f new_node

let rec width { atom = node; _ } =
  match node.right_link with
  | Sibling sibling -> width sibling + 1
  | Child _ -> 1

let lower_first_atoms atom size =
  let rec f atom size =
    if size = 0 then (atom, Child atom.atom.left_child)
    else
      match atom.atom.right_link with
      | Child _ -> assert false
      | Sibling sibling ->
          let root, right_link = f sibling (size - 1) in
          (root, Sibling (make_sized { atom.atom with right_link }))
  in
  let root, link = f atom size in
  match link with
  | Child _ -> assert false
  | Sibling node -> make_sized { root.atom with left_child = Node node }

let rec unflatten_list node child_sizes =
  match child_sizes with
  | [] -> assert false
  | n :: s ->
      let toplevel_node = lower_first_atoms node n in
      let link =
        match toplevel_node.atom.right_link with
        | Child _ -> assert false
        | Sibling sibling -> (
            match s with
            | [] -> Child (Node sibling)
            | _ -> Sibling (unflatten_list sibling s))
      in
      make_sized { toplevel_node.atom with right_link = link }

let make_higher_if_necessary wide_node =
  let w = width wide_node in
  match w with
  | 1 | 2 -> (wide_node, ExcessZero)
  | 3 | 4 -> (unflatten_list wide_node [ 1 ], ExcessOne)
  | _ -> assert false

let rec insert_in_node value { atom = node; _ } =
  let rec g atom =
    if value <= atom.value then
      let new_node, excess = insert_full value atom.left_child in
      let atom = { atom with left_child = Node new_node } in
      match excess with
      | ExcessZero -> make_sized atom
      | ExcessOne -> raise_left_child atom
    else
      match atom.right_link with
      | Sibling sibling ->
          make_sized { atom with right_link = Sibling (g sibling.atom) }
      | Child right_child -> (
          let new_node, excess = insert_full value right_child in
          match excess with
          | ExcessZero ->
              make_sized { atom with right_link = Child (Node new_node) }
          | ExcessOne -> make_sized { atom with right_link = Sibling new_node })
  in
  let possibly_too_wide = g node in
  make_higher_if_necessary possibly_too_wide

and insert_full value tree =
  match tree with
  | Empty ->
      ( make_sized { value; left_child = Empty; right_link = Child Empty },
        ExcessOne )
  | Node node -> insert_in_node value node

let insert value tree =
  let t, _ = insert_full value tree in
  Node t

type deficit = DeficitZero | DeficitOne

let rec expand node =
  let new_sibling =
    match node.right_link with
    | Child (Node new_sibling) -> new_sibling
    | Child Empty -> assert false
    | Sibling sibling -> expand sibling.atom
  in
  (* Does not change the size because it's the same subtree on the
     right, its status might just change from right child to sibling. *)
  let center = { node with right_link = Sibling new_sibling } in
  raise_left_child center

let expand_except_left_child node =
  let sibling =
    match node.right_link with
    | Sibling sibling -> expand sibling.atom
    | Child (Node new_sibling) -> new_sibling
    | Child Empty -> assert false
  in
  make_sized { node with right_link = Sibling sibling }

let make_higher_if_possible node =
  let w = width node in
  match w with
  | 2 -> (node, DeficitOne)
  | _ ->
      let child_sizes =
        match w with
        | 3 | 4 -> [ 1 ]
        | 5 -> [ 2 ]
        | 6 | 7 -> [ 2; 1 ]
        | _ -> assert false
      in
      (unflatten_list node child_sizes, DeficitZero)

let handle_left_deficit node =
  let atom = expand_except_left_child node in
  make_higher_if_possible atom

let handle_right_deficit node =
  let atom = raise_left_child node in
  make_higher_if_possible atom

let rec extract_min_full node =
  match node.left_child with
  | Empty -> (
      match node.right_link with
      | Sibling sibling -> (Node sibling, DeficitZero, node.value)
      | Child Empty -> (Empty, DeficitOne, node.value)
      | _ -> assert false)
  | Node left_node ->
      let new_child, deficit, min = extract_min_full left_node.atom in
      (* `make_sized` is not necessary I think. *)
      let node = make_sized { node with left_child = new_child } in
      let node, deficit =
        match deficit with
        | DeficitZero -> (node, DeficitZero)
        | DeficitOne -> handle_left_deficit node.atom
      in
      (Node node, deficit, min)

let extract_min tree =
  match tree with
  | Empty -> failwith "Called extract_min on a empty tree"
  | Node node ->
      let tree, _, min = extract_min_full node.atom in
      (tree, min)

let update_right_with_deficit node f =
  let right =
    match node.right_link with Sibling node -> Node node | Child tree -> tree
  in
  let tree, deficit = f right in
  let tree, deficit =
    match (tree, deficit, node.right_link) with
    | Node sibling, DeficitZero, Sibling _ ->
        (make_sized { node with right_link = Sibling sibling }, DeficitZero)
    | Empty, DeficitZero, Sibling _ -> assert false
    | tree, DeficitOne, Sibling _ | tree, DeficitZero, Child _ ->
        (make_sized { node with right_link = Child tree }, DeficitZero)
    | tree, DeficitOne, Child _ ->
        let unbalanced_node = { node with right_link = Child tree } in
        handle_right_deficit unbalanced_node
  in

  (tree, deficit)

let delete_atom node =
  match node.right_link with
  | Sibling right | Child (Node right) ->
      let tree, deficit, min = extract_min_full right.atom in
      let link, deficit =
        match (tree, deficit, node.right_link) with
        | Empty, DeficitZero, _ -> assert false
        | Node new_node, DeficitZero, Sibling _ ->
            (Sibling new_node, DeficitZero)
        | tree, DeficitOne, Sibling _ | tree, DeficitZero, Child _ ->
            (Child tree, DeficitZero)
        | tree, DeficitOne, Child _ -> (Child tree, DeficitOne)
      in
      let node = { node with value = min; right_link = link } in
      let node, deficit =
        match deficit with
        | DeficitZero -> (make_sized node, DeficitZero)
        | DeficitOne -> handle_right_deficit node
      in
      (Node node, deficit)
  | Child Empty -> (node.left_child, DeficitOne)

let rec delete_full value tree =
  match tree with
  | Empty -> (Empty, DeficitZero)
  | Node node -> delete_in_node value node

and delete_in_node value node =
  if value < node.atom.value then
    let tree, deficit = delete_full value node.atom.left_child in
    let node = { node.atom with left_child = tree } in
    let node, deficit =
      match deficit with
      | DeficitZero -> (make_sized node, DeficitZero)
      | DeficitOne -> handle_left_deficit node
    in
    (Node node, deficit)
  else if value = node.atom.value then delete_atom node.atom
  else
    let f = delete_full value in
    let node, deficit = update_right_with_deficit node.atom f in
    (Node node, deficit)

let delete value tree =
  let tree, _ = delete_full value tree in
  tree

let get_num () =
  let rec f acc =
    try
      let c = input_byte stdin in
      if int_of_char '0' <= c && c <= int_of_char '9' then
        f ((acc * 10) + c - int_of_char '0')
      else if acc > 0 then Some acc
      else f 0
    with End_of_file -> if acc > 0 then Some acc else None
  in
  f 0

let get_num () = match get_num () with Some x -> x | None -> exit 1
let max_value = 1000000000
let half = max_value / 2

let double x = if x < half then 2 * x else max_value

let rec print_list list =
  match list with
  | [] -> ()
  | x :: [] ->
      let () = print_int x in
      print_newline ()
  | x :: list ->
      let () = print_int x in
      let () = print_char ' ' in
      print_list list

let solve_case () =
  let n = get_num () in
  let k = get_num () in

  let ans =
    let a0 = get_num () in
    let a1 = get_num () in

    let rest, search_tree =
      let rec f i =
        if i >= n then ([], Empty)
        else
          let x = get_num () in
          let rest, search_tree = f (i + 1) in
          (x :: rest, insert (double x) search_tree)
      in
      f 2
    in
    if k = n then max_value
    else
      let search_tree = insert a0 search_tree in
      let search_tree = insert a1 search_tree in

      let get_candidate tree = get_nth tree k in

      let ans = get_candidate search_tree in

      let rec f ans search_tree a0 a1 rest =
        match rest with
        | [] -> ans
        | x :: rest ->
            let search_tree = delete a0 search_tree in
            let search_tree = insert (double a0) search_tree in
            let search_tree = delete (double x) search_tree in
            let search_tree = insert x search_tree in
            let cand = get_candidate search_tree in
            let ans = if ans < cand then cand else ans in
            f ans search_tree a1 x rest
      in
      f ans search_tree a0 a1 rest
  in
  let ans = if max_value < ans then max_value else ans in
  print_int ans

let run () =
  let t = get_num () in
  let rec f i =
    if i = 0 then ()
    else
      let () = solve_case () in
      let () = print_newline () in
      (f [@tailcall]) (i - 1)
  in
  f t

let () = run ()

type right_link = Sibling of sized_atom | Child of tree
and atom = { value : int; left_child : tree; right_link : right_link }
and tree = Empty | Node of sized_atom
and sized_atom = { atom : atom; size : int }

let print_tree tree =
  let rec build_floors floors tree rank =
    match tree with
    | Empty -> (floors, rank)
    | Node { atom = node; _ } ->
        let top, below =
          match floors with top :: below -> (top, below) | _ -> ([], [])
        in
        let rec f below atom rank top =
          let below, rank = build_floors below atom.left_child rank in
          let top = (atom.value, rank) :: top in
          let rank = rank + 1 in
          match atom.right_link with
          | Sibling { atom = sibling; _ } -> f below sibling rank top
          | Child child ->
              let below, rank = build_floors below child rank in
              (below, rank, top)
        in
        let below, rank, top = f below node rank top in
        (top :: below, rank)
  in
  let floors, _ = build_floors [] tree 1 in
  let rec f floors =
    match floors with
    | [] -> ()
    | floor :: floors ->
        let floor = List.rev floor in
        let rec g i floor =
          match floor with
          | [] -> ()
          | (value, rank) :: remainder ->
              let (), floor =
                if rank = i then (print_int value, remainder)
                else (print_char ' ', floor)
              in
              g (i + 1) floor
        in
        let () = g 1 floor in
        let () = print_newline () in
        f floors
  in

  f floors

let rec fold tree f acc =
  match tree with
  | Empty -> acc
  | Node { atom; _ } ->
      let rec g atom acc =
        let acc = fold atom.left_child f acc in
        let acc = f atom.value acc in
        match atom.right_link with
        | Sibling { atom; _ } -> g atom acc
        | Child tree -> fold tree f acc
      in
      g atom acc

let traverse tree f = fold tree f ()

type excess = ExcessZero | ExcessOne

let tree_size tree = match tree with Empty -> 0 | Node node -> node.size

let make_sized atom =
  let size =
    tree_size atom.left_child + 1
    +
    match atom.right_link with
    | Sibling sibling -> sibling.size
    | Child child -> tree_size child
  in
  { atom; size }

(* The index of the first element is zero *)
let rec get_nth tree n =
  match tree with
  | Empty -> failwith "Out of bounds"
  | Node { atom = node; _ } -> (
      let b = tree_size node.left_child in
      if n < b then get_nth node.left_child n
      else if n = b then node.value
      else
        let n = n - b - 1 in
        match node.right_link with
        | Sibling sibling -> get_nth (Node sibling) n
        | Child tree -> get_nth tree n)

let raise_left_child node =
  match node.left_child with
  | Empty -> assert false
  | Node { atom = new_node; _ } ->
      let rec f atom =
        match atom.right_link with
        | Child child ->
            let new_sibling = make_sized { node with left_child = child } in
            make_sized { atom with right_link = Sibling new_sibling }
        | Sibling sibling ->
            make_sized { atom with right_link = Sibling (f sibling.atom) }
      in
      f new_node

let rec width { atom = node; _ } =
  match node.right_link with
  | Sibling sibling -> width sibling + 1
  | Child _ -> 1

let lower_first_atoms atom size =
  let rec f atom size =
    if size = 0 then (atom, Child atom.atom.left_child)
    else
      match atom.atom.right_link with
      | Child _ -> assert false
      | Sibling sibling ->
          let root, right_link = f sibling (size - 1) in
          (root, Sibling (make_sized { atom.atom with right_link }))
  in
  let root, link = f atom size in
  match link with
  | Child _ -> assert false
  | Sibling node -> make_sized { root.atom with left_child = Node node }

let rec unflatten_list node child_sizes =
  match child_sizes with
  | [] -> assert false
  | n :: s ->
      let toplevel_node = lower_first_atoms node n in
      let link =
        match toplevel_node.atom.right_link with
        | Child _ -> assert false
        | Sibling sibling -> (
            match s with
            | [] -> Child (Node sibling)
            | _ -> Sibling (unflatten_list sibling s))
      in
      make_sized { toplevel_node.atom with right_link = link }

let make_higher_if_necessary wide_node =
  let w = width wide_node in
  match w with
  | 1 | 2 -> (wide_node, ExcessZero)
  | 3 | 4 -> (unflatten_list wide_node [ 1 ], ExcessOne)
  | _ -> assert false

let rec insert_in_node value { atom = node; _ } =
  let rec g atom =
    if value <= atom.value then
      let new_node, excess = insert_full value atom.left_child in
      let atom = { atom with left_child = Node new_node } in
      match excess with
      | ExcessZero -> make_sized atom
      | ExcessOne -> raise_left_child atom
    else
      match atom.right_link with
      | Sibling sibling ->
          make_sized { atom with right_link = Sibling (g sibling.atom) }
      | Child right_child -> (
          let new_node, excess = insert_full value right_child in
          match excess with
          | ExcessZero ->
              make_sized { atom with right_link = Child (Node new_node) }
          | ExcessOne -> make_sized { atom with right_link = Sibling new_node })
  in
  let possibly_too_wide = g node in
  make_higher_if_necessary possibly_too_wide

and insert_full value tree =
  match tree with
  | Empty ->
      ( make_sized { value; left_child = Empty; right_link = Child Empty },
        ExcessOne )
  | Node node -> insert_in_node value node

let insert value tree =
  let t, _ = insert_full value tree in
  Node t

type deficit = DeficitZero | DeficitOne

let rec expand node =
  let new_sibling =
    match node.right_link with
    | Child (Node new_sibling) -> new_sibling
    | Child Empty -> assert false
    | Sibling sibling -> expand sibling.atom
  in
  (* Does not change the size because it's the same subtree on the
     right, its status might just change from right child to sibling. *)
  let center = { node with right_link = Sibling new_sibling } in
  raise_left_child center

let expand_except_left_child node =
  let sibling =
    match node.right_link with
    | Sibling sibling -> expand sibling.atom
    | Child (Node new_sibling) -> new_sibling
    | Child Empty -> assert false
  in
  make_sized { node with right_link = Sibling sibling }

let make_higher_if_possible node =
  let w = width node in
  match w with
  | 2 -> (node, DeficitOne)
  | _ ->
      let child_sizes =
        match w with
        | 3 | 4 -> [ 1 ]
        | 5 -> [ 2 ]
        | 6 | 7 -> [ 2; 1 ]
        | _ -> assert false
      in
      (unflatten_list node child_sizes, DeficitZero)

let handle_left_deficit node =
  let atom = expand_except_left_child node in
  make_higher_if_possible atom

let handle_right_deficit node =
  let atom = raise_left_child node in
  make_higher_if_possible atom

let rec extract_min_full node =
  match node.left_child with
  | Empty -> (
      match node.right_link with
      | Sibling sibling -> (Node sibling, DeficitZero, node.value)
      | Child Empty -> (Empty, DeficitOne, node.value)
      | _ -> assert false)
  | Node left_node ->
      let new_child, deficit, min = extract_min_full left_node.atom in
      (* `make_sized` is not necessary I think. *)
      let node = make_sized { node with left_child = new_child } in
      let node, deficit =
        match deficit with
        | DeficitZero -> (node, DeficitZero)
        | DeficitOne -> handle_left_deficit node.atom
      in
      (Node node, deficit, min)

let extract_min tree =
  match tree with
  | Empty -> failwith "Called extract_min on a empty tree"
  | Node node ->
      let tree, _, min = extract_min_full node.atom in
      (tree, min)

let update_right_with_deficit node f =
  let right =
    match node.right_link with Sibling node -> Node node | Child tree -> tree
  in
  let tree, deficit = f right in
  let tree, deficit =
    match (tree, deficit, node.right_link) with
    | Node sibling, DeficitZero, Sibling _ ->
        (make_sized { node with right_link = Sibling sibling }, DeficitZero)
    | Empty, DeficitZero, Sibling _ -> assert false
    | tree, DeficitOne, Sibling _ | tree, DeficitZero, Child _ ->
        (make_sized { node with right_link = Child tree }, DeficitZero)
    | tree, DeficitOne, Child _ ->
        let unbalanced_node = { node with right_link = Child tree } in
        handle_right_deficit unbalanced_node
  in

  (tree, deficit)

let delete_atom node =
  match node.right_link with
  | Sibling right | Child (Node right) ->
      let tree, deficit, min = extract_min_full right.atom in
      let link, deficit =
        match (tree, deficit, node.right_link) with
        | Empty, DeficitZero, _ -> assert false
        | Node new_node, DeficitZero, Sibling _ ->
            (Sibling new_node, DeficitZero)
        | tree, DeficitOne, Sibling _ | tree, DeficitZero, Child _ ->
            (Child tree, DeficitZero)
        | tree, DeficitOne, Child _ -> (Child tree, DeficitOne)
      in
      let node = { node with value = min; right_link = link } in
      let node, deficit =
        match deficit with
        | DeficitZero -> (make_sized node, DeficitZero)
        | DeficitOne -> handle_right_deficit node
      in
      (Node node, deficit)
  | Child Empty -> (node.left_child, DeficitOne)

let rec delete_full value tree =
  match tree with
  | Empty -> (Empty, DeficitZero)
  | Node node -> delete_in_node value node

and delete_in_node value node =
  if value < node.atom.value then
    let tree, deficit = delete_full value node.atom.left_child in
    let node = { node.atom with left_child = tree } in
    let node, deficit =
      match deficit with
      | DeficitZero -> (make_sized node, DeficitZero)
      | DeficitOne -> handle_left_deficit node
    in
    (Node node, deficit)
  else if value = node.atom.value then delete_atom node.atom
  else
    let f = delete_full value in
    let node, deficit = update_right_with_deficit node.atom f in
    (Node node, deficit)

let delete value tree =
  let tree, _ = delete_full value tree in
  tree

let get_num () =
  let rec f acc =
    try
      let c = input_byte stdin in
      if int_of_char '0' <= c && c <= int_of_char '9' then
        f ((acc * 10) + c - int_of_char '0')
      else if acc > 0 then Some acc
      else f 0
    with End_of_file -> if acc > 0 then Some acc else None
  in
  f 0

let get_num () = match get_num () with Some x -> x | None -> exit 1
let max_value = 1000000000

let rec print_list list =
  match list with
  | [] -> ()
  | x :: [] ->
      let () = print_int x in
      print_newline ()
  | x :: list ->
      let () = print_int x in
      let () = print_char ' ' in
      print_list list

let solve_case () =
  let n = get_num () in
  let k = get_num () in

  let ans =
    let a0 = get_num () in
    let a1 = get_num () in

    let rest, search_tree =
      let rec f i =
        if i >= n then ([], Empty)
        else
          let x = get_num () in
          let rest, search_tree = f (i + 1) in
          (x :: rest, insert (2 * x) search_tree)
      in
      f 2
    in
    if k = n then max_value
    else
      let search_tree = insert a0 search_tree in
      let search_tree = insert a1 search_tree in

      let get_candidate tree = get_nth tree k in

      let ans = get_candidate search_tree in

      let rec f ans search_tree a0 a1 rest =
        match rest with
        | [] -> ans
        | x :: rest ->
            let search_tree = delete a0 search_tree in
            let search_tree = insert (2 * a0) search_tree in
            let search_tree = delete (2 * x) search_tree in
            let search_tree = insert x search_tree in
            let cand = get_candidate search_tree in
            let ans = if ans < cand then cand else ans in
            f ans search_tree a1 x rest
      in
      f ans search_tree a0 a1 rest
  in
  let ans = if max_value < ans then max_value else ans in
  print_int ans

let run () =
  let t = get_num () in
  let rec f i =
    if i = 0 then ()
    else
      let () = solve_case () in
      let () = print_newline () in
      (f [@tailcall]) (i - 1)
  in
  f t

let () = run ()

type right_link = Sibling of sized_atom | Child of tree
and atom = { value : int; left_child : tree; right_link : right_link }
and tree = Empty | Node of sized_atom
and sized_atom = { atom : atom; size : int }

let print_tree tree =
  let rec build_floors floors tree rank =
    match tree with
    | Empty -> (floors, rank)
    | Node { atom = node; _ } ->
        let top, below =
          match floors with top :: below -> (top, below) | _ -> ([], [])
        in
        let rec f below atom rank top =
          let below, rank = build_floors below atom.left_child rank in
          let top = (atom.value, rank) :: top in
          let rank = rank + 1 in
          match atom.right_link with
          | Sibling { atom = sibling; _ } -> f below sibling rank top
          | Child child ->
              let below, rank = build_floors below child rank in
              (below, rank, top)
        in
        let below, rank, top = f below node rank top in
        (top :: below, rank)
  in
  let floors, _ = build_floors [] tree 1 in
  let rec f floors =
    match floors with
    | [] -> ()
    | floor :: floors ->
        let floor = List.rev floor in
        let rec g i floor =
          match floor with
          | [] -> ()
          | (value, rank) :: remainder ->
              let (), floor =
                if rank = i then (print_int value, remainder)
                else (print_char ' ', floor)
              in
              g (i + 1) floor
        in
        let () = g 1 floor in
        let () = print_newline () in
        f floors
  in

  f floors

let rec fold tree f acc =
  match tree with
  | Empty -> acc
  | Node { atom; _ } ->
      let rec g atom acc =
        let acc = fold atom.left_child f acc in
        let acc = f atom.value acc in
        match atom.right_link with
        | Sibling { atom; _ } -> g atom acc
        | Child tree -> fold tree f acc
      in
      g atom acc

let traverse tree f = fold tree f ()

type excess = ExcessZero | ExcessOne

let tree_size tree = match tree with Empty -> 0 | Node node -> node.size

let make_sized atom =
  let size =
    tree_size atom.left_child + 1
    +
    match atom.right_link with
    | Sibling sibling -> sibling.size
    | Child child -> tree_size child
  in
  { atom; size }

(* The index of the first element is zero *)
let rec get_nth tree n =
  match tree with
  | Empty -> failwith "Out of bounds"
  | Node { atom = node; _ } -> (
      let b = tree_size node.left_child in
      if n < b then get_nth node.left_child n
      else if n = b then node.value
      else
        let n = n - b - 1 in
        match node.right_link with
        | Sibling sibling -> get_nth (Node sibling) n
        | Child tree -> get_nth tree n)

let raise_left_child node =
  match node.left_child with
  | Empty -> assert false
  | Node { atom = new_node; _ } ->
      let rec f atom =
        match atom.right_link with
        | Child child ->
            let new_sibling = make_sized { node with left_child = child } in
            make_sized { atom with right_link = Sibling new_sibling }
        | Sibling sibling ->
            make_sized { atom with right_link = Sibling (f sibling.atom) }
      in
      f new_node

let rec width { atom = node; _ } =
  match node.right_link with
  | Sibling sibling -> width sibling + 1
  | Child _ -> 1

let lower_first_atoms atom size =
  let rec f atom size =
    if size = 0 then (atom, Child atom.atom.left_child)
    else
      match atom.atom.right_link with
      | Child _ -> assert false
      | Sibling sibling ->
          let root, right_link = f sibling (size - 1) in
          (root, Sibling (make_sized { atom.atom with right_link }))
  in
  let root, link = f atom size in
  match link with
  | Child _ -> assert false
  | Sibling node -> make_sized { root.atom with left_child = Node node }

let rec unflatten_list node child_sizes =
  match child_sizes with
  | [] -> assert false
  | n :: s ->
      let toplevel_node = lower_first_atoms node n in
      let link =
        match toplevel_node.atom.right_link with
        | Child _ -> assert false
        | Sibling sibling -> (
            match s with
            | [] -> Child (Node sibling)
            | _ -> Sibling (unflatten_list sibling s))
      in
      make_sized { toplevel_node.atom with right_link = link }

let make_higher_if_necessary wide_node =
  let w = width wide_node in
  match w with
  | 1 | 2 -> (wide_node, ExcessZero)
  | 3 | 4 -> (unflatten_list wide_node [ 1 ], ExcessOne)
  | _ -> assert false

let rec insert_in_node value { atom = node; _ } =
  let rec g atom =
    if value <= atom.value then
      let new_node, excess = insert_full value atom.left_child in
      let atom = { atom with left_child = Node new_node } in
      match excess with
      | ExcessZero -> make_sized atom
      | ExcessOne -> raise_left_child atom
    else
      match atom.right_link with
      | Sibling sibling ->
          make_sized { atom with right_link = Sibling (g sibling.atom) }
      | Child right_child -> (
          let new_node, excess = insert_full value right_child in
          match excess with
          | ExcessZero ->
              make_sized { atom with right_link = Child (Node new_node) }
          | ExcessOne -> make_sized { atom with right_link = Sibling new_node })
  in
  let possibly_too_wide = g node in
  make_higher_if_necessary possibly_too_wide

and insert_full value tree =
  match tree with
  | Empty ->
      ( make_sized { value; left_child = Empty; right_link = Child Empty },
        ExcessOne )
  | Node node -> insert_in_node value node

let insert value tree =
  let t, _ = insert_full value tree in
  Node t

type deficit = DeficitZero | DeficitOne

let rec expand node =
  let new_sibling =
    match node.right_link with
    | Child (Node new_sibling) -> new_sibling
    | Child Empty -> assert false
    | Sibling sibling -> expand sibling.atom
  in
  (* Does not change the size because it's the same subtree on the
     right, its status might just change from right child to sibling. *)
  let center = { node with right_link = Sibling new_sibling } in
  raise_left_child center

let expand_except_left_child node =
  let sibling =
    match node.right_link with
    | Sibling sibling -> expand sibling.atom
    | Child (Node new_sibling) -> new_sibling
    | Child Empty -> assert false
  in
  make_sized { node with right_link = Sibling sibling }

let make_higher_if_possible node =
  let w = width node in
  match w with
  | 2 -> (node, DeficitOne)
  | _ ->
      let child_sizes =
        match w with
        | 3 | 4 -> [ 1 ]
        | 5 -> [ 2 ]
        | 6 | 7 -> [ 2; 1 ]
        | _ -> assert false
      in
      (unflatten_list node child_sizes, DeficitZero)

let handle_left_deficit node =
  let atom = expand_except_left_child node in
  make_higher_if_possible atom

let handle_right_deficit node =
  let atom = raise_left_child node in
  make_higher_if_possible atom

let rec extract_min_full node =
  match node.left_child with
  | Empty -> (
      match node.right_link with
      | Sibling sibling -> (Node sibling, DeficitZero, node.value)
      | Child Empty -> (Empty, DeficitOne, node.value)
      | _ -> assert false)
  | Node left_node ->
      let new_child, deficit, min = extract_min_full left_node.atom in
      (* `make_sized` is not necessary I think. *)
      let node = make_sized { node with left_child = new_child } in
      let node, deficit =
        match deficit with
        | DeficitZero -> (node, DeficitZero)
        | DeficitOne -> handle_left_deficit node.atom
      in
      (Node node, deficit, min)

let extract_min tree =
  match tree with
  | Empty -> failwith "Called extract_min on a empty tree"
  | Node node ->
      let tree, _, min = extract_min_full node.atom in
      (tree, min)

let update_right_with_deficit node f =
  let right =
    match node.right_link with Sibling node -> Node node | Child tree -> tree
  in
  let tree, deficit = f right in
  let tree, deficit =
    match (tree, deficit, node.right_link) with
    | Node sibling, DeficitZero, Sibling _ ->
        (make_sized { node with right_link = Sibling sibling }, DeficitZero)
    | Empty, DeficitZero, Sibling _ -> assert false
    | tree, DeficitOne, Sibling _ | tree, DeficitZero, Child _ ->
        (make_sized { node with right_link = Child tree }, DeficitZero)
    | tree, DeficitOne, Child _ ->
        let unbalanced_node = { node with right_link = Child tree } in
        handle_right_deficit unbalanced_node
  in

  (tree, deficit)

let delete_atom node =
  match node.right_link with
  | Sibling right | Child (Node right) ->
      let tree, deficit, min = extract_min_full right.atom in
      let link, deficit =
        match (tree, deficit, node.right_link) with
        | Empty, DeficitZero, _ -> assert false
        | Node new_node, DeficitZero, Sibling _ ->
            (Sibling new_node, DeficitZero)
        | tree, DeficitOne, Sibling _ | tree, DeficitZero, Child _ ->
            (Child tree, DeficitZero)
        | tree, DeficitOne, Child _ -> (Child tree, DeficitOne)
      in
      let node = { node with value = min; right_link = link } in
      let node, deficit =
        match deficit with
        | DeficitZero -> (make_sized node, DeficitZero)
        | DeficitOne -> handle_right_deficit node
      in
      (Node node, deficit)
  | Child Empty -> (node.left_child, DeficitOne)

let rec delete_full value tree =
  match tree with
  | Empty -> (Empty, DeficitZero)
  | Node node -> delete_in_node value node

and delete_in_node value node =
  if value < node.atom.value then
    let tree, deficit = delete_full value node.atom.left_child in
    let node = { node.atom with left_child = tree } in
    let node, deficit =
      match deficit with
      | DeficitZero -> (make_sized node, DeficitZero)
      | DeficitOne -> handle_left_deficit node
    in
    (Node node, deficit)
  else if value = node.atom.value then delete_atom node.atom
  else
    let f = delete_full value in
    let node, deficit = update_right_with_deficit node.atom f in
    (Node node, deficit)

let delete value tree =
  let tree, _ = delete_full value tree in
  tree

let get_num () =
  let rec f acc =
    try
      let c = input_byte stdin in
      if int_of_char '0' <= c && c <= int_of_char '9' then
        f ((acc * 10) + c - int_of_char '0')
      else if acc > 0 then Some acc
      else f 0
    with End_of_file -> if acc > 0 then Some acc else None
  in
  f 0

let get_num () = match get_num () with Some x -> x | None -> exit 1
let max_value = 1000000000

let rec print_list list = match list with
| [] -> ()
| x::[] -> let () = print_int x in print_newline ()
| x::list -> let () = print_int x in let () = print_char ' ' in print_list list

let solve_case () =
  let n = get_num () in
  let k = get_num () in

  let ans =
    let a0 = get_num () in
    let a1 = get_num () in

    let rest, search_tree =
      let rec f i =
        if i >= n then ([], Empty)
        else
          let x = get_num () in
          let rest, search_tree = f (i + 1) in
          (x :: rest, insert (2 * x) search_tree)
      in
      f 2
    in
    if k = n then max_value
    else
      let search_tree = insert a0 search_tree in
      let search_tree = insert a1 search_tree in

      let get_candidate tree = get_nth tree k in

      let ans = get_candidate search_tree in

      let rec f ans tree a0 a1 rest =
        match rest with
        | [] -> ans
        | x :: rest ->
            let search_tree = delete a0 search_tree in
            let search_tree = insert (2 * a0) search_tree in
            let search_tree = delete (2 * x) search_tree in
            let search_tree = insert x search_tree in
            let cand = get_candidate search_tree in
            let ans =
              if ans < cand then
                cand
              else ans
            in
            f ans search_tree a1 x rest
      in
      f ans search_tree a0 a1 rest
  in
  let ans = if max_value < ans then max_value else ans in
  print_int ans

let run () =
  let t = get_num () in
  let rec f i =
    if i = 0 then ()
    else
      let () = solve_case () in
      let () = print_newline () in
      (f [@tailcall]) (i - 1)
  in
  f t

let () = run ()

type right_link = Sibling of sized_atom | Child of tree
and atom = { value : int; left_child : tree; right_link : right_link }
and tree = Empty | Node of sized_atom
and sized_atom = { atom : atom; size : int }

let print_tree tree =
  let rec build_floors floors tree rank =
    match tree with
    | Empty -> (floors, rank)
    | Node { atom = node; _ } ->
        let top, below =
          match floors with top :: below -> (top, below) | _ -> ([], [])
        in
        let rec f below atom rank top =
          let below, rank = build_floors below atom.left_child rank in
          let top = (atom.value, rank) :: top in
          let rank = rank + 1 in
          match atom.right_link with
          | Sibling { atom = sibling; _ } -> f below sibling rank top
          | Child child ->
              let below, rank = build_floors below child rank in
              (below, rank, top)
        in
        let below, rank, top = f below node rank top in
        (top :: below, rank)
  in
  let floors, _ = build_floors [] tree 1 in
  let rec f floors =
    match floors with
    | [] -> ()
    | floor :: floors ->
        let floor = List.rev floor in
        let rec g i floor =
          match floor with
          | [] -> ()
          | (value, rank) :: remainder ->
              let (), floor =
                if rank = i then (print_int value, remainder)
                else (print_char ' ', floor)
              in
              g (i + 1) floor
        in
        let () = g 1 floor in
        let () = print_newline () in
        f floors
  in

  f floors

let rec fold tree f acc =
  match tree with
  | Empty -> acc
  | Node { atom; _ } ->
      let rec g atom acc =
        let acc = fold atom.left_child f acc in
        let acc = f atom.value acc in
        match atom.right_link with
        | Sibling { atom; _ } -> g atom acc
        | Child tree -> fold tree f acc
      in
      g atom acc

let traverse tree f = fold tree f ()

type excess = ExcessZero | ExcessOne

let tree_size tree = match tree with Empty -> 0 | Node node -> node.size

let make_sized atom =
  let size =
    tree_size atom.left_child + 1
    +
    match atom.right_link with
    | Sibling sibling -> sibling.size
    | Child child -> tree_size child
  in
  { atom; size }

(* The index of the first element is zero *)
let rec get_nth tree n =
  match tree with
  | Empty -> failwith "Out of bounds"
  | Node { atom = node; _ } -> (
      let b = tree_size node.left_child in
      if n < b then get_nth node.left_child n
      else if n = b then node.value
      else
        let n = n - b - 1 in
        match node.right_link with
        | Sibling sibling -> get_nth (Node sibling) n
        | Child tree -> get_nth tree n)

let raise_left_child node =
  match node.left_child with
  | Empty -> assert false
  | Node { atom = new_node; _ } ->
      let rec f atom =
        match atom.right_link with
        | Child child ->
            let new_sibling = make_sized { node with left_child = child } in
            make_sized { atom with right_link = Sibling new_sibling }
        | Sibling sibling ->
            make_sized { atom with right_link = Sibling (f sibling.atom) }
      in
      f new_node

let rec width { atom = node; _ } =
  match node.right_link with
  | Sibling sibling -> width sibling + 1
  | Child _ -> 1

let lower_first_atoms atom size =
  let rec f atom size =
    if size = 0 then (atom, Child atom.atom.left_child)
    else
      match atom.atom.right_link with
      | Child _ -> assert false
      | Sibling sibling ->
          let root, right_link = f sibling (size - 1) in
          (root, Sibling (make_sized { atom.atom with right_link }))
  in
  let root, link = f atom size in
  match link with
  | Child _ -> assert false
  | Sibling node -> make_sized { root.atom with left_child = Node node }

let rec unflatten_list node child_sizes =
  match child_sizes with
  | [] -> assert false
  | n :: s ->
      let toplevel_node = lower_first_atoms node n in
      let link =
        match toplevel_node.atom.right_link with
        | Child _ -> assert false
        | Sibling sibling -> (
            match s with
            | [] -> Child (Node sibling)
            | _ -> Sibling (unflatten_list sibling s))
      in
      make_sized { toplevel_node.atom with right_link = link }

let make_higher_if_necessary wide_node =
  let w = width wide_node in
  match w with
  | 1 | 2 -> (wide_node, ExcessZero)
  | 3 | 4 -> (unflatten_list wide_node [ 1 ], ExcessOne)
  | _ -> assert false

let rec insert_in_node value { atom = node; _ } =
  let rec g atom =
    if value <= atom.value then
      let new_node, excess = insert_full value atom.left_child in
      let atom = { atom with left_child = Node new_node } in
      match excess with
      | ExcessZero -> make_sized atom
      | ExcessOne -> raise_left_child atom
    else
      match atom.right_link with
      | Sibling sibling ->
          make_sized { atom with right_link = Sibling (g sibling.atom) }
      | Child right_child -> (
          let new_node, excess = insert_full value right_child in
          match excess with
          | ExcessZero ->
              make_sized { atom with right_link = Child (Node new_node) }
          | ExcessOne -> make_sized { atom with right_link = Sibling new_node })
  in
  let possibly_too_wide = g node in
  make_higher_if_necessary possibly_too_wide

and insert_full value tree =
  match tree with
  | Empty ->
      ( make_sized { value; left_child = Empty; right_link = Child Empty },
        ExcessOne )
  | Node node -> insert_in_node value node

let insert value tree =
  let t, _ = insert_full value tree in
  Node t

type deficit = DeficitZero | DeficitOne

let rec expand node =
  let new_sibling =
    match node.right_link with
    | Child (Node new_sibling) -> new_sibling
    | Child Empty -> assert false
    | Sibling sibling -> expand sibling.atom
  in
  (* Does not change the size because it's the same subtree on the
     right, its status might just change from right child to sibling. *)
  let center = { node with right_link = Sibling new_sibling } in
  raise_left_child center

let expand_except_left_child node =
  let sibling =
    match node.right_link with
    | Sibling sibling -> expand sibling.atom
    | Child (Node new_sibling) -> new_sibling
    | Child Empty -> assert false
  in
  make_sized { node with right_link = Sibling sibling }

let make_higher_if_possible node =
  let w = width node in
  match w with
  | 2 -> (node, DeficitOne)
  | _ ->
      let child_sizes =
        match w with
        | 3 | 4 -> [ 1 ]
        | 5 -> [ 2 ]
        | 6 | 7 -> [ 2; 1 ]
        | _ -> assert false
      in
      (unflatten_list node child_sizes, DeficitZero)

let handle_left_deficit node =
  let atom = expand_except_left_child node in
  make_higher_if_possible atom

let handle_right_deficit node =
  let atom = raise_left_child node in
  make_higher_if_possible atom

let rec extract_min_full node =
  match node.left_child with
  | Empty -> (
      match node.right_link with
      | Sibling sibling -> (Node sibling, DeficitZero, node.value)
      | Child Empty -> (Empty, DeficitOne, node.value)
      | _ -> assert false)
  | Node left_node ->
      let new_child, deficit, min = extract_min_full left_node.atom in
      (* `make_sized` is not necessary I think. *)
      let node = make_sized { node with left_child = new_child } in
      let node, deficit =
        match deficit with
        | DeficitZero -> (node, DeficitZero)
        | DeficitOne -> handle_left_deficit node.atom
      in
      (Node node, deficit, min)

let extract_min tree =
  match tree with
  | Empty -> failwith "Called extract_min on a empty tree"
  | Node node ->
      let tree, _, min = extract_min_full node.atom in
      (tree, min)

let update_right_with_deficit node f =
  let right =
    match node.right_link with Sibling node -> Node node | Child tree -> tree
  in
  let tree, deficit = f right in
  let tree, deficit =
    match (tree, deficit, node.right_link) with
    | Node sibling, DeficitZero, Sibling _ ->
        (make_sized { node with right_link = Sibling sibling }, DeficitZero)
    | Empty, DeficitZero, Sibling _ -> assert false
    | tree, DeficitOne, Sibling _ | tree, DeficitZero, Child _ ->
        (make_sized { node with right_link = Child tree }, DeficitZero)
    | tree, DeficitOne, Child _ ->
        let unbalanced_node = { node with right_link = Child tree } in
        handle_right_deficit unbalanced_node
  in

  (tree, deficit)

let delete_atom node =
  match node.right_link with
  | Sibling right | Child (Node right) ->
      let tree, deficit, min = extract_min_full right.atom in
      let link, deficit =
        match (tree, deficit, node.right_link) with
        | Empty, DeficitZero, _ -> assert false
        | Node new_node, DeficitZero, Sibling _ ->
            (Sibling new_node, DeficitZero)
        | tree, DeficitOne, Sibling _ | tree, DeficitZero, Child _ ->
            (Child tree, DeficitZero)
        | tree, DeficitOne, Child _ -> (Child tree, DeficitOne)
      in
      let node = { node with value = min; right_link = link } in
      let node, deficit =
        match deficit with
        | DeficitZero -> (make_sized node, DeficitZero)
        | DeficitOne -> handle_right_deficit node
      in
      (Node node, deficit)
  | Child Empty -> (node.left_child, DeficitOne)

let rec delete_full value tree =
  match tree with
  | Empty -> (Empty, DeficitZero)
  | Node node -> delete_in_node value node

and delete_in_node value node =
  if value < node.atom.value then
    let tree, deficit = delete_full value node.atom.left_child in
    let node = { node.atom with left_child = tree } in
    let node, deficit =
      match deficit with
      | DeficitZero -> (make_sized node, DeficitZero)
      | DeficitOne -> handle_left_deficit node
    in
    (Node node, deficit)
  else if value = node.atom.value then delete_atom node.atom
  else
    let f = delete_full value in
    let node, deficit = update_right_with_deficit node.atom f in
    (Node node, deficit)

let delete value tree =
  let tree, _ = delete_full value tree in
  tree

let get_num () =
  let rec f acc =
    try
      let c = input_byte stdin in
      if int_of_char '0' <= c && c <= int_of_char '9' then
        f ((acc * 10) + c - int_of_char '0')
      else if acc > 0 then Some acc
      else f 0
    with End_of_file -> if acc > 0 then Some acc else None
  in
  f 0

let get_num () = match get_num () with Some x -> x | None -> exit 1
let max_value = 1000000000

let solve_case () =
  let n = get_num () in
  let k = get_num () in

  let ans =
    let a0 = get_num () in
    let a1 = get_num () in

    let rest, search_tree =
      let rec f i =
        if i >= n then ([], Empty)
        else
          let rest, search_tree = f (i + 1) in
          let x = get_num () in
          (x :: rest, insert (2 * x) search_tree)
      in
      f 2
    in
    if k = n then max_value
    else
      let search_tree = insert a0 search_tree in
      let search_tree = insert a1 search_tree in

      let get_candidate tree = get_nth tree k in

      let ans = get_candidate search_tree in

      let rec f ans tree a0 a1 rest =
        match rest with
        | [] -> ans
        | x :: rest ->
            let search_tree = delete a0 search_tree in
            let search_tree = insert (2 * a0) search_tree in
            let search_tree = delete (2 * x) search_tree in
            let search_tree = insert x search_tree in
            let cand = get_candidate search_tree in
            let ans = if ans < cand then cand else ans in
            f ans search_tree a1 x rest
      in
      f ans search_tree a0 a1 rest
  in
  let ans = if max_value < ans then max_value else ans in
  print_int ans

let run () =
  let t = get_num () in
  let rec f i =
    if i = 0 then ()
    else
      let () = solve_case () in
      let () = print_newline () in
      (f [@tailcall]) (i - 1)
  in
  f t

let () = run ()


You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times:   Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$;  Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$;  Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$).

Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it.

let read_x x_of_string () = read_line () |> Str.(split (regexp " ")) |> List.map x_of_string;;
let read_ints = read_x int_of_string;;
let read_int64s = read_x Int64.of_string;;
let print_x string_of_x xs = List.map string_of_x xs |> String.concat " " |> print_endline;;
let print_ints = print_x string_of_int;;
let print_int64s = print_x Int64.to_string;;

let rec solve n =
  1 +
    let open Int64 in
    if rem n 2L = 0L then
      solve (div n 2L)
    else if rem n 3L = 0L then
      solve (mul 2L (div n 3L))
    else if rem n 5L = 0L then
      solve (mul 4L (div n 5L))
    else if n = 1L then
      -1
    else
      raise Not_found;;

let [q] = read_ints ();;
for _ = 1 to q do
  let [n] = read_int64s () in
  print_ints [try solve n with Not_found -> -1]
done;;


There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (there is no neutral state).You hate love triangles (A-B are in love and B-C are in love, but A-C hate each other), and you also hate it when nobody is in love. So, considering any three characters, you will be happy if exactly one pair is in love (A and B love each other, and C hates both A and B), or if all three pairs are in love (A loves B, B loves C, C loves A).You are given a list of m known relationships in the anime. You know for sure that certain pairs love each other, and certain pairs hate each other. You're wondering how many ways you can fill in the remaining relationships so you are happy with every triangle. Two ways are considered different if two characters are in love in one way but hate each other in the other. Print this count modulo 1 000 000 007.

The first line of input will contain two integers n, m (3 ≤ n ≤ 100 000, 0 ≤ m ≤ 100 000). The next m lines will contain the description of the known relationships. The i-th line will contain three integers ai, bi, ci. If ci is 1, then ai and bi are in love, otherwise, they hate each other (1 ≤ ai, bi ≤ n, ai ≠ bi, ). Each pair of people will be described no more than once.

Print a single integer equal to the number of ways to fill in the remaining pairs so that you are happy with every triangle modulo 1 000 000 007.

NoteIn the first sample, the four ways are to:   Make everyone love each other  Make 1 and 2 love each other, and 3 hate 1 and 2 (symmetrically, we get 3 ways from this). In the second sample, the only possible solution is to make 1 and 3 love each other and 2 and 4 hate each other.

type relat = Love | Hate

let flip = function
  | Love -> (fun x -> x)
  | Hate -> not

let modulus = Int64.of_int 1000000007

let rec modexp2 = function
  | 0 -> Int64.one
  | n when n mod 2 = 0 -> let k = modexp2 (n/2) in Int64.rem (Int64.mul k k) modulus
  | n                  -> let k = modexp2 (n/2) in
                          Int64.rem (Int64.add (Int64.mul k k) (Int64.mul k k)) modulus

let _ =
  let n,m = Scanf.scanf "%d %d " (fun n m -> n,m) in
  let adjl = Array.init n (fun _ -> []) in
  for i = 1 to m do
    Scanf.scanf "%d %d %d " begin fun a b c ->
      adjl.(a-1) <- (b-1, if c = 1 then Love else Hate) :: adjl.(a-1);
      adjl.(b-1) <- (a-1, if c = 1 then Love else Hate) :: adjl.(b-1)
    end
  done;
  let mark = Array.init n (fun _ -> None) in
  let bfs i =
    let q = Queue.create () in
    let visit m j =
      match mark.(j) with
      | Some m' -> if m <> m' then raise Not_found
      | None -> (mark.(j) <- Some m; Queue.push (j, m) q)
    in
    visit true i;
    while not (Queue.is_empty q) do
      let (j, m) = Queue.pop q in
      List.iter (fun (v, rel) -> visit (flip rel m) v) adjl.(j)
    done
  in
  try
    let ctr = ref 0 in
    for i = 0 to n-1 do
      if mark.(i) = None then (bfs i; incr ctr)
    done;
    print_int (Int64.to_int (modexp2 (!ctr - 1)))
  with Not_found -> print_int 0

type relat = Love | Hate

let flip = function
  | Love -> (fun x -> x)
  | Hate -> not

let modulus = 1000000007

let rec modexp2 = function
  | 0 -> 1
  | n when n mod 2 = 0 -> let k = modexp2 (n/2) in (k*k) mod modulus
  | n                  -> let k = modexp2 (n/2) in (2*k*k) mod modulus

let _ =
  let n,m = Scanf.scanf "%d %d " (fun n m -> n,m) in
  let adjl = Array.init n (fun _ -> []) in
  for i = 1 to m do
    Scanf.scanf "%d %d %d " begin fun a b c ->
      adjl.(a-1) <- (b-1, if c = 1 then Love else Hate) :: adjl.(a-1);
      adjl.(b-1) <- (a-1, if c = 1 then Love else Hate) :: adjl.(b-1)
    end
  done;
  let mark = Array.init n (fun _ -> None) in
  let bfs i =
    let q = Queue.create () in
    let visit m j =
      match mark.(j) with
      | Some m' -> if m <> m' then raise Not_found
      | None -> (mark.(j) <- Some m; Queue.push (j, m) q)
    in
    visit true i;
    while not (Queue.is_empty q) do
      let (j, m) = Queue.pop q in
      List.iter (fun (v, rel) -> visit (flip rel m) v) adjl.(j)
    done
  in
  try
    let ctr = ref 0 in
    for i = 0 to n-1 do
      if mark.(i) = None then (bfs i; incr ctr)
    done;
    print_int (modexp2 (!ctr - 1))
  with Not_found -> print_int 0

type relat = Love | Hate

let flip = function
  | Love -> (fun x -> x)
  | Hate -> not

let rec modexp2 = function
  | 0 -> 1
  | n when n mod 2 = 0 -> let k = modexp2 (n/2) in k*k
  | n                  -> let k = modexp2 (n/2) in 2*k*k

let _ =
  let n,m = Scanf.scanf "%d %d " (fun n m -> n,m) in
  let adjl = Array.init n (fun _ -> []) in
  for i = 1 to m do
    Scanf.scanf "%d %d %d " begin fun a b c ->
      adjl.(a-1) <- (b-1, if c = 1 then Love else Hate) :: adjl.(a-1);
      adjl.(b-1) <- (a-1, if c = 1 then Love else Hate) :: adjl.(b-1)
    end
  done;
  let mark = Array.init n (fun _ -> None) in
  let bfs i =
    let q = Queue.create () in
    let visit m j =
      match mark.(j) with
      | Some m' -> if m <> m' then raise Not_found
      | None -> (mark.(j) <- Some m; Queue.push (j, m) q)
    in
    visit true i;
    while not (Queue.is_empty q) do
      let (j, m) = Queue.pop q in
      List.iter (fun (v, rel) -> visit (flip rel m) v) adjl.(j)
    done
  in
  try
    let ctr = ref 0 in
    for i = 0 to n-1 do
      if mark.(i) = None then (bfs i; incr ctr)
    done;
    print_int (modexp2 (!ctr - 1))
  with Not_found -> print_int 0

type relat = Love | Hate

let flip = function
  | Love -> (fun x -> x)
  | Hate -> not

let modulus = 1000000007

let rec modexp2 = function
  | 0 -> 1
  | n when n mod 2 = 0 -> let k = modexp2 (n/2) in (k*k) mod modulus
  | n                  -> let k = modexp2 (n/2) in 2*k*k mod modulus

let _ =
  let n,m = Scanf.scanf "%d %d " (fun n m -> n,m) in
  let adjl = Array.init n (fun _ -> []) in
  for i = 1 to m do
    Scanf.scanf "%d %d %d " begin fun a b c ->
      adjl.(a-1) <- (b-1, if c = 1 then Love else Hate) :: adjl.(a-1);
      adjl.(b-1) <- (a-1, if c = 1 then Love else Hate) :: adjl.(b-1)
    end
  done;
  let mark = Array.init n (fun _ -> None) in
  let bfs i =
    let q = Queue.create () in
    let visit m j =
      match mark.(j) with
      | Some m' -> if m <> m' then raise Not_found
      | None -> (mark.(j) <- Some m; Queue.push (j, m) q)
    in
    visit true i;
    while not (Queue.is_empty q) do
      let (j, m) = Queue.pop q in
      List.iter (fun (v, rel) -> visit (flip rel m) v) adjl.(j)
    done
  in
  try
    let ctr = ref 0 in
    for i = 0 to n-1 do
      if mark.(i) = None then (bfs i; incr ctr)
    done;
    print_int (modexp2 (!ctr - 1))
  with Not_found -> print_int 0


You are given a permutation $$$p$$$ of $$$n$$$ elements. A permutation of $$$n$$$ elements is an array of length $$$n$$$ containing each integer from $$$1$$$ to $$$n$$$ exactly once. For example, $$$[1, 2, 3]$$$ and $$$[4, 3, 5, 1, 2]$$$ are permutations, but $$$[1, 2, 4]$$$ and $$$[4, 3, 2, 1, 2]$$$ are not permutations. You should perform $$$q$$$ queries.There are two types of queries:  $$$1$$$ $$$x$$$ $$$y$$$ — swap $$$p_x$$$ and $$$p_y$$$.  $$$2$$$ $$$i$$$ $$$k$$$ — print the number that $$$i$$$ will become if we assign $$$i = p_i$$$ $$$k$$$ times.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 10^5$$$). The second line contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$. Each of the next $$$q$$$ lines contains three integers. The first integer is $$$t$$$ ($$$1 \le t \le 2$$$) — type of query. If $$$t = 1$$$, then the next two integers are $$$x$$$ and $$$y$$$ ($$$1 \le x, y \le n$$$; $$$x \ne y$$$) — first-type query. If $$$t = 2$$$, then the next two integers are $$$i$$$ and $$$k$$$ ($$$1 \le i, k \le n$$$) — second-type query. It is guaranteed that there is at least one second-type query.

For every second-type query, print one integer in a new line — answer to this query.

NoteIn the first example $$$p = \{5, 3, 4, 2, 1\}$$$. The first query is to print $$$p_3$$$. The answer is $$$4$$$.The second query is to print $$$p_{p_1}$$$. The answer is $$$1$$$.The third query is to swap $$$p_1$$$ and $$$p_3$$$. Now $$$p = \{4, 3, 5, 2, 1\}$$$.The fourth query is to print $$$p_{p_1}$$$. The answer is $$$2$$$.

type node = {
  mutable l:node;
  mutable r:node;
  mutable p:node; (* parent *)
  mutable s:int;  (* size *)
  mutable key:int;
}

let rec null = {l=null; r=null; p=null; s=0; key= -1}

let isroot n = n.p == null

let update x = (* assumes x is non-null *)
  x.s <- 1 + x.l.s + x.r.s

let rot_right p =  (* we know that p is a left child *)
  let q = p.p in
  let r = q.p in
  q.l <- p.r;
  if q.l != null then q.l.p <- q;
  p.r <- q;
  q.p <- p;
  p.p <- r;
  if r != null then (
    if r.l == q then r.l <- p
    else if r.r == q then r.r <- p
  );
  update q (* p and r will be updated later *)

let rot_left p =
  let q = p.p in
  let r = q.p in
  q.r <- p.l;
  if q.r != null then q.r.p <- q;
  p.l <- q;
  q.p <- p;
  p.p <- r;
  if r != null then (
    if r.r == q then r.r <- p
    else if r.l == q then r.l <- p
  );
  update q

let splay p =
  let rec loop p = if not (isroot p) then
      let q = p.p in
      if isroot q then (
	if q.l == p then rot_right p else rot_left p
      ) else (
	let r = q.p in
	if r.l == q then (
	  if q.l == p then (rot_right q; rot_right p)
	  else (rot_left p; rot_right p)
	) else (
	  if q.r == p then (rot_left q; rot_left p)
	  else (rot_right p; rot_left p)
	)
      );
      loop p
  in
  loop p;
  update p

let join x y =
  (* x and y are tree roots. join them with x to the left of y *)
  (* returns the result *)
  if x == null then y else if y == null then x else
      let rec find_rightmost p =
	if p.r == null then p else find_rightmost p.r in
      let z = find_rightmost x in
      splay z;
      z.r <- y;
      y.p <- z;
      update z;
      z

let split x =
(*  return two trees.  The stuff to the left of x,
    and everything from x to the end *)
  splay x;
  let left = x.l in
  if left != null then left.p <- null;
  x.l <- null;
  update x;
  (left,x)

let find_node_of_rank t r =
(* t is a tree root, r is the desired rank.  r=0 is leftmost *)
(* splay the node of the required rank *)
  let rec loop x r =
    if x.l.s = r then x
    else if x.l.s > r then loop x.l r
    else loop x.r (r - x.l.s - 1)
  in
  let root = loop t r in
  splay root;
  root

let rec find_root z old = if isroot z then (z,old)
  else find_root z.p z

open Printf
open Scanf

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

let bound = 1_000_000

let () =
  let (n,q) = read_pair() in
  let node = Array.init n (fun i -> {null with s=1; key=i}) in
  let perm = Array.init n (fun i -> read_int() -1) in
  (* 0 based permutation *)

  (* build the trees based on the initial permutation *)

(*
  let print_cycles () =
    let mark = Array.make n false in
    let rec print_tree r =
      let rec loop r =
	if r == null then () else (
	  print_tree r.l;
	  printf "%d " (1+r.key);
	  mark.(r.key) <- true;
	  print_tree r.r
	)
      in
      loop r;
    in

    for i=0 to n-1 do
      let i = (fst (find_root node.(i) null)).key in
      if not mark.(i) then (
	printf "Tree:";
	print_tree node.(i);
	print_newline()
      )
    done
  in
*)
  let mark = Array.make n false in

  let rec build_tree_for_cycle curr cycle =
    match cycle with [] -> ()
      | h::t ->
	let nxt = node.(h) in
	nxt.l <- curr;
	if curr != null then curr.p <- nxt;
	update nxt;
	build_tree_for_cycle nxt t
  in

  for i=0 to n-1 do
    if not mark.(i) then (
      let rec visit_cycle i ac =
	if mark.(i) then List.rev ac else (
	  mark.(i) <- true;
	  visit_cycle perm.(i) (i::ac)
	)
      in
      let cycle = visit_cycle i [] in
      build_tree_for_cycle null cycle
    )
  done;

  (* the trees are now initialized *)

  let apply_swap_to_trees a b =
    splay a;
    let (b_root,b_below) = find_root b null in
    let a_to_left = a.r == b_below in
    splay b;
    if b_root == a then ( (* same tree *)
(*      printf "same tree\n"; *)
      let (a,b) = if a_to_left then (a,b) else (b,a) in
(*      printf "Now a=%d  b=%d\n" (a.key+1) (b.key+1); *)
      (* now a is to the left of b *)
      let (t1,ax) = split a in
      let (t2,bx) = split b in
      ignore (join t1 bx);
    ) else ( (*diff tree*)
      let (t1,ax) = split a in
      let (t2,bx) = split b in
      ignore (join t1 (join bx (join t2 ax)))
    )
  in

  let apply_scan_to_tree x k =
    splay x;
    let rx = x.l.s in
    let cyclesize = x.s in
    let ry = (rx + k) mod cyclesize in
    let y = find_node_of_rank x ry in
    y.key
  in

(*  print_cycles (); *)

  for query = 0 to q-1 do
    match read_int() with
      | 1 -> (*swap*)
	let (x,y) = read_pair() in
(*	printf "doing swap %d %d\n" x y; *)
	let (x,y) = (x-1,y-1) in
	let (px,py) = (perm.(x),perm.(y)) in
	perm.(x) <- py;
	perm.(y) <- px;
	apply_swap_to_trees node.(px) node.(py)
(*	print_cycles() *)
      | 2 -> (*scan*)
	let (x,k) = read_pair() in
(*	printf "doing scan %d %d\n" x k;	 *)
	let x = x-1 in
	let key = apply_scan_to_tree node.(perm.(x)) (k-1) in
	printf "%d\n" (key+1)
(*	print_cycles() *)
      | _ -> failwith "bad input"
  done;