You have got a shelf and want to put some books on it.You are given $$$q$$$ queries of three types:  L $$$id$$$ — put a book having index $$$id$$$ on the shelf to the left from the leftmost existing book;  R $$$id$$$ — put a book having index $$$id$$$ on the shelf to the right from the rightmost existing book;  ? $$$id$$$ — calculate the minimum number of books you need to pop from the left or from the right in such a way that the book with index $$$id$$$ will be leftmost or rightmost. You can assume that the first book you will put can have any position (it does not matter) and queries of type $$$3$$$ are always valid (it is guaranteed that the book in each such query is already placed). You can also assume that you don't put the same book on the shelf twice, so $$$id$$$s don't repeat in queries of first two types.Your problem is to answer all the queries of type $$$3$$$ in order they appear in the input.Note that after answering the query of type $$$3$$$ all the books remain on the shelf and the relative order of books does not change.If you are Python programmer, consider using PyPy instead of Python when you submit your code.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Then $$$q$$$ lines follow. The $$$i$$$-th line contains the $$$i$$$-th query in format as in the problem statement. It is guaranteed that queries are always valid (for query type $$$3$$$, it is guaranteed that the book in each such query is already placed, and for other types, it is guaranteed that the book was not placed before). It is guaranteed that there is at least one query of type $$$3$$$ in the input. In each query the constraint $$$1 \le id \le 2 \cdot 10^5$$$ is met.

Print answers to queries of the type $$$3$$$ in order they appear in the input.

NoteLet's take a look at the first example and let's consider queries:   The shelf will look like $$$[1]$$$;  The shelf will look like $$$[1, 2]$$$;  The shelf will look like $$$[1, 2, 3]$$$;  The shelf looks like $$$[1, \textbf{2}, 3]$$$ so the answer is $$$1$$$;  The shelf will look like $$$[4, 1, 2, 3]$$$;  The shelf looks like $$$[4, \textbf{1}, 2, 3]$$$ so the answer is $$$1$$$;  The shelf will look like $$$[5, 4, 1, 2, 3]$$$;  The shelf looks like $$$[5, 4, \textbf{1}, 2, 3]$$$ so the answer is $$$2$$$. Let's take a look at the second example and let's consider queries:   The shelf will look like $$$[100]$$$;  The shelf will look like $$$[100, 100000]$$$;  The shelf will look like $$$[100, 100000, 123]$$$;  The shelf will look like $$$[101, 100, 100000, 123]$$$;  The shelf looks like $$$[101, 100, 100000, \textbf{123}]$$$ so the answer is $$$0$$$;  The shelf will look like $$$[10, 101, 100, 100000, 123]$$$;  The shelf will look like $$$[10, 101, 100, 100000, 123, 115]$$$;  The shelf looks like $$$[10, 101, \textbf{100}, 100000, 123, 115]$$$ so the answer is $$$2$$$;  The shelf will look like $$$[10, 101, 100, 100000, 123, 115, 110]$$$;  The shelf looks like $$$[10, 101, 100, 100000, 123, \textbf{115}, 110]$$$ so the answer is $$$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 let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end
module MyInt64 = struct
	let (%$) = (mod) 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 repb 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; !f 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 !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb 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,!f) 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 (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v
	let ceildiv m n = (m+n-1L) / n
	let abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf " %s" (fun v -> v)
	let i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a
	let dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf " %d" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf " %d %d" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y) let repi 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
end open MyInt64

let dl l = l|>Array.of_list|>dump_array

let () =
	let q = get_i64 0 in
	let a = Array.make 200018 `Null in
	let lf,rg = ref 0,ref 0 in
	(* let llf,rrg = ref [], ref [] in *)
	rep 1L q (fun _ ->
		let c,i = scanf " %c %Ld" (fun u v -> u,v) in (
			match c with
			| 'L' ->
				lf := !lf +$ 1;
				(* llf := i :: !llf; printf "left :"; dl !llf; *)
				a.(i32 i) <- `Left (!lf);
			| 'R' ->
				rg := !rg +$ 1;
				(* rrg := i :: !rrg; printf "right:"; dl !rrg; *)
				a.(i32 i) <- `Right (!rg);
			| '?' ->
				let pos = a.(i32 i) in (
					match pos with
					| `Left q -> printf "%d\n" @@ min (!lf -$ q) (!rg+$q-$1)
					| `Right q -> printf "%d\n" @@ min (!rg -$ q) (!lf+$q-$1)
					| _ -> exit 1
				)
			| c -> printf "err: %c\n" c; exit 1;
		);
		`Ok
	)

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 let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end
module MyInt64 = struct
	let (%$) = (mod) 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 repb 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; !f 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 !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb 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,!f) 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 (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v
	let ceildiv m n = (m+n-1L) / n
	let abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf " %s" (fun v -> v)
	let i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a
	let dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf " %d" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf " %d %d" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y) let repi 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
end open MyInt64

let () =
	let q = get_i64 0 in
	let a = Array.make 200018 `Null in
	let lf,rg = ref 0,ref 0 in
	rep 1L q (fun _ ->
		let c,i = scanf " %c %Ld" (fun u v -> u,v) in (
			match c with
			| 'L' ->
				lf := !lf +$ 1;
				a.(i32 i) <- `Left (!lf);
			| 'R' ->
				rg := !rg +$ 1;
				a.(i32 i) <- `Right (!rg);
			| '?' ->
				let pos = a.(i32 i) in (
					match pos with
					| `Left q -> printf "%d\n" (!lf -$ q)
					| `Right q -> printf "%d\n" (!rg -$ q)
					| _ -> exit 0
				)
			| c -> printf "err: %c\n" c; exit 0;
		);
		`Ok
	)

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 let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end
module MyInt64 = struct
	let (%$) = (mod) 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 repb 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; !f 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 !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb 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,!f) 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 (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v
	let ceildiv m n = (m+n-1L) / n
	let abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf " %s" (fun v -> v)
	let i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a
	let dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf " %d" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf " %d %d" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y) let repi 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
end open MyInt64

let dl l = l|>Array.of_list|>dump_array

let () =
	let q = get_i64 0 in
	let a = Array.make 200018 `Null in
	let lf,rg = ref 0,ref 0 in
	(* let llf,rrg = ref [], ref [] in *)
	rep 1L q (fun _ ->
		let c,i = scanf " %c %Ld" (fun u v -> u,v) in (
			match c with
			| 'L' ->
				lf := !lf +$ 1;
				(* llf := i :: !llf; printf "left :"; dl !llf; *)
				a.(i32 i) <- `Left (!lf);
			| 'R' ->
				rg := !rg +$ 1;
				(* rrg := i :: !rrg; printf "right:"; dl !rrg; *)
				a.(i32 i) <- `Right (!rg);
			| '?' ->
				let pos = a.(i32 i) in (
					match pos with
					| `Left q -> printf "%d\n" @@ min (!lf -$ q) (!rg+$q+$1)
					| `Right q -> printf "%d\n" @@ min (!rg -$ q) (!rg+$q+$1)
					| _ -> exit 1
				)
			| c -> printf "err: %c\n" c; exit 1;
		);
		`Ok
	)

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 let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end
module MyInt64 = struct
	let (%$) = (mod) 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 repb 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; !f 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 !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb 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,!f) 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 (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v
	let ceildiv m n = (m+n-1L) / n
	let abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf " %s" (fun v -> v)
	let i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a
	let dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf " %d" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf " %d %d" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y) let repi 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
end open MyInt64

let dl l = l|>Array.of_list|>dump_array

let () =
	let q = get_i64 0 in
	let a = Array.make 200018 `Null in
	let lf,rg = ref 0,ref 0 in
	(* let llf,rrg = ref [], ref [] in *)
	rep 1L q (fun _ ->
		let c,i = scanf " %c %Ld" (fun u v -> u,v) in (
			match c with
			| 'L' ->
				lf := !lf +$ 1;
				(* llf := i :: !llf; printf "left :"; dl !llf; *)
				a.(i32 i) <- `Left (!lf);
			| 'R' ->
				rg := !rg +$ 1;
				(* rrg := i :: !rrg; printf "right:"; dl !rrg; *)
				a.(i32 i) <- `Right (!rg);
			| '?' ->
				let pos = a.(i32 i) in (
					match pos with
					| `Left q -> printf "%d\n" @@ min (!lf -$ q) (!rg+$q-$1)
					| `Right q -> printf "%d\n" @@ min (!rg -$ q) (!rg+$q-$1)
					| _ -> exit 1
				)
			| c -> printf "err: %c\n" c; exit 1;
		);
		`Ok
	)


You are given a permutation $$$p_1, p_2, \ldots, p_n$$$ of length $$$n$$$. You have to choose two integers $$$l,r$$$ ($$$1 \le l \le r \le n$$$) and reverse the subsegment $$$[l,r]$$$ of the permutation. The permutation will become $$$p_1,p_2, \dots, p_{l-1},p_r,p_{r-1}, \dots, p_l,p_{r+1},p_{r+2}, \dots ,p_n$$$.Find the lexicographically smallest permutation that can be obtained by performing exactly one reverse operation on the initial permutation.Note that for two distinct permutations of equal length $$$a$$$ and $$$b$$$, $$$a$$$ is lexicographically smaller than $$$b$$$ if at the first position they differ, $$$a$$$ has the smaller element.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 500$$$) — the length of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$) — the elements of the permutation.

For each test case print the lexicographically smallest permutation you can obtain.

NoteIn the first test case, the permutation has length $$$1$$$, so the only possible segment is $$$[1,1]$$$. The resulting permutation is $$$[1]$$$.In the second test case, we can obtain the identity permutation by reversing the segment $$$[1,2]$$$. The resulting permutation is $$$[1,2,3]$$$.In the third test case, the best possible segment is $$$[2,3]$$$. The resulting permutation is $$$[1,2,4,3]$$$.In the fourth test case, there is no lexicographically smaller permutation, so we can leave it unchanged by choosing the segment $$$[1,1]$$$. The resulting permutation is $$$[1,2,3,4,5]$$$.

let find x t = let rep = ref 0 in
  for i = 0 to Array.length t -1 do
    if t.(i) = x then rep:=i ;
  done ;
  !rep ;;

let inverse s n1 n2 = let rep = ref "" in
  let pile = Stack.create () in
  for i = 0 to Array.length s -1 do
    let popo = if i = Array.length s -1 then "" else " " in
    if i<n1 || i>n2 then (rep := (!rep)^(string_of_int s.(i)^popo))
    else (
      if i = n2 then (Stack.push s.(i) pile ; for j = n1 to n2 -1 do rep := (!rep)^(string_of_int (Stack.pop pile))^" ";done; rep:=(!rep)^(string_of_int (Stack.pop pile))^popo)
      else (Stack.push s.(i) pile ) )
  done ; !rep ;;

let to_t s len = let t = Array.make len 0 in
  let temp = ref "" in
  let inc = ref 0 in
  for i = 0 to String.length s -1 do
    if s.[i] = ' ' then (t.(!inc)<- int_of_string (!temp); incr inc ; temp:= "" )else
      temp := !temp^(String.make 1 (s.[i])) done ; t.(!inc)<- int_of_string (!temp); t;;

let n = int_of_string(input_line stdin) in

for i = 0 to n-1 do
  let len = int_of_string(input_line stdin) in
  let str = (input_line stdin) in
  let t = to_t str len in
  let finito = ref false in
  let interest = ref (-1,-1) in
  for j = 0 to Array.length t -1  do
    if not(!finito) && (t.(j))<>j+1 then
      (interest := (j,find (j+1) t) ;
       finito := true)
  done ;
  let rety = if !interest <> (-1,-1) then
      (let a,b = !interest in inverse t a b )
    else str in
  print_endline rety
done;
;;

(* Codeforces 1638 A Reverse train *)

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

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

let rec extract_smallest_start i first l = match l with
    | [] -> (i, [])
    | h :: t ->
        if h == i then extract_smallest_start (i+1) (h :: first) t
        else
        (i, l);;

let rec get_until_a a part l = match l with
    | [] -> (part, l)
    | h :: t ->
        if h == a then (a :: part, t)
                  else get_until_a a (h :: part) t;;

let rec generater n = if n==0 then [] else n :: generater (n-1);;
let generate n = List.rev (generater n);;

let do_one () =
    let n = gr () in
    let p = readlist n [] in
    let nfirst, pl = extract_smallest_start 1 [] p in
    (*let _ = Printf.printf "nfirst = %d\n" nfirst in
    let _ = Printf.printf "pl: %s\n" (list_to_s pl) in*)
    let pend = if List.length pl == 0 then []
        else
            ( let revpart, pla = get_until_a nfirst [] pl in
            (List.append revpart pla)) in
    let lret = List.append (generate (nfirst-1)) pend in
    (printlisti lret; print_string "\n");;

let do_all () =
    let t = gr () in
    for i = 1 to t do
        do_one ()
    done;;

let main() =
	do_all ();;

main();;

let find x s = let rep = ref 0 in
  for i = 0 to String.length s -1 do
    if s.[i] = (string_of_int(x)).[0] then rep:=i ;
  done ;
  !rep ;;

let inverse s n1 n2 = let rep = ref "" in
  let pile = Stack.create () in
  for i = 0 to String.length s -1 do
    if i<n1 || i>n2 then (rep := (!rep)^(String.make 1 (s.[i])))
    else (
      if i = n2 then (Stack.push (String.make 1 (s.[i])) pile ; for j = n1 to n2 do rep := (!rep)^(Stack.pop pile);done;)
      else (
        (String.make 1 (s.[i])) ;  Stack.push (String.make 1 (s.[i])) pile ))
  done ; !rep ;;

let n = int_of_string(input_line stdin) in

for i = 0 to n-1 do
  let len = int_of_string(input_line stdin) in
  let str = (input_line stdin) in
  let finito = ref false in
  let interest = ref (-1,-1) in
  for j = 0 to String.length str -1  do
    if str.[j] <> ' ' && not(!finito) && str.[j]<>(string_of_int (j/2 +1)).[0] then
      (prerr_endline (string_of_int j);
       interest := (j,find (j/2 +1) str) ;
       finito := true)
  done ;
  let rety = if !interest <> (-1,-1) then
      (let a,b = !interest in inverse str a b )
    else str in
  print_endline rety
done;
;;


There is a light source on the plane. This source is so small that it can be represented as point. The light source is moving from point $$$(a, s_y)$$$ to the $$$(b, s_y)$$$ $$$(s_y < 0)$$$ with speed equal to $$$1$$$ unit per second. The trajectory of this light source is a straight segment connecting these two points. There is also a fence on $$$OX$$$ axis represented as $$$n$$$ segments $$$(l_i, r_i)$$$ (so the actual coordinates of endpoints of each segment are $$$(l_i, 0)$$$ and $$$(r_i, 0)$$$). The point $$$(x, y)$$$ is in the shade if segment connecting $$$(x,y)$$$ and the current position of the light source intersects or touches with any segment of the fence.  You are given $$$q$$$ points. For each point calculate total time of this point being in the shade, while the light source is moving from $$$(a, s_y)$$$ to the $$$(b, s_y)$$$.

First line contains three space separated integers $$$s_y$$$, $$$a$$$ and $$$b$$$ ($$$-10^9 \le s_y < 0$$$, $$$1 \le a < b \le 10^9$$$) — corresponding coordinates of the light source. Second line contains single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — number of segments in the fence. Next $$$n$$$ lines contain two integers per line: $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i < r_i \le 10^9$$$, $$$r_{i - 1} < l_i$$$) — segments in the fence in increasing order. Segments don't intersect or touch each other. Next line contains single integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — number of points to check. Next $$$q$$$ lines contain two integers per line: $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le 10^9$$$) — points to process.

Print $$$q$$$ lines. The $$$i$$$-th line should contain one real number — total time of the $$$i$$$-th point being in the shade, while the light source is moving from $$$(a, s_y)$$$ to the $$$(b, s_y)$$$. The answer is considered as correct if its absolute of relative error doesn't exceed $$$10^{-6}$$$.

Note  The 1-st point is always in the shade;  the 2-nd point is in the shade while light source is moving from $$$(3, -3)$$$ to $$$(6, -3)$$$;  the 3-rd point is in the shade while light source is at point $$$(6, -3)$$$.  the 4-th point is in the shade while light source is moving from $$$(1, -3)$$$ to $$$(2.5, -3)$$$ and at point $$$(6, -3)$$$;  the 5-th point is in the shade while light source is moving from $$$(1, -3)$$$ to $$$(2.5, -3)$$$ and from $$$(5.5, -3)$$$ to $$$(6, -3)$$$;

let _ =
  let sb = Scanf.Scanning.stdib in
  let sy = Scanf.bscanf sb "%f " (fun s -> s) in
  let a = Scanf.bscanf sb "%f " (fun s -> s) in
  let b = Scanf.bscanf sb "%f " (fun s -> s) in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let f = Array.make n (0.0, 0.0) in
  let _ =
    for i = 0 to n - 1 do
      let l = Scanf.bscanf sb "%f " (fun s -> s) in
      let r = Scanf.bscanf sb "%f " (fun s -> s) in
	f.(i) <- (l, r)
    done;
  in
  let s = Array.make (n + 1) 0.0 in
  let _ =
    for i = 0 to n - 1 do
      s.(i + 1) <- s.(i) +. snd f.(i) -. fst f.(i)
    done;
  in
  let q = Scanf.bscanf sb "%d " (fun s -> s) in
    for i = 1 to q do
      let x = Scanf.bscanf sb "%f " (fun s -> s) in
      let y = Scanf.bscanf sb "%f " (fun s -> s) in
      let x1 = (sy *. x -. a *. y) /. (sy -. y) in
      let x2 = (sy *. x -. b *. y) /. (sy -. y) in
      let idx1 =
	let l = ref (-1) in
	let r = ref n in
	  while !l < !r - 1 do
	    let m = (!l + !r) / 2 in
	      if fst f.(m) <= x1
	      then l := m
	      else r := m
	  done;
	  !l
      in
      let idx2 =
	let l = ref (-1) in
	let r = ref n in
	  while !l < !r - 1 do
	    let m = (!l + !r) / 2 in
	      if fst f.(m) <= x2
	      then l := m
	      else r := m
	  done;
	  !l
      in
      let g = s.(idx2 + 1) -. s.(idx1 + 1) in
      let g =
	if idx1 >= 0 && x1 <= snd f.(idx1)
	then g +. snd f.(idx1) -. x1
	else g
      in
      let g =
	if idx2 >= 0 && x2 <= snd f.(idx2)
	then g -. (snd f.(idx2) -. x2)
	else g
      in
	(*Printf.printf "asd %f %f  %d %d  %f\n" x1 x2 idx1 idx2 g;*)
	Printf.printf "%.15f\n" (g /. (x2 -. x1) *. (b -. a))
    done


One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.Your task is to write a program that will determine the required number of seconds t.

The first input line contains a single integer n — the number of cupboards in the kitchen (2 ≤ n ≤ 104). Then follow n lines, each containing two integers li and ri (0 ≤ li, ri ≤ 1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces.

In the only output line print a single integer t — the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs.

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

let () =
  let n = read_int() in
  let c = Array.make 2 0 in
    for i=0 to n-1 do
      let l = read_int() in
      let r = read_int() in
	if l=0 then c.(0) <- c.(0) + 1;
	if r=0 then c.(1) <- c.(1) + 1;
    done;
    let left = min c.(0) (n-c.(0)) in
    let right = min c.(1) (n-c.(1)) in
      Printf.printf "%d\n" (left+right)


IT City administration has no rest because of the fame of the Pyramids in Egypt. There is a project of construction of pyramid complex near the city in the place called Emerald Walley. The distinction of the complex is that its pyramids will be not only quadrangular as in Egypt but also triangular and pentagonal. Of course the amount of the city budget funds for the construction depends on the pyramids' volume. Your task is to calculate the volume of the pilot project consisting of three pyramids — one triangular, one quadrangular and one pentagonal.The first pyramid has equilateral triangle as its base, and all 6 edges of the pyramid have equal length. The second pyramid has a square as its base and all 8 edges of the pyramid have equal length. The third pyramid has a regular pentagon as its base and all 10 edges of the pyramid have equal length.

The only line of the input contains three integers l3, l4, l5 (1 ≤ l3, l4, l5 ≤ 1000) — the edge lengths of triangular, quadrangular and pentagonal pyramids correspondingly.

Output one number — the total volume of the pyramids. Absolute or relative error should not be greater than 10 - 9.

let _ =
  let sb = Scanf.Scanning.stdib in
  let l3 = Scanf.bscanf sb "%f " (fun s -> s) in
  let l4 = Scanf.bscanf sb "%f " (fun s -> s) in
  let l5 = Scanf.bscanf sb "%f " (fun s -> s) in
  let pi = 4.0 *. atan 1.0 in
  let sqr x = x *. x in
  let solve l n =
    let n = float_of_int n in
    let alpha = pi /. n in
    let d = l /. 2.0 /. tan alpha in
    let e = l *. sqrt 3.0 /. 2.0 in
    let h = sqrt (sqr e -. sqr d) in
    let s = n *. d *. l /. 2.0 in
    let v = h *. s /. 3.0 in
      v
  in
  let res = solve l3 3 +. solve l4 4 +. solve l5 5 in
    Printf.printf "%.9f\n" res


Autumn came late to the kingdom of Far Far Away. The harvest was exuberant and it is now time to get ready for the winter. As most people celebrate the Harvest festival, Simon the Caretaker tries to solve a very non-trivial task of how to find place for the agricultural equipment in the warehouse.He's got problems with some particularly large piece of equipment, which is, of course, turboplows. The problem is that when a turboplow is stored, it takes up not some simply rectangular space. It takes up a T-shaped space like on one of the four pictures below (here character "#" stands for the space occupied by the turboplow and character "." stands for the free space):   ###      ..#      .#.      #...#.      ###      .#.      ###.#.      ..#      ###      #..   Simon faced a quite natural challenge: placing in the given n × m cells warehouse the maximum number of turboplows. As one stores the turboplows, he can rotate them in any manner (so that they take up the space like on one of the four pictures above). However, two turboplows cannot "overlap", that is, they cannot share the same cell in the warehouse.Simon feels that he alone cannot find the optimal way of positioning the plugs in the warehouse that would maximize their quantity. Can you help him?

The only line contains two space-separated integers n and m — the sizes of the warehouse (1 ≤ n, m ≤ 9).

In the first line print the maximum number of turboplows that can be positioned in the warehouse. In each of the next n lines print m characters. Use "." (dot) to mark empty space and use successive capital Latin letters ("A" for the first turboplow, "B" for the second one and so on until you reach the number of turboplows in your scheme) to mark place for the corresponding turboplows considering that they are positioned in the optimal manner in the warehouse. The order in which you number places for the turboplows does not matter. If there are several optimal solutions for a warehouse of the given size, print any of them.

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make_matrix n m (-1) in
  let b = Array.make_matrix n m (-1) in
  let res = ref 0 in
  let pred = ref 10 in
  let rec bf x y k =
    (*Printf.printf "asd %d %d  %d\n" x y k;
    for i = 0 to n - 1 do
      for j = 0 to m - 1 do
	Printf.printf "%d " a.(i).(j)
      done;
      Printf.printf "\n"
    done;*)
    let x = ref x in
    let y = ref y in
      while !x < n && a.(!x).(!y) >= 0 do
	incr x
      done;
    (*Printf.printf "qwe %d %d  %d\n" !x !y k;
    for i = 0 to n - 1 do
      for j = 0 to m - 1 do
	Printf.printf "%d " a.(i).(j)
      done;
      Printf.printf "\n"
    done;*)
      if !x = n then (
	if !y < m - 1 then (
	  x := 0;
	  incr y;
	  bf !x !y k;
	) else (
	  if !res < k then (
	    res := k;
	    for i = 0 to n - 1 do
	      for j = 0 to m - 1 do
		b.(i).(j) <- a.(i).(j)
	      done
	    done;
	    if !res >= !pred then raise Not_found
	  )
	)
      ) else (
	let x = !x
	and y = !y in
	  if x <= n - 3 && y <= m - 3 &&
	    a.(x).(y + 1) < 0 &&
	    a.(x).(y + 2) < 0 &&
	    a.(x + 1).(y + 1) < 0 &&
	    a.(x + 2).(y + 1) < 0
	  then (
	    a.(x).(y) <- k;
	    a.(x).(y + 1) <- k;
	    a.(x).(y + 2) <- k;
	    a.(x + 1).(y + 1) <- k;
	    a.(x + 2).(y + 1) <- k;
	    bf x y (k + 1);
	    a.(x).(y) <- -1;
	    a.(x).(y + 1) <- -1;
	    a.(x).(y + 2) <- -1;
	    a.(x + 1).(y + 1) <- -1;
	    a.(x + 2).(y + 1) <- -1;
	  );
	  if 1 <= x && x <= n - 2 && y <= m - 3 &&
	    a.(x).(y + 1) < 0 &&
	    a.(x).(y + 2) < 0 &&
	    a.(x + 1).(y + 2) < 0 &&
	    a.(x - 1).(y + 2) < 0
	  then (
	    a.(x).(y) <- k;
	    a.(x).(y + 1) <- k;
	    a.(x).(y + 2) <- k;
	    a.(x + 1).(y + 2) <- k;
	    a.(x - 1).(y + 2) <- k;
	    bf x y (k + 1);
	    a.(x).(y) <- -1;
	    a.(x).(y + 1) <- -1;
	    a.(x).(y + 2) <- -1;
	    a.(x + 1).(y + 2) <- -1;
	    a.(x - 1).(y + 2) <- -1;
	  );
	  if 2 <= x && x <= n - 1 && y <= m - 3 &&
	    a.(x).(y + 1) < 0 &&
	    a.(x).(y + 2) < 0 &&
	    a.(x - 1).(y + 1) < 0 &&
	    a.(x - 2).(y + 1) < 0
	  then (
	    a.(x).(y) <- k;
	    a.(x).(y + 1) <- k;
	    a.(x).(y + 2) <- k;
	    a.(x - 1).(y + 1) <- k;
	    a.(x - 2).(y + 1) <- k;
	    bf x y (k + 1);
	    a.(x).(y) <- -1;
	    a.(x).(y + 1) <- -1;
	    a.(x).(y + 2) <- -1;
	    a.(x - 1).(y + 1) <- -1;
	    a.(x - 2).(y + 1) <- -1;
	  );
	  if x <= n - 3 && y <= m - 3 &&
	    a.(x + 1).(y) < 0 &&
	    a.(x + 2).(y) < 0 &&
	    a.(x + 1).(y + 1) < 0 &&
	    a.(x + 1).(y + 2) < 0
	  then (
	    a.(x).(y) <- k;
	    a.(x + 1).(y) <- k;
	    a.(x + 2).(y) <- k;
	    a.(x + 1).(y + 1) <- k;
	    a.(x + 1).(y + 2) <- k;
	    bf x y (k + 1);
	    a.(x).(y) <- -1;
	    a.(x + 1).(y) <- -1;
	    a.(x + 2).(y) <- -1;
	    a.(x + 1).(y + 1) <- -1;
	    a.(x + 1).(y + 2) <- -1;
	  );
	  bf (x + 1) y k;
      )
  in
    (match n, m with
       | 9, 9 -> pred := 13
       | 8, 9 -> pred := 12
       | 9, 8 -> pred := 12
       | 8, 8 -> pred := 10
       | 7, 9 -> pred := 10
       | 9, 7 -> pred := 10
       | 7, 8 -> pred := 9
       | 8, 7 -> pred := 9
       | _ -> ()
    );
    (try bf 0 0 0 with Not_found -> ());
    Printf.printf "%d\n" !res;
    for i = 0 to n - 1 do
      for j = 0 to m - 1 do
	let v = b.(i).(j) in
	let c =
	  if v < 0
	  then '.'
	  else Char.chr (Char.code 'A' + v)
	in
	  Printf.printf "%c" c
      done;
      Printf.printf "\n"
    done

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

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

let (h,w) = (n+1,m+1)

let wall = -2
let hole = -1
let empty = 0

let a = Array.make (h*w) wall
let () =
  for i=0 to n-1 do for j=0 to m-1 do
    a.(w*i+j) <- empty
  done done

let p = Array.make 4 [||]
let () =
  p.(0) <- [|w;w+1;w+2;2*w|];
  p.(1) <- [|1;2;w+1;2*w+1|];
  p.(2) <- [|w-2;w-1;w;2*w|];
  p.(3) <- [|w;2*w-1;2*w;2*w+1|]

let rec backtrack i blanks =  (* i is the first empty space, blanks is the # of blanks left *)
  if i=h*w then true else if a.(i) != empty then backtrack (i+1) blanks else
    let rec trypiece q = if q=4 then (
      if blanks=0 then false else (
	a.(i) <- hole;
	if backtrack (i+1) (blanks-1) then true else (
	  a.(i) <- empty;
	  false
	)
      )
    ) else (
      let rec fit j = if j=4 then true else a.(i+p.(q).(j)) = 0 && (fit (j+1)) in
      let rec fill j x = if j=4 then a.(i) <- x else (
	a.(i+p.(q).(j)) <- x;
	fill (j+1) x
      )
      in
	if not (fit 0) then trypiece (q+1) else (
	  fill 0 (i+1);
	  if backtrack (i+1) blanks then true else (
	    fill 0 empty;
	    trypiece (q+1)
	  )
	)
    )
    in
      trypiece 0

let rec tryblanks b = if backtrack 0 b then b else tryblanks (b+5)

let () =
  let blanks = tryblanks (n*m mod 5) in
  let lab = Array.make (h*w) (-1) in
  let rec labels i c = if i=h*w then () else (
    if a.(i)=hole || a.(i)=wall || lab.(a.(i)) >= 0 then labels (i+1) c else (
      lab.(a.(i)) <- c;
      labels (i+1) (c+1)
    )
  )
  in
    Printf.printf "%d\n" (((n*m)-blanks)/5);
    labels 0 0;
    for i=0 to n-1 do
      for j=0 to m-1 do
	let c = if a.(w*i+j) = hole then '.' else char_of_int ((int_of_char 'A') + lab.(a.(w*i+j))) in
	  print_char c
      done;
      print_newline ()
    done

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let n = min n m
  and m = max n m in
  let a = Array.make_matrix n m (-1) in
  let b = Array.make_matrix n m (-1) in
  let res = ref 0 in
  let pred = ref 10 in
  let rec bf x y k =
    (*Printf.printf "asd %d %d  %d\n" x y k;
    for i = 0 to n - 1 do
      for j = 0 to m - 1 do
	Printf.printf "%d " a.(i).(j)
      done;
      Printf.printf "\n"
    done;*)
    let x = ref x in
    let y = ref y in
      while !x < n && a.(!x).(!y) >= 0 do
	incr x
      done;
    (*Printf.printf "qwe %d %d  %d\n" !x !y k;
    for i = 0 to n - 1 do
      for j = 0 to m - 1 do
	Printf.printf "%d " a.(i).(j)
      done;
      Printf.printf "\n"
    done;*)
      if !x = n then (
	if !y < m - 1 then (
	  x := 0;
	  incr y;
	  bf !x !y k;
	) else (
	  if !res < k then (
	    res := k;
	    for i = 0 to n - 1 do
	      for j = 0 to m - 1 do
		b.(i).(j) <- a.(i).(j)
	      done
	    done;
	    if !res >= !pred then raise Not_found
	  )
	)
      ) else (
	let x = !x
	and y = !y in
	  if x <= n - 3 && y <= m - 3 &&
	    a.(x).(y + 1) < 0 &&
	    a.(x).(y + 2) < 0 &&
	    a.(x + 1).(y + 1) < 0 &&
	    a.(x + 2).(y + 1) < 0
	  then (
	    a.(x).(y) <- k;
	    a.(x).(y + 1) <- k;
	    a.(x).(y + 2) <- k;
	    a.(x + 1).(y + 1) <- k;
	    a.(x + 2).(y + 1) <- k;
	    bf x y (k + 1);
	    a.(x).(y) <- -1;
	    a.(x).(y + 1) <- -1;
	    a.(x).(y + 2) <- -1;
	    a.(x + 1).(y + 1) <- -1;
	    a.(x + 2).(y + 1) <- -1;
	  );
	  if 1 <= x && x <= n - 2 && y <= m - 3 &&
	    a.(x).(y + 1) < 0 &&
	    a.(x).(y + 2) < 0 &&
	    a.(x + 1).(y + 2) < 0 &&
	    a.(x - 1).(y + 2) < 0
	  then (
	    a.(x).(y) <- k;
	    a.(x).(y + 1) <- k;
	    a.(x).(y + 2) <- k;
	    a.(x + 1).(y + 2) <- k;
	    a.(x - 1).(y + 2) <- k;
	    bf x y (k + 1);
	    a.(x).(y) <- -1;
	    a.(x).(y + 1) <- -1;
	    a.(x).(y + 2) <- -1;
	    a.(x + 1).(y + 2) <- -1;
	    a.(x - 1).(y + 2) <- -1;
	  );
	  if 2 <= x && x <= n - 1 && y <= m - 3 &&
	    a.(x).(y + 1) < 0 &&
	    a.(x).(y + 2) < 0 &&
	    a.(x - 1).(y + 1) < 0 &&
	    a.(x - 2).(y + 1) < 0
	  then (
	    a.(x).(y) <- k;
	    a.(x).(y + 1) <- k;
	    a.(x).(y + 2) <- k;
	    a.(x - 1).(y + 1) <- k;
	    a.(x - 2).(y + 1) <- k;
	    bf x y (k + 1);
	    a.(x).(y) <- -1;
	    a.(x).(y + 1) <- -1;
	    a.(x).(y + 2) <- -1;
	    a.(x - 1).(y + 1) <- -1;
	    a.(x - 2).(y + 1) <- -1;
	  );
	  if x <= n - 3 && y <= m - 3 &&
	    a.(x + 1).(y) < 0 &&
	    a.(x + 2).(y) < 0 &&
	    a.(x + 1).(y + 1) < 0 &&
	    a.(x + 1).(y + 2) < 0
	  then (
	    a.(x).(y) <- k;
	    a.(x + 1).(y) <- k;
	    a.(x + 2).(y) <- k;
	    a.(x + 1).(y + 1) <- k;
	    a.(x + 1).(y + 2) <- k;
	    bf x y (k + 1);
	    a.(x).(y) <- -1;
	    a.(x + 1).(y) <- -1;
	    a.(x + 2).(y) <- -1;
	    a.(x + 1).(y + 1) <- -1;
	    a.(x + 1).(y + 2) <- -1;
	  );
	  bf (x + 1) y k;
      )
  in
    (match n, m with
       | 9, 9 -> pred := 13
       | 8, 9 -> pred := 12
       | 8, 8 -> pred := 10
       | 7, 9 -> pred := 10
       | 7, 8 -> pred := 9
       | _ -> ()
    );
    (try bf 0 0 0 with Not_found -> ());
    Printf.printf "%d\n" !res;
    for i = 0 to n - 1 do
      for j = 0 to m - 1 do
	let v = b.(i).(j) in
	let c =
	  if v < 0
	  then '.'
	  else Char.chr (Char.code 'A' + v)
	in
	  Printf.printf "%c" c
      done;
      Printf.printf "\n"
    done

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let n = min n m
  and m = max n m in
  let a = Array.make_matrix n m (-1) in
  let b = Array.make_matrix n m (-1) in
  let res = ref 0 in
  let pred = ref 10 in
  let rec bf x y k =
    (*Printf.printf "asd %d %d  %d\n" x y k;
    for i = 0 to n - 1 do
      for j = 0 to m - 1 do
	Printf.printf "%d " a.(i).(j)
      done;
      Printf.printf "\n"
    done;*)
    let x = ref x in
    let y = ref y in
      while !x < n && a.(!x).(!y) >= 0 do
	incr x
      done;
    (*Printf.printf "qwe %d %d  %d\n" !x !y k;
    for i = 0 to n - 1 do
      for j = 0 to m - 1 do
	Printf.printf "%d " a.(i).(j)
      done;
      Printf.printf "\n"
    done;*)
      if !x = n then (
	if !y < m - 1 then (
	  x := 0;
	  incr y;
	  bf !x !y k;
	) else (
	  if !res < k then (
	    res := k;
	    for i = 0 to n - 1 do
	      for j = 0 to m - 1 do
		b.(i).(j) <- a.(i).(j)
	      done
	    done;
	    if !res >= !pred then raise Not_found
	  )
	)
      ) else (
	let x = !x
	and y = !y in
	  if x <= n - 3 && y <= m - 3 &&
	    a.(x).(y + 1) < 0 &&
	    a.(x).(y + 2) < 0 &&
	    a.(x + 1).(y + 1) < 0 &&
	    a.(x + 2).(y + 1) < 0
	  then (
	    a.(x).(y) <- k;
	    a.(x).(y + 1) <- k;
	    a.(x).(y + 2) <- k;
	    a.(x + 1).(y + 1) <- k;
	    a.(x + 2).(y + 1) <- k;
	    bf x y (k + 1);
	    a.(x).(y) <- -1;
	    a.(x).(y + 1) <- -1;
	    a.(x).(y + 2) <- -1;
	    a.(x + 1).(y + 1) <- -1;
	    a.(x + 2).(y + 1) <- -1;
	  );
	  if 1 <= x && x <= n - 2 && y <= m - 3 &&
	    a.(x).(y + 1) < 0 &&
	    a.(x).(y + 2) < 0 &&
	    a.(x + 1).(y + 2) < 0 &&
	    a.(x - 1).(y + 2) < 0
	  then (
	    a.(x).(y) <- k;
	    a.(x).(y + 1) <- k;
	    a.(x).(y + 2) <- k;
	    a.(x + 1).(y + 2) <- k;
	    a.(x - 1).(y + 2) <- k;
	    bf x y (k + 1);
	    a.(x).(y) <- -1;
	    a.(x).(y + 1) <- -1;
	    a.(x).(y + 2) <- -1;
	    a.(x + 1).(y + 2) <- -1;
	    a.(x - 1).(y + 2) <- -1;
	  );
	  if 2 <= x && x <= n - 1 && y <= m - 3 &&
	    a.(x).(y + 1) < 0 &&
	    a.(x).(y + 2) < 0 &&
	    a.(x - 1).(y + 1) < 0 &&
	    a.(x - 2).(y + 1) < 0
	  then (
	    a.(x).(y) <- k;
	    a.(x).(y + 1) <- k;
	    a.(x).(y + 2) <- k;
	    a.(x - 1).(y + 1) <- k;
	    a.(x - 2).(y + 1) <- k;
	    bf x y (k + 1);
	    a.(x).(y) <- -1;
	    a.(x).(y + 1) <- -1;
	    a.(x).(y + 2) <- -1;
	    a.(x - 1).(y + 1) <- -1;
	    a.(x - 2).(y + 1) <- -1;
	  );
	  if x <= n - 3 && y <= m - 3 &&
	    a.(x + 1).(y) < 0 &&
	    a.(x + 2).(y) < 0 &&
	    a.(x + 1).(y + 1) < 0 &&
	    a.(x + 1).(y + 2) < 0
	  then (
	    a.(x).(y) <- k;
	    a.(x + 1).(y) <- k;
	    a.(x + 2).(y) <- k;
	    a.(x + 1).(y + 1) <- k;
	    a.(x + 1).(y + 2) <- k;
	    bf x y (k + 1);
	    a.(x).(y) <- -1;
	    a.(x + 1).(y) <- -1;
	    a.(x + 2).(y) <- -1;
	    a.(x + 1).(y + 1) <- -1;
	    a.(x + 1).(y + 2) <- -1;
	  );
	  bf (x + 1) y k;
      )
  in
    (match n, m with
       | 9, 9 -> pred := 13
       | 8, 9 -> pred := 12
       | 7, 9 -> pred := 10
       | 7, 8 -> pred := 9
       | _ -> ()
    );
    (try bf 0 0 0 with Not_found -> ());
    Printf.printf "%d\n" !res;
    for i = 0 to n - 1 do
      for j = 0 to m - 1 do
	let v = b.(i).(j) in
	let c =
	  if v < 0
	  then '.'
	  else Char.chr (Char.code 'A' + v)
	in
	  Printf.printf "%c" c
      done;
      Printf.printf "\n"
    done


The Zoo in the Grid Kingdom is represented by an infinite grid. The Zoo has n observation binoculars located at the OX axis. For each i between 1 and n, inclusive, there exists a single binocular located at the point with coordinates (i, 0). There are m flamingos in the Zoo, located at points with positive coordinates. The flamingos are currently sleeping and you can assume that they don't move.In order to get a good view over the flamingos, each of the binoculars can be independently rotated to face any angle (not necessarily integer). Then, the binocular can be used to observe all flamingos that is located at the straight line passing through the binocular at the angle it is set. In other words, you can assign each binocular a direction corresponding to any straight line passing through the binocular, and the binocular will be able to see all flamingos located on that line.Today, some kids from the prestigious Codeforces kindergarten went on a Field Study to the Zoo. Their teacher would like to set each binocular an angle to maximize the number of flamingos that can be seen by the binocular. The teacher is very interested in the sum of these values over all binoculars. Please help him find this sum.

The first line contains two space-separated integers n and m (1 ≤ n ≤ 106, 1 ≤ m ≤ 250), denoting the number of binoculars and the number of flamingos, respectively. Then m lines follow, the i-th line will contain two space-separated integers xi and yi (1 ≤ xi, yi ≤ 109), which means that the i-th flamingo is located at point (xi, yi).  All flamingos will be located at distinct points.

Print a single integer denoting the maximum total number of flamingos that can be seen by all the binoculars.

NoteThis picture shows the answer to the example test case.

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let x = Array.make m 0 in
  let y = Array.make m 0 in
  let () =
    for i = 0 to m - 1 do
      x.(i) <- Scanf.bscanf sb "%d " (fun s -> s);
      y.(i) <- Scanf.bscanf sb "%d " (fun s -> s);
    done;
  in
  let area x y x1 y1 x2 y2 =
    Int64.sub
      (Int64.mul (Int64.of_int (x1 - x))
	 (Int64.of_int (y2 - y)))
      (Int64.mul (Int64.of_int (x2 - x))
	 (Int64.of_int (y1 - y)))
  in
  let check x1 y1 x2 y2 =
    let x1 = Int64.of_int x1 in
    let y1 = Int64.of_int y1 in
    let x2 = Int64.of_int x2 in
    let y2 = Int64.of_int y2 in
    let a = Int64.sub (Int64.mul x2 y1) (Int64.mul x1 y2) in
    let b = Int64.sub y1 y2 in
      if Int64.rem a b = 0L
      then Some (Int64.div a b)
      else None
  in
  let a = Array.make (n + 1) 1 in
    for i = 0 to m - 1 do
      for j = i + 1 to m - 1 do
	if y.(i) <> y.(j) then (
	  match check x.(i) y.(i) x.(j) y.(j) with
	    | Some x' ->
		if x' > 0L && x' <= Int64.of_int n then (
		  let x' = Int64.to_int x' in
		  let c = ref 2 in
		    for k = 0 to m - 1 do
		      if k <> i && k <> j &&
			area x.(i) y.(i) x.(j) y.(j) x.(k) y.(k) = 0L
		      then incr c
		    done;
		    a.(x') <- max a.(x') !c
		)
	    | None -> ()
	)
      done
    done;
    let res = ref 0 in
      for i = 1 to n do
	res := !res + a.(i)
      done;
      Printf.printf "%d\n" !res


You are given a positive integer $$$n$$$.The weight of a permutation $$$p_1, p_2, \ldots, p_n$$$ is the number of indices $$$1\le i\le n$$$ such that $$$i$$$ divides $$$p_i$$$. Find a permutation $$$p_1,p_2,\dots, p_n$$$ with the minimum possible weight (among all permutations of length $$$n$$$).A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). The description of the test cases follows. The only line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a line containing $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ so that the permutation $$$p$$$ has the minimum possible weight. If there are several possible answers, you can print any of them.

NoteIn the first test case, the only valid permutation is $$$p=[1]$$$. Its weight is $$$1$$$.In the second test case, one possible answer is the permutation $$$p=[2,1,4,3]$$$. One can check that $$$1$$$ divides $$$p_1$$$ and $$$i$$$ does not divide $$$p_i$$$ for $$$i=2,3,4$$$, so the weight of this permutation is $$$1$$$. It is impossible to find a permutation of length $$$4$$$ with a strictly smaller weight.

open Printf
open Scanf

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let () =
  let cases = read_int () in
  for case = 1 to cases do
    let n = read_int() in
    for i=0 to n-1 do
      printf "%d " (if i = 0 then n else i)
    done;
    print_newline()
  done


Burenka and Tonya are playing an old Buryat game with a chip on a board of $$$n \times m$$$ cells.At the beginning of the game, the chip is located in the lower left corner of the board. In one move, the player can move the chip to the right or up by any odd number of cells (but you cannot move the chip both to the right and up in one move). The one who cannot make a move loses.Burenka makes the first move, the players take turns. Burenka really wants to win the game, but she is too lazy to come up with a strategy, so you are invited to solve the difficult task of finding it. Name the winner of the game (it is believed that Burenka and Tonya are masters of playing with chips, so they always move in the optimal way).    Chip's starting cell is green, the only cell from which chip can't move is red. if the chip is in the yellow cell, then blue cells are all options to move the chip in one move.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The following is a description of the input data sets. The only line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^9$$$) — the dimensions of the game board.

For each test case print a single line — the name of the winner of the game ("Burenka" or "Tonya").

Tonya
Burenka
Burenka
Tonya
Burenka
Burenka

NoteIn the first case, Burenka has no move, so Tonya wins.In the second case, Burenka can move $$$3$$$ cells to the right, after which Tony will not be able to make a move, which means that Burenka wins.In the third case, Burenka can move $$$5$$$ squares to the right. Then we can say that we have a game on a board of $$$1 \times 5$$$ cells, and Tonya is the first player. In such game the second player wins, so in the original one Burenka will win.

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

let () =
  let t = read_int () in
  for _ = 1 to t do
    let n = read_int () in
    let m = read_int () in
    if (n + m) mod 2 = 0 then
      Printf.printf "Tonya\n"
    else
      Printf.printf "Burenka\n"
  done;

(* 2n+1, 1 then second player wins
since 1st moves 2a-1, 2nd moves 2(n-a)+1, leaving 1,1 for first.

2n,1 then first player wins since first moves 2n-1
which leaves second with 1,1

2n,2m then 2x+1,2m so second player wins.
2n+1,2m then first moves 2m-1 leaving 2n+1,1 and that means
first player wins as second player must go first in this grid type.

2n+1,2m+1 then first player moves 2a-1 in either direction so
second should move in that direction s.t 1,2m+1 or 2n+1,1 which means they win as the player that
needs to go seconds in the config wins.
*)

let read_long () = Scanf.scanf " %Ld" (fun l-> l);;
let read_int () = Scanf.scanf " %d" (fun x-> x);;
let run_case = function
| () ->
     let n = read_long () in
     let m = read_long () in
     let nrem = Int64.sub n (Int64.mul (Int64.div n 2L) 2L) in
     let mrem = Int64.sub m (Int64.mul (Int64.div m 2L) 2L) in
     if ((nrem=0L)&&(mrem=0L)) then print_string "Tonya"
     else if ((nrem=0L)||(mrem=0L)) then print_string "Burenka"
     else print_string "Tonya"
;;

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

let t=read_int () in iter_cases t;;


There are $$$n$$$ children numbered from $$$1$$$ to $$$n$$$ in a kindergarten. Kindergarten teacher gave $$$a_i$$$ ($$$1 \leq a_i \leq n$$$) candies to the $$$i$$$-th child. Children were seated in a row in order from $$$1$$$ to $$$n$$$ from left to right and started eating candies. While the $$$i$$$-th child was eating candies, he calculated two numbers $$$l_i$$$ and $$$r_i$$$ — the number of children seating to the left of him that got more candies than he and the number of children seating to the right of him that got more candies than he, respectively.Formally, $$$l_i$$$ is the number of indices $$$j$$$ ($$$1 \leq j < i$$$), such that $$$a_i < a_j$$$ and $$$r_i$$$ is the number of indices $$$j$$$ ($$$i < j \leq n$$$), such that $$$a_i < a_j$$$.Each child told to the kindergarten teacher the numbers $$$l_i$$$ and $$$r_i$$$ that he calculated. Unfortunately, she forgot how many candies she has given to each child. So, she asks you for help: given the arrays $$$l$$$ and $$$r$$$ determine whether she could have given the candies to the children such that all children correctly calculated their values $$$l_i$$$ and $$$r_i$$$, or some of them have definitely made a mistake. If it was possible, find any way how she could have done it.

On the first line there is a single integer $$$n$$$ ($$$1 \leq n \leq 1000$$$) — the number of children in the kindergarten. On the next line there are $$$n$$$ integers $$$l_1, l_2, \ldots, l_n$$$ ($$$0 \leq l_i \leq n$$$), separated by spaces. On the next line, there are $$$n$$$ integer numbers $$$r_1, r_2, \ldots, r_n$$$ ($$$0 \leq r_i \leq n$$$), separated by spaces.

If there is no way to distribute the candies to the children so that all of them calculated their numbers correctly, print «NO» (without quotes). Otherwise, print «YES» (without quotes) on the first line. On the next line, print $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$, separated by spaces — the numbers of candies the children $$$1, 2, \ldots, n$$$ received, respectively. Note that some of these numbers can be equal, but all numbers should satisfy the condition $$$1 \leq a_i \leq n$$$. The number of children seating to the left of the $$$i$$$-th child that got more candies than he should be equal to $$$l_i$$$ and the number of children seating to the right of the $$$i$$$-th child that got more candies than he should be equal to $$$r_i$$$. If there is more than one solution, find any of them.

NoteIn the first example, if the teacher distributed $$$1$$$, $$$3$$$, $$$1$$$, $$$2$$$, $$$1$$$ candies to $$$1$$$-st, $$$2$$$-nd, $$$3$$$-rd, $$$4$$$-th, $$$5$$$-th child, respectively, then all the values calculated by the children are correct. For example, the $$$5$$$-th child was given $$$1$$$ candy, to the left of him $$$2$$$ children were given $$$1$$$ candy, $$$1$$$ child was given $$$2$$$ candies and $$$1$$$ child — $$$3$$$ candies, so there are $$$2$$$ children to the left of him that were given more candies than him.In the second example it is impossible to distribute the candies, because the $$$4$$$-th child made a mistake in calculating the value of $$$r_4$$$, because there are no children to the right of him, so $$$r_4$$$ should be equal to $$$0$$$.In the last example all children may have got the same number of candies, that's why all the numbers are $$$0$$$. Note that each child should receive at least one candy.

let split_on_char sep s =
  let r = ref [] in
  let j = ref (String.length s) in
  for i = String.length s - 1 downto 0 do
    if String.unsafe_get s i = sep then (
      r := String.sub s (i + 1) (!j - i - 1) :: !r ;
      j := i )
  done ;
  String.sub s 0 !j :: !r

let insert s i a n x =
  let min = ref 0 and max = ref (n+1) in
  while !max - !min > 0 do
    if x < a.((!max + !min) / 2) then max := (!max + !min) / 2
    else min := ((!max + !min) / 2) + 1;
  done ;
  for i = n downto !min do
    a.(i + 1) <- a.(i)
  done ;
  a.(!min) <- x ;
  s.(i) <- n + 1 - !min

;;
let n = Scanf.sscanf (read_line ()) "%i" (fun n -> n) in
let l = Array.make n 0 in
split_on_char ' ' (read_line ())
|> List.iteri (fun i x -> l.(i) <- int_of_string x) ;
let r = Array.make n 0 in
split_on_char ' ' (read_line ())
|> List.iteri (fun i x -> r.(i) <- int_of_string x) ;
let total = Array.init n (fun i -> (l.(i) + r.(i), i + 1)) in
Array.fast_sort compare total ;
let current = ref n in
let bonbon = ref 0 in
let sol = Array.make n 0 in
for i = n - 1 downto 0 do
  if !current > fst total.(i) then (
    current := fst total.(i) ;
    incr bonbon ) ;
  sol.(snd total.(i) - 1) <- !bonbon
done ;
let sl = Array.make n 0 in
let al = Array.make n sol.(0) in
let sr = Array.make n 0 in
let ar = Array.make n sol.(n - 1) in
for i = 1 to n - 1 do
  insert sl i al (i - 1) sol.(i) ;
  insert sr (n - 1 - i) ar (i - 1) sol.(n - 1 - i);
done ;
if sl = l && sr = r then (
  print_endline "YES" ;
  Array.iter (Printf.printf "%i ") sol )
else print_string "NO" ;
print_newline ()


The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction.At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north.You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate.

The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters. The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second.

Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road.  Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if  holds.

NoteIn the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds.

let read_array n = let a = Array.make n 0 in
  for i = 0 to (n - 1) do
    Scanf.scanf " %d" (fun x -> a.(i) <- x)
  done;
  a

let best_time pos spd =
  let n = Array.length pos in
  let max_x = float_of_int (Array.fold_left max min_int pos) in
  let min_v = float_of_int (Array.fold_left min max_int spd) in
  let merge (a, b) (c, d) = (max a c, min b d) in
  let feasible_time t =
    let range = ref (neg_infinity, infinity) in
    for i = 0 to (n-1) do
      let (x, dx) = (float_of_int pos.(i), float_of_int spd.(i) *. t) in
      range := merge !range (x -. dx, x +. dx)
    done;
    let (a, b) = !range in a <= b
  in
  let rec find lo hi it =
    if (hi -. lo) < epsilon_float || it >= 64
    then lo
    else
      let m = lo +. (hi -. lo) /. 2. in
      if feasible_time m
      then find lo m (it + 1)
      else find (m +. epsilon_float) hi (it + 1)
  in
  find 0.0 (max_x /. min_v) 0

let () =
  let n = Scanf.scanf "%d" (fun x -> x) in
  let pos = read_array n in
  let spd = read_array n in
  Printf.printf "%10.12f\n" (best_time pos spd)

open Printf
open Scanf

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

let () =
  let n = read_int () in
  let x = Array.init n read_float in
  let v = Array.init n read_float in

  let intersect (lo1,hi1) (lo2,hi2) = (max lo1 lo2, min hi1 hi2) in
  let no_overlap (lo,hi) = lo > hi in

  let overlap_interval t =
  (* given time t, if they overlap return Some (lo,hi) else None *)
    let rec loop oldinterval i =
      if i=n then Some oldinterval else
	let my_hi = x.(i) +. t *. v.(i) in
	let my_lo = x.(i) -. t *. v.(i) in
	let newinterval = if i=0 then (my_lo,my_hi) else intersect (my_lo,my_hi) oldinterval in
	if no_overlap newinterval then None else loop newinterval (i+1)
    in
    loop (0.0, 0.0) 0
  in

  let rec bsearch lo_t hi_t count =  (* hi has overlap, lo has no overlap *)
    if count = 50 then hi_t else
      let m = (lo_t +. hi_t) /. 2.0 in
      match overlap_interval m with
	| None -> bsearch m hi_t (count+1)
	| Some _ -> bsearch lo_t m (count+1)
  in

  let rec find_hi t = match overlap_interval t with None -> find_hi (2.0 *. t) | Some _ -> t in

  let answer = match overlap_interval 0.0 with Some _ -> 0.0
    | None -> bsearch 0.0 (find_hi 1.0) 0
  in

  printf "%.10f\n" answer

open Printf
open Scanf

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

let () =
  let n = read_int () in
  let x = Array.init n read_float in
  let v = Array.init n read_float in

  let intersect (lo1,hi1) (lo2,hi2) = (max lo1 lo2, min hi1 hi2) in
  let no_overlap (lo,hi) = lo > hi in

  let overlap_interval t =
  (* given time t, if they overlap return Some (lo,hi) else None *)
    let rec loop oldinterval i =
      if i=n then Some oldinterval else
	let my_hi = x.(i) +. t *. v.(i) in
	let my_lo = x.(i) -. t *. v.(i) in
	let newinterval = if i=0 then (my_lo,my_hi) else intersect (my_lo,my_hi) oldinterval in
	if no_overlap newinterval then None else loop newinterval (i+1)
    in
    loop (0.0, 0.0) 0
  in

  let rec bsearch lo_t hi_t count =  (* hi has overlap, lo has no overlap *)
    if count = 50 then hi_t else
      let m = (lo_t +. hi_t) /. 2.0 in
      match overlap_interval m with
	| None -> bsearch m hi_t (count+1)
	| Some _ -> bsearch lo_t m (count+1)
  in

  let rec find_hi t = match overlap_interval t with None -> find_hi (2.0 *. t) | Some _ -> t in

  let answer = match overlap_interval 0.0 with Some (lo,hi) -> lo | None ->
    bsearch 0.0 (find_hi 1.0) 0
  in

  printf "%.10f\n" answer


Vanya wants to pass n exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least avg. The exam grade cannot exceed r. Vanya has passed the exams and got grade ai for the i-th exam. To increase the grade for the i-th exam by 1 point, Vanya must write bi essays. He can raise the exam grade multiple times.What is the minimum number of essays that Vanya needs to write to get scholarship?

The first line contains three integers n, r, avg (1 ≤ n ≤ 105, 1 ≤ r ≤ 109, 1 ≤ avg ≤ min(r, 106)) — the number of exams, the maximum grade and the required grade point average, respectively. Each of the following n lines contains space-separated integers ai and bi (1 ≤ ai ≤ r, 1 ≤ bi ≤ 106).

In the first line print the minimum number of essays.

NoteIn the first sample Vanya can write 2 essays for the 3rd exam to raise his grade by 2 points and 2 essays for the 4th exam to raise his grade by 1 point.In the second sample, Vanya doesn't need to write any essays as his general point average already is above average.

exception Invalid_input

let (|>) x f = f x

let rec make_list = fun len f ->
  if len = 0 then
    []
  else
    (f ()) :: (make_list (len - 1) f)

let rec count_essay = fun maximum_grade target l ->
  let open Int64 in
  if (compare target zero) <= 0 then
    zero
  else
    let (grade, essay) = List.hd l in
    let grade_up = sub maximum_grade (of_int grade) in
    if (compare grade_up target) <= 0 then
      (add (mul grade_up (of_int essay)) (count_essay maximum_grade (sub target grade_up) (List.tl l)))
    else
      (mul target (of_int essay))

let () =
  let (n, r, avg) = read_line ()
    |> Str.split (Str.regexp " +")
    |> List.map int_of_string
    |> fun li ->
      match li with
      | a :: b :: [c] ->
        (a, b, c)
      | _ ->
        raise Invalid_input
  in
  let exams = make_list n (fun () ->
    read_line ()
    |> Str.split (Str.regexp " +")
    |> List.map int_of_string
    |> fun li ->
      match li with
      | a :: [b] ->
        (a, b)
      | _ ->
        raise Invalid_input
  )
  |> List.fast_sort (fun (_, a) (_, b) -> a - b)
  in
  let current_score = exams
  |> List.fold_left (fun sum (a, _) -> Int64.(add sum (of_int a))) Int64.zero
  in
  exams
  |> count_essay (Int64.of_int r) Int64.(sub (mul (of_int n) (of_int avg)) current_score)
  |> Int64.to_string
  |> print_string
  |> print_newline

open Str

exception Invalid_input

let (|>) x f = f x

let rec make_list = fun len f ->
  if len = 0 then
    []
  else
    (f ()) :: (make_list (len - 1) f)

let rec count_essay = fun maximum_grade target l ->
  if target <= 0.0 then
    0.0
  else
    let (grade, essay) = List.hd l in
    let grade_up = maximum_grade -. grade in
    if grade_up <= target then
      grade_up *. essay +. (count_essay maximum_grade (target -. grade_up) (List.tl l))
    else
      target *. essay

let () =
  let (n, r, avg) = read_line ()
    |> Str.split (Str.regexp " +")
    |> List.map float_of_string
    |> fun li ->
      match li with
      | a :: b :: [c] ->
        (a, b, c)
      | _ ->
        raise Invalid_input
  in
  let exams = make_list (int_of_float n) (fun () ->
    read_line ()
    |> Str.split (Str.regexp " +")
    |> List.map float_of_string
    |> fun li ->
      match li with
      | a :: [b] ->
        (a, b)
      | _ ->
        raise Invalid_input
  )
  |> List.fast_sort (fun (_, a) (_, b) ->
    if a < b then -1 else 1
  )
  in
  let current_score = exams
  |> List.fold_left (fun sum (a, _) -> sum +. a) 0.0
  in
  exams
  |> count_essay r (n *. avg -. current_score)
  |> int_of_float
  |> Printf.printf "%d\n"

open Str

exception Invalid_input

let (|>) x f = f x

let rec make_list = fun len f ->
  if len = 0 then
    []
  else
    (f ()) :: (make_list (len - 1) f)

let rec count_essay = fun maximum_grade target l ->
  if target <= 0 then
    0
  else
    let (grade, essay) = List.hd l in
    let grade_up = maximum_grade - grade in
    if grade_up <= target then
      grade_up * essay + (count_essay maximum_grade (target - grade_up) (List.tl l))
    else
      target * essay

let () =
  let (n, r, avg) = read_line ()
    |> Str.split (Str.regexp " +")
    |> List.map int_of_string
    |> fun li ->
      match li with
      | a :: b :: [c] ->
        (a, b, c)
      | _ ->
        raise Invalid_input
  in
  let exams = make_list n (fun () ->
    read_line ()
    |> Str.split (Str.regexp " +")
    |> List.map int_of_string
    |> fun li ->
      match li with
      | a :: [b] ->
        (a, b)
      | _ ->
        raise Invalid_input
  )
  |> List.fast_sort (fun (_, a) (_, b) ->
    a - b
  )
  in
  let current_score = exams
  |> List.fold_left (fun sum (a, _) -> sum + a) 0
  in
  exams
  |> count_essay r (n * avg - current_score)
  |> Printf.printf "%d\n"

open Str

exception Invalid_input

let (|>) x f = f x

let rec make_list = fun len f ->
  if len = 0 then
    []
  else
    (f ()) :: (make_list (len - 1) f)

let rec count_essay = fun maximum_grade target l ->
  if target <= 0.0 then
    0.0
  else
    let (grade, essay) = List.hd l in
    let grade_up = maximum_grade -. grade in
    if grade_up <= target then
      grade_up *. essay +. (count_essay maximum_grade (target -. grade_up) (List.tl l))
    else
      target *. essay

let () =
  let (n, r, avg) = read_line ()
    |> Str.split (Str.regexp " +")
    |> List.map float_of_string
    |> fun li ->
      match li with
      | a :: b :: [c] ->
        (a, b, c)
      | _ ->
        raise Invalid_input
  in
  let exams = make_list (int_of_float n) (fun () ->
    read_line ()
    |> Str.split (Str.regexp " +")
    |> List.map float_of_string
    |> fun li ->
      match li with
      | a :: [b] ->
        (a, b)
      | _ ->
        raise Invalid_input
  )
  |> List.fast_sort (fun (_, a) (_, b) ->
    if a < b then -1 else 1
  )
  in
  let current_score = exams
  |> List.fold_left (fun sum (a, _) -> sum +. a) 0.0
  in
  exams
  |> count_essay r (n *. avg -. current_score)
  |> Printf.printf "%.f\n"


You are given a permutation of the numbers 1, 2, ..., n and m pairs of positions (aj, bj).At each step you can choose a pair from the given positions and swap the numbers in that positions. What is the lexicographically maximal permutation one can get?Let p and q be two permutations of the numbers 1, 2, ..., n. p is lexicographically smaller than the q if a number 1 ≤ i ≤ n exists, so pk = qk for 1 ≤ k < i and pi < qi.

The first line contains two integers n and m (1 ≤ n, m ≤ 106) — the length of the permutation p and the number of pairs of positions. The second line contains n distinct integers pi (1 ≤ pi ≤ n) — the elements of the permutation p. Each of the last m lines contains two integers (aj, bj) (1 ≤ aj, bj ≤ n) — the pairs of positions to swap. Note that you are given a positions, not the values to swap.

Print the only line with n distinct integers p'i (1 ≤ p'i ≤ n) — the lexicographically maximal permutation one can get.

let getnum =
  let l = 512000 in
  let buf = String.make l ' ' in
  let s = ref 0 in
  let pos = ref 0 in
  let getc () =
    if !pos >= !s then (
      let new_s = input stdin buf 0 l in
	(*if new_s = 0 then raise End_of_file;*)
	s := new_s;
	if new_s = 0 then (
	  buf.[0] <- '\000';
	  s := 1;
	);
	pos := 0;
    );
    let c = buf.[!pos] in
      incr pos;
      c
  in
  let aux () =
    let n = ref 0 in
    let k = ref 1 in
      if !s - !pos < 50 then (
	let c = ref (getc ()) in
	  while !c <= ' ' do
	    c := getc ()
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := getc ();
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := getc ()
	  done;
	  !n * !k
      ) else (
	let c = ref (buf.[!pos]) in
	  incr pos;
	  while !c <= ' ' do
	    c := buf.[!pos];
	    incr pos;
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := buf.[!pos];
	    incr pos;
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := buf.[!pos];
	    incr pos;
	  done;
	  !n * !k
      )
  in
    aux

type t = {p : int array;
	  rank : int array}

let makeset set x =
  set.p.(x) <- x;
  set.rank.(x) <- 0

let rec find set x =
  if x <> set.p.(x) then set.p.(x) <- find set set.p.(x);
  set.p.(x)

let link set x y =
  if set.rank.(x) > set.rank.(y) then (
    set.p.(y) <- x;
    x
  ) else (
    if set.rank.(x) = set.rank.(y) then set.rank.(y) <- set.rank.(y) + 1;
    set.p.(x) <- y;
    y
  )

let newsets size =
  let set =
    {p = Array.make size (-1);
     rank = Array.make size 0
    }
  in
    for i = 0 to size-1 do
      makeset set i
    done;
    set

let _ =
  let n = getnum () in
  let m = getnum () in
  let a = Array.make n 0 in
  let ds = newsets n in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- getnum ()
    done;
    for i = 0 to m - 1 do
      let u = getnum () - 1 in
      let v = getnum () - 1 in
      let u = find ds u in
      let v = find ds v in
	ignore (link ds u v)
    done;
  in
  let res = Array.make n 0 in
  let b = Array.make n [] in
  let _ =
    for i = 0 to n - 1 do
      let j = find ds i in
	b.(j) <- i :: b.(j)
    done;
  in
  let b = Array.map Array.of_list b in
  let cmp (x : int) y =
    if x < y
    then -1
    else if x = y
    then 0
    else 1
  in
  let get i = a.(i) in
    for i = 0 to n - 1 do
      let c = Array.map get b.(i) in
	Array.sort cmp c;
	for j = 0 to Array.length b.(i) - 1 do
	  res.(b.(i).(j)) <- c.(j)
	done;
    done;
    for i = 0 to n - 1 do
      Printf.printf "%d " res.(i)
    done;
    Printf.printf "\n"


Vova plans to go to the conference by train. Initially, the train is at the point $$$1$$$ and the destination point of the path is the point $$$L$$$. The speed of the train is $$$1$$$ length unit per minute (i.e. at the first minute the train is at the point $$$1$$$, at the second minute — at the point $$$2$$$ and so on).There are lanterns on the path. They are placed at the points with coordinates divisible by $$$v$$$ (i.e. the first lantern is at the point $$$v$$$, the second is at the point $$$2v$$$ and so on).There is also exactly one standing train which occupies all the points from $$$l$$$ to $$$r$$$ inclusive.Vova can see the lantern at the point $$$p$$$ if $$$p$$$ is divisible by $$$v$$$ and there is no standing train at this position ($$$p \not\in [l; r]$$$). Thus, if the point with the lantern is one of the points covered by the standing train, Vova can't see this lantern.Your problem is to say the number of lanterns Vova will see during the path. Vova plans to go to $$$t$$$ different conferences, so you should answer $$$t$$$ independent queries.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of queries. Then $$$t$$$ lines follow. The $$$i$$$-th line contains four integers $$$L_i, v_i, l_i, r_i$$$ ($$$1 \le L, v \le 10^9$$$, $$$1 \le l \le r \le L$$$) — destination point of the $$$i$$$-th path, the period of the lantern appearance and the segment occupied by the standing train.

Print $$$t$$$ lines. The $$$i$$$-th line should contain one integer — the answer for the $$$i$$$-th query.

NoteFor the first example query, the answer is $$$3$$$. There are lanterns at positions $$$2$$$, $$$4$$$, $$$6$$$, $$$8$$$ and $$$10$$$, but Vova didn't see the lanterns at positions $$$4$$$ and $$$6$$$ because of the standing train.For the second example query, the answer is $$$0$$$ because the only lantern is at the point $$$51$$$ and there is also a standing train at this point.For the third example query, the answer is $$$1134$$$ because there are $$$1234$$$ lanterns, but Vova didn't see the lanterns from the position $$$100$$$ to the position $$$199$$$ inclusive.For the fourth example query, the answer is $$$0$$$ because the standing train covers the whole path.

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 let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end
module MyInt64 = struct
	let (%$) = (mod) 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 repb 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; !f 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 !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb 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,!f) 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 (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v
	let ceildiv m n = (m+n-1L) / n
	let abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf " %s" (fun v -> v)
	let i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a
	let dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf " %d" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf " %d %d" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y) let repi 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
end open MyInt64

let () =
	let t = get_i64 0 in
	rep 1L t (fun _ ->
		let ll,v,l,r = get_4_i64 0 in
		let k_left =
			if l mod v = 0L then l/v-1L
			else l/v
		in
		let v_r = if r mod v = 0L then (r/v+1L)*v else (r/v+1L)*v in
		let k_right = ((ll/v)*v - v_r)/v + 1L in
		printf "%Ld\n" (k_left + k_right);
		(* printf "%Ld %Ld\n" k_left k_right  *)
		(* let n = ll / v in
		printf "%Ld\n" (ll/v - r/v + l/v) *)
		; `Ok
	)


Little Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph.There are n toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turned over, both cars turned over. A car is good if it turned over in no collision. The results of the collisions are determined by an n × n matrix А: there is a number on the intersection of the і-th row and j-th column that describes the result of the collision of the і-th and the j-th car:    - 1: if this pair of cars never collided.  - 1 occurs only on the main diagonal of the matrix.  0: if no car turned over during the collision.  1: if only the i-th car turned over during the collision.  2: if only the j-th car turned over during the collision.  3: if both cars turned over during the collision. Susie wants to find all the good cars. She quickly determined which cars are good. Can you cope with the task?

The first line contains integer n (1 ≤ n ≤ 100) — the number of cars. Each of the next n lines contains n space-separated integers that determine matrix A.  It is guaranteed that on the main diagonal there are  - 1, and  - 1 doesn't appear anywhere else in the matrix. It is guaranteed that the input is correct, that is, if Aij = 1, then Aji = 2, if Aij = 3, then Aji = 3, and if Aij = 0, then Aji = 0.

Print the number of good cars and in the next line print their space-separated indices in the increasing order.

let _ =
	let n = Scanf.scanf "%d " (fun i -> i) and l = ref [] in
	for i=1 to n do
		let flg = ref true in
		for j=1 to i-1 do
			Scanf.scanf "%d " (fun a -> flg := !flg && (a mod 2 = 0));
		done;
		Scanf.scanf "%d " (fun a -> ());
		for j=i+1 to n do
			Scanf.scanf "%d " (fun a -> flg := !flg && (a mod 2 = 0));
		done;
		if !flg then l := i::!l;
	done;
	Printf.printf "%d\n" (List.length !l);
	List.iter (fun i -> Printf.printf "%d " i) (List.rev !l)


You are given an integer m.Let M = 2m - 1.You are also given a set of n integers denoted as the set T. The integers will be provided in base 2 as n binary strings of length m.A set of integers S is called "good" if the following hold.   If , then .  If , then     All elements of S are less than or equal to M. Here,  and  refer to the bitwise XOR and bitwise AND operators, respectively.Count the number of good sets S, modulo 109 + 7.

The first line will contain two integers m and n (1 ≤ m ≤ 1 000, 1 ≤ n ≤ min(2m, 50)). The next n lines will contain the elements of T. Each line will contain exactly m zeros and ones. Elements of T will be distinct.

Print a single integer, the number of good sets modulo 109 + 7.

(* Write the input numbers as a matrix.  Each number forms a row of
   bits.  Now let's say you want to construct the set S = closure(T)
   generated by using the described operations.  You do this by doing
   row operations on the matrix to construct new rows, and continue to
   do this until no operation adds anything new.  The operations are
   (1) complement a row and (2) form the AND of two rows.  Note that
   by combining these we can get OR as well.

   Suppose no two columns are identical.  Then S consists of all m bit
   patterns.  Here's why.  Take the ith column.  By ANDing together
   each row (complented if column i of that row has a 0 in it) we get
   an basis vector that has 1 in position i and 0 everywhere else.
   We can now OR together any subset of these basis vectors to get
   any vector.

   Conversely note that if two columns i and j are identical, then
   positions i and j will be identical in any number generated by
   any of the row operations.

   So closure(T) is completely characterized by the groups of
   identical columns of T.  For example, say m=5, and columns 1, 2,
   and 3 of T are identical and columns 4 and 5 are also identical
   (but different from 1, 2, and 3).  Say we add this row: 00100.
   This splits columns 1,2, and 3 into two groups: (1,2) and (3).
   (Alternatively we could have added 01000 which would make the
   groups (1,3) and (2).)  Then we could add 10000 which further
   splits the (1,2) group in two.  Each way of doing this gives a
   different closure and thus a different S.

   So given a set of numbers {1,2,...,n} how many distinct ways are
   there to split it into non-empty groups?  You solve this by
   defining S(n,k) to be the numuber of ways to break {1...n} into
   k groups.  What we want is then S(n,1) + S(n,2) + ... + S(n,n).

   So in the example above with m=5 the number of possible closures is:

         (S(3,1) + S(3,2) + S(3,3))  *  (S(2,1) + S(2,2))

   Of course this is a known combinatorial quantity, the Stirling
   numbers of the 2nd kind.  A nice recurrence is

   S(n+1,k) = k*S(n,k) + S(n,k-1)

   Along with base cases S(0,0) = 1 and S(n,0) = S(0,n) = 0. for n>0.
   https://en.wikipedia.org/wiki/Stirling_numbers_of_the_second_kind

   We can just compute these mod 10^9+7 using the obove recurrence
   since m <= 1000, and it's O(m^2).  Grouping the columns into
   equivalence classes is easily done using a hash table.  voilà.

*)

let p = 1_000_000_007L

let long x = Int64.of_int x
let short x = Int64.to_int x
let ( %% ) a b = Int64.rem a b
let ( ** ) a b = (Int64.mul a b) %% p
let ( ++ ) a b = (Int64.add a b) %% p
let ( -- ) a b = ((Int64.sub a b) ++ p)

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

let init_stirling nn kk =
  (* compute an array b so that s.(n).(k) = {n stirling k},
     where 0 <= n <= nn and 0 <= k <= kk. *)
  let s = Array.make_matrix (nn+1) (kk+1) 0L in
  for n=0 to nn do for k=0 to min nn kk do
      s.(n).(k) <-
	if n=0 && k=0 then 1L
	else if n=0 || k=0 then 0L
	else (long k) ** s.(n-1).(k) ++ s.(n-1).(k-1)
    done done;
  s

let init_bell nn =
  let s = init_stirling nn nn in
  let bell = Array.make (nn+1) 0L in
  for n=0 to nn do
    bell.(n) <- sum 0 n (fun k -> s.(n).(k))
  done;
  bell

open Printf
open Scanf

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

  let h = Hashtbl.create 10 in
  let increment t =
    let c = try Hashtbl.find h t with Not_found -> 0 in
    Hashtbl.replace h t (c+1)
  in

  let column i = Array.init n (fun r -> t.(r).[i]) in
  for i=0 to m-1 do increment (column i) done;

  let bell = init_bell m in

  let answer = Hashtbl.fold (fun _ c ac -> bell.(c) ** ac) h 1L in

  printf "%Ld\n" answer


Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to n in their order. Dima performs several steps, on step i he reverses the segment of cubes from i-th to (n - i + 1)-th. He does this while i ≤ n - i + 1.After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location.

The first line contains single integer n (1 ≤ n ≤ 2·105) — the number of cubes. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109), where ai is the number written on the i-th cube after Dima has changed their order.

Print n integers, separated by spaces — the numbers written on the cubes in their initial order. It can be shown that the answer is unique.

NoteConsider the first sample.  At the begining row was [2, 3, 9, 6, 7, 1, 4].  After first operation row was [4, 1, 7, 6, 9, 3, 2].  After second operation row was [4, 3, 9, 6, 7, 1, 2].  After third operation row was [4, 3, 7, 6, 9, 1, 2].  At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4].

let () =
  let n = read_int () in
  (* values *)
  let a = Array.init n (fun _ -> Scanf.scanf "%d%_c" (fun x -> x)) in
  (* permutation *)
  let p = Array.init n (fun i ->
                       if i mod 2 = (if n mod 2 = 0 && i >= n / 2 then 1 else 0)
                       then a.(n - i - 1)
                       else a.(i)) in
  (* output *)
  print_endline (String.concat " " (Array.to_list (Array.map string_of_int p)))

let rd_int = (fun () -> Scanf.scanf " %d" (fun n -> n)) in
let pri i = print_string ((string_of_int i) ^ " ") in
let n = rd_int () in
let rec make_list n =
    if n == 0 then
        []
    else
        let num = rd_int () in
        num :: make_list (n - 1)
in
let a = make_list n in
let rec pr_list k l rl =
    if k >= n then
        ()
    else

        match l with
        | [] -> ()
        | hd :: tl ->
                match rl with
                | [] -> ()
                | hdr :: tlr ->
                        let _ = pri hdr in
                        let _ = pr_list (k + 2) tlr tl in
                        if k + 1 == n then () else pri hd
in
pr_list 0 a (List.rev a);;

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

    print_newline ();
;;

let rearrange_blocks a =
    let n = Array.length a in
    let n_2 = n / 2 in
    let n_4 = (n_2 + 1) / 2 in
    for j = 0 to (n_4 - 1) do
        let k = j * 2 in
        let tmp = a.(k) in
        begin
            a.( k ) <- a.( n - k - 1 );
            a.( n - k - 1 ) <- tmp;
        end
    done;
    print_array a;
;;

let rec read_block a k =
    if k < (Array.length a) then
        Scanf.bscanf Scanf.Scanning.stdin "%i " (add_block a k)
    else
        rearrange_blocks a
and add_block a k v =
    begin
        a.(k) <- v;
        read_block a (k + 1)
    end
;;

let read_blocks n =
    let blocks = Array.make n 0 in
    read_block blocks 0
;;

read_blocks (read_int ());;


Amr loves Chemistry, and specially doing experiments. He is preparing for a new interesting experiment.Amr has n different types of chemicals. Each chemical i has an initial volume of ai liters. For this experiment, Amr has to mix all the chemicals together, but all the chemicals volumes must be equal first. So his task is to make all the chemicals volumes equal.To do this, Amr can do two different kind of operations.   Choose some chemical i and double its current volume so the new volume will be 2ai  Choose some chemical i and divide its volume by two (integer division) so the new volume will be  Suppose that each chemical is contained in a vessel of infinite volume. Now Amr wonders what is the minimum number of operations required to make all the chemicals volumes equal?

The first line contains one number n (1 ≤ n ≤ 105), the number of chemicals. The second line contains n space separated integers ai (1 ≤ ai ≤ 105), representing the initial volume of the i-th chemical in liters.

Output one integer the minimum number of operations required to make all the chemicals volumes equal.

NoteIn the first sample test, the optimal solution is to divide the second chemical volume by two, and multiply the third chemical volume by two to make all the volumes equal 4.In the second sample test, the optimal solution is to divide the first chemical volume by two, and divide the second and the third chemical volumes by two twice to make all the volumes equal 1.

open Printf
open Scanf

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

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let a = Array.init n (fun _ -> read_int()) in

  let ma = maxf 0 (n-1) (fun i -> a.(i)) in

  let inf_cost = 100 in
  let gen_cost = Array.make (ma+1) inf_cost in

  let count = Array.make (ma+1) 0 in  (* how many of the input number gen this number *)
  let gen_me = Array.make (ma+1) 0 in  (* total over all input of the cost to generate this *)

  for i = 0 to n-1 do
    let glist = ref [] in
    let x = a.(i) in
    let rec outer_loop r =
      let x = x lsr r in
      if x > 0 then (
	let rec inner_loop l =
	  let x = x lsl l in
	  if x <= ma then (
	    if gen_cost.(x) = inf_cost then glist := x:: !glist;
	    gen_cost.(x) <- min gen_cost.(x) (r+l);
	    inner_loop (l+1)
	  )
	in
	inner_loop 0;
	outer_loop (r+1)
      )
    in
    outer_loop 0;
    List.iter (fun x -> count.(x) <- count.(x) + 1) !glist;
    List.iter (fun x -> gen_me.(x) <- gen_me.(x) + gen_cost.(x)) !glist;
    List.iter (fun x -> gen_cost.(x) <- inf_cost) !glist
  done;

  let answer = minf 1 ma (
    fun g ->
      if count.(g) = n then gen_me.(g) else inf_cost * n
  ) in

  printf "%d\n" answer


Let's call an array $$$a$$$ consisting of $$$n$$$ positive (greater than $$$0$$$) integers beautiful if the following condition is held for every $$$i$$$ from $$$1$$$ to $$$n$$$: either $$$a_i = 1$$$, or at least one of the numbers $$$a_i - 1$$$ and $$$a_i - 2$$$ exists in the array as well.For example:   the array $$$[5, 3, 1]$$$ is beautiful: for $$$a_1$$$, the number $$$a_1 - 2 = 3$$$ exists in the array; for $$$a_2$$$, the number $$$a_2 - 2 = 1$$$ exists in the array; for $$$a_3$$$, the condition $$$a_3 = 1$$$ holds;  the array $$$[1, 2, 2, 2, 2]$$$ is beautiful: for $$$a_1$$$, the condition $$$a_1 = 1$$$ holds; for every other number $$$a_i$$$, the number $$$a_i - 1 = 1$$$ exists in the array;  the array $$$[1, 4]$$$ is not beautiful: for $$$a_2$$$, neither $$$a_2 - 2 = 2$$$ nor $$$a_2 - 1 = 3$$$ exists in the array, and $$$a_2 \ne 1$$$;  the array $$$[2]$$$ is not beautiful: for $$$a_1$$$, neither $$$a_1 - 1 = 1$$$ nor $$$a_1 - 2 = 0$$$ exists in the array, and $$$a_1 \ne 1$$$;  the array $$$[2, 1, 3]$$$ is beautiful: for $$$a_1$$$, the number $$$a_1 - 1 = 1$$$ exists in the array; for $$$a_2$$$, the condition $$$a_2 = 1$$$ holds; for $$$a_3$$$, the number $$$a_3 - 2 = 1$$$ exists in the array. You are given a positive integer $$$s$$$. Find the minimum possible size of a beautiful array with the sum of elements equal to $$$s$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 5000$$$) — the number of test cases. Then $$$t$$$ lines follow, the $$$i$$$-th line contains one integer $$$s$$$ ($$$1 \le s \le 5000$$$) for the $$$i$$$-th test case.

Print $$$t$$$ integers, the $$$i$$$-th integer should be the answer for the $$$i$$$-th testcase: the minimum possible size of a beautiful array with the sum of elements equal to $$$s$$$.

NoteConsider the example test:  in the first test case, the array $$$[1]$$$ meets all conditions;  in the second test case, the array $$$[3, 4, 1]$$$ meets all conditions;  in the third test case, the array $$$[1, 2, 4]$$$ meets all conditions;  in the fourth test case, the array $$$[1, 4, 6, 8, 10, 2, 11]$$$ meets all conditions.

open Scanf
open Printf

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

let () =
  for _ = 1 to scan_int () do
    let s = scan_int () in
    printf "%d\n" @@ int_of_float @@ ceil @@ sqrt @@ float_of_int s
  done