Ujan decided to make a new wooden roof for the house. He has $$$n$$$ rectangular planks numbered from $$$1$$$ to $$$n$$$. The $$$i$$$-th plank has size $$$a_i \times 1$$$ (that is, the width is $$$1$$$ and the height is $$$a_i$$$).Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will glue together all of these planks by their vertical sides. Finally, he will cut out a square from the resulting shape in such a way that the sides of the square are horizontal and vertical.For example, if Ujan had planks with lengths $$$4$$$, $$$3$$$, $$$1$$$, $$$4$$$ and $$$5$$$, he could choose planks with lengths $$$4$$$, $$$3$$$ and $$$5$$$. Then he can cut out a $$$3 \times 3$$$ square, which is the maximum possible. Note that this is not the only way he can obtain a $$$3 \times 3$$$ square.  What is the maximum side length of the square Ujan can get?

The first line of input contains a single integer $$$k$$$ ($$$1 \leq k \leq 10$$$), the number of test cases in the input. For each test case, the first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 1\,000$$$), the number of planks Ujan has in store. The next line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \leq a_i \leq n$$$), the lengths of the planks.

For each of the test cases, output a single integer, the maximum possible side length of the square.

NoteThe first sample corresponds to the example in the statement.In the second sample, gluing all $$$4$$$ planks will result in a $$$4 \times 4$$$ square.In the third sample, the maximum possible square is $$$1 \times 1$$$ and can be taken simply as any of the planks.

open Printf

let can_square n l =
  (List.fold_left (fun a x -> if x > n then a+1 else a) 0 l) > n

let split_on_char char str =
  let re = Str.regexp char in
  Str.split re str

let solve l =
  let rec solve' n l =
    if can_square n l then solve' (n+1) l else n
  in
  solve' 0 l

let rec parse_problems () =
  let _ = input_line stdin in
  let sticks = input_line stdin in
  let problem = List.map int_of_string (split_on_char " " sticks) in
  printf "%d\n" (solve problem);
  parse_problems ()

let () =
  let _ = input_line stdin in
  try parse_problems ()
  with End_of_file -> ()


You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems:  the Power Gem of purple color,  the Time Gem of green color,  the Space Gem of blue color,  the Soul Gem of orange color,  the Reality Gem of red color,  the Mind Gem of yellow color. Using colors of Gems you saw in the Gauntlet determine the names of absent Gems.

In the first line of input there is one integer $$$n$$$ ($$$0 \le n \le 6$$$) — the number of Gems in Infinity Gauntlet. In next $$$n$$$ lines there are colors of Gems you saw. Words used for colors are: purple, green, blue, orange, red, yellow. It is guaranteed that all the colors are distinct. All colors are given in lowercase English letters.

In the first line output one integer $$$m$$$ ($$$0 \le m \le 6$$$) — the number of absent Gems. Then in $$$m$$$ lines print the names of absent Gems, each on its own line. Words used for names are: Power, Time, Space, Soul, Reality, Mind. Names can be printed in any order. Keep the first letter uppercase, others lowercase.

NoteIn the first sample Thanos already has Reality, Power, Mind and Soul Gems, so he needs two more: Time and Space.In the second sample Thanos doesn't have any Gems, so he needs all six.

module StringSet = Set.Make(String)

module StringMap = Map.Make(String)

let all_colors = (StringSet.of_list [
    "purple"; "green"; "blue"; "orange"; "red"; "yellow"
  ])

let gem_of_color = ref StringMap.empty

let () =
  List.iter
    (fun (k, v) -> gem_of_color := StringMap.add k v !gem_of_color)
    [
      ("purple", "Power");
      ("green", "Time");
      ("blue", "Space");
      ("orange", "Soul");
      ("red", "Reality");
      ("yellow", "Mind");
    ];
  let m = Scanf.scanf "%d" (fun i -> i) in
  let colors = ref all_colors in
  for i = 1 to m do
    let s = Scanf.scanf " %s" (fun i -> i) in
    colors := StringSet.remove s !colors
  done;
  Printf.printf "%d\n" (StringSet.cardinal !colors);
  StringSet.iter (fun s ->
      Printf.printf "%s\n" (StringMap.find s !gem_of_color)) !colors

let gems =
  [("purple", "Power");
  ("green", "Time");
  ("blue", "Space");
  ("orange", "Soul");
  ("red", "Reality");
  ("yellow", "Mind")]

let () =
  let n = int_of_string (input_line stdin) in
  let pr = ref [] in
  for i = 0 to n - 1 do
    pr := (input_line stdin) :: !pr
  done;
  let present = !pr in
  let p (gem_colour, gem_name) = not (List.mem gem_colour present) in
  let f (gem_colour, gem_name) = gem_name in
  let toprint = List.map f (List.filter p gems) in
  print_endline (string_of_int (List.length toprint));
  ignore (List.map print_endline toprint)


Consider a simplified penalty phase at the end of a football match.A penalty phase consists of at most $$$10$$$ kicks, the first team takes the first kick, the second team takes the second kick, then the first team takes the third kick, and so on. The team that scores more goals wins; if both teams score the same number of goals, the game results in a tie (note that it goes against the usual football rules). The penalty phase is stopped if one team has scored more goals than the other team could reach with all of its remaining kicks. For example, if after the $$$7$$$-th kick the first team has scored $$$1$$$ goal, and the second team has scored $$$3$$$ goals, the penalty phase ends — the first team cannot reach $$$3$$$ goals.You know which player will be taking each kick, so you have your predictions for each of the $$$10$$$ kicks. These predictions are represented by a string $$$s$$$ consisting of $$$10$$$ characters. Each character can either be 1, 0, or ?. This string represents your predictions in the following way:  if $$$s_i$$$ is 1, then the $$$i$$$-th kick will definitely score a goal;  if $$$s_i$$$ is 0, then the $$$i$$$-th kick definitely won't score a goal;  if $$$s_i$$$ is ?, then the $$$i$$$-th kick could go either way. Based on your predictions, you have to calculate the minimum possible number of kicks there can be in the penalty phase (that means, the earliest moment when the penalty phase is stopped, considering all possible ways it could go). Note that the referee doesn't take into account any predictions when deciding to stop the penalty phase — you may know that some kick will/won't be scored, but the referee doesn't.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 1\,000$$$) — the number of test cases. Each test case is represented by one line containing the string $$$s$$$, consisting of exactly $$$10$$$ characters. Each character is either 1, 0, or ?.

For each test case, print one integer — the minimum possible number of kicks in the penalty phase.

NoteConsider the example test:In the first test case, consider the situation when the $$$1$$$-st, $$$5$$$-th and $$$7$$$-th kicks score goals, and kicks $$$2$$$, $$$3$$$, $$$4$$$ and $$$6$$$ are unsuccessful. Then the current number of goals for the first team is $$$3$$$, for the second team is $$$0$$$, and the referee sees that the second team can score at most $$$2$$$ goals in the remaining kicks. So the penalty phase can be stopped after the $$$7$$$-th kick.In the second test case, the penalty phase won't be stopped until all $$$10$$$ kicks are finished.In the third test case, if the first team doesn't score any of its three first kicks and the second team scores all of its three first kicks, then after the $$$6$$$-th kick, the first team has scored $$$0$$$ goals and the second team has scored $$$3$$$ goals, and the referee sees that the first team can score at most $$$2$$$ goals in the remaining kicks. So, the penalty phase can be stopped after the $$$6$$$-th kick.In the fourth test case, even though you can predict the whole penalty phase, the referee understands that the phase should be ended only after the $$$9$$$-th kick.

(* Codeforces 1553 C Penalty train *)

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

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

(* end my library. below concrete program *)

type tside = First | Second;;

let other side = match side with
	| First -> Second
	| Second -> First;;

let sideName side = match side with
	| First -> "First"
	| Second -> "Second";;

let won step nfirst nsecond =
	let canF = (10 - step) / 2 in
	let canS = (10 - step + 1) /2 in
	let wonF = nfirst > (nsecond + canS) in
	let wonS = nsecond > (nfirst + canF) in
	wonF || wonS;;

let rec game s side forFirst step nfirst nsecond =
	if step==10 then step
	else
		let _ = if debug then Printf.printf "game %s %s %b %d %d %d\n"
						s (sideName side) forFirst step nfirst nsecond in
		let nside = other side in
		let nstep = step+1 in
		let ch = s.[step-1] in
		let nch = if (ch != '?') then ch
				else if (((side==First) && forFirst) || (side==Second && (not forFirst)))
					then	'1'
					else  '0' in
		let ich = if nch == '1' then 1 else 0 in
		let _ = if debug then
				Printf.printf "ch,nch,ich %c %c %d\n" ch nch ich in
		let nnfirst = if side==First then nfirst+ich else nfirst in
		let nnsecond = if side==Second then nsecond+ich else nsecond in
		if won step nnfirst nnsecond
			then
				let _ = if debug then Printf.printf "won step,nfirst,nsecond = %d %d %d\n"
																	step nnfirst nnsecond in
				step
		else
			game s nside forFirst nstep nnfirst nnsecond;;

let do_one () =
    let s = rdln() in
    let gameF = game s First true 1 0 0 in
		let gameS = game s First false 1 0 0 in
		let nwin = if gameF < gameS then gameF else gameS in
    Printf.printf "%d\n" nwin;;

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

let main() =
	let st = rdln () in
	let t = int_of_string st in
	do_all t;;

main();;

(* Codeforces 1553 C Penalty train *)

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

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

(* end my library. below concrete program *)

type tside = First | Second;;

let other side = match side with
	| First -> Second
	| Second -> First;;

let sideName side = match side with
	| First -> "First"
	| Second -> "Second";;

let won step nfirst nsecond =
	let canF = (10 - step) / 2 in
	let canS = (10 - step + 1) /2 in
	let wonF = nfirst > (nsecond + canS) in
	let wonS = nsecond > (nfirst + canF) in
	wonF || wonS;;

let rec game s side forFirst step nfirst nsecond =
	if step==10 then step
	else if won step nfirst nsecond then step
	else
		(* let _ = Printf.printf "game %s %s %b %d %d %d\n"
						s (sideName side) forFirst step nfirst nsecond in *)
		let nside = other side in
		let nstep = step+1 in
		let ch = s.[step-1] in
		let nch = if (ch != '?') then ch
				else if (((side==First) && forFirst) || (side==Second && (not forFirst)))
					then	'1'
					else  '0' in
		let ich = if nch == '1' then 1 else 0 in
		(*let _ = Printf.printf "ch,nch,ich %c %c %d\n" ch nch ich in*)
		let nnfirst = if side==First then nfirst+ich else nfirst in
		let nnsecond = if side==Second then nsecond+ich else nsecond in
		game s nside forFirst nstep nnfirst nnsecond;;

let do_one () =
    let s = rdln() in
    let gameF = game s First true 1 0 0 in
		let gameS = game s First false 1 0 0 in
		let nwin = if gameF < gameS then gameF else gameS in
    Printf.printf "%d\n" nwin;;

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

let main() =
	let st = rdln () in
	let t = int_of_string st in
	do_all t;;

main();;


Mike has a frog and a flower. His frog is named Xaniar and his flower is named Abol. Initially(at time 0), height of Xaniar is h1 and height of Abol is h2. Each second, Mike waters Abol and Xaniar.  So, if height of Xaniar is h1 and height of Abol is h2, after one second height of Xaniar will become  and height of Abol will become  where x1, y1, x2 and y2 are some integer numbers and  denotes the remainder of a modulo b.Mike is a competitive programmer fan. He wants to know the minimum time it takes until height of Xania is a1 and height of Abol is a2.Mike has asked you for your help. Calculate the minimum time or say it will never happen.

The first line of input contains integer m (2 ≤ m ≤ 106). The second line of input contains integers h1 and a1 (0 ≤ h1, a1 < m). The third line of input contains integers x1 and y1 (0 ≤ x1, y1 < m). The fourth line of input contains integers h2 and a2 (0 ≤ h2, a2 < m). The fifth line of input contains integers x2 and y2 (0 ≤ x2, y2 < m). It is guaranteed that h1 ≠ a1 and h2 ≠ a2.

Print the minimum number of seconds until Xaniar reaches height a1 and Abol reaches height a2 or print -1 otherwise.

NoteIn the first sample, heights sequences are following:Xaniar: Abol:

module I = Int64

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

let cyclize m h a x y =
  let lim = 1000*1000 in
  let x = I.of_int x in
  let y = I.of_int y in
  let m = I.of_int m in
  let adv h = I.to_int (I.rem (I.add (I.mul x (I.of_int h)) (y)) m) in
  let rec search i h =
    if i = lim then raise Not_found
    else
      if h = a
      then (i, search2 1 (adv h))
      else search (i+1) (adv h)
  and search2 i h =
    if i = lim then 0
    else
      if h = a
      then i
      else (search2 (i+1) (adv h))
  in
  search 0 h

(* Timize is probably wrong, but nobody will ever observe this *)
let timize t1 p1 t2 p2 =
  let lim = 1000 * 1000 in
  let t1 = I.of_int t1 in
  let t2 = I.of_int t2 in
  let p1 = I.of_int p1 in
  let p2 = I.of_int p2 in
  (* Advance one and another until meet or limit *)
  let rec search i j t1 t2 =
    if i > lim || j > lim then raise Not_found
    else
      if t1 = t2 then t2
      else if t1 > t2 then (if p2 = I.zero then raise Not_found; search (i+1) j t1 (I.add t2 p2))
      else (if p1 = I.zero then raise Not_found; search i (j+1) (I.add t1 p1) t2)
  in
  search 0 0 t1 t2

let _ =
  let m = read_int () in
  let h1 = read_int () in
  let a1 = read_int () in
  let x1 = read_int () in
  let y1 = read_int () in
  let h2 = read_int () in
  let a2 = read_int () in
  let x2 = read_int () in
  let y2 = read_int () in
  try
    let (t1,p1) = cyclize m h1 a1 x1 y1 in
    let (t2,p2) = cyclize m h2 a2 x2 y2 in
(*    Printf.printf "Stopped at (%d,%d) and (%d,%d)\n" t1 p1 t2 p2; *)
    Printf.printf "%Ld\n" (timize t1 p1 t2 p2)
  with
      Not_found -> Printf.printf "-1\n"

module I = Int64

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

let cyclize m h a x y =
  let lim = 1000*1000 in
  let x = I.of_int x in
  let y = I.of_int y in
  let m = I.of_int m in
  let adv h = I.to_int (I.rem (I.add (I.mul x (I.of_int h)) (y)) m) in
  let rec search i h =
    if i = lim then raise Not_found
    else
      if h = a
      then (i, search2 1 (adv h))
      else search (i+1) (adv h)
  and search2 i h =
    if i = lim then 0
    else
      if h = a
      then i
      else (search2 (i+1) (adv h))
  in
  search 0 h

(* Timize is probably wrong, but nobody will ever observe this *)
let timize t1 p1 t2 p2 =
  let lim = 1000 * 1000 in
  let t1 = I.of_int t1 in
  let t2 = I.of_int t2 in
  let p1 = I.of_int p1 in
  let p2 = I.of_int p2 in
  (* Advance one and another until meet or limit *)
  let rec search i j t1 t2 =
    if i > lim || j > lim then raise Not_found
    else
      if t1 = t2 then t2
      else if t1 > t2 then (if p2 = I.zero then raise Not_found; search (i+1) j t1 (I.add t2 p2))
      else (if p1 = I.zero then raise Not_found; search i (j+1) (I.add t1 p1) t2)
  in
  search 0 0 t1 t2

let _ =
  let m = read_int () in
  let h1 = read_int () in
  let a1 = read_int () in
  let x1 = read_int () in
  let y1 = read_int () in
  let h2 = read_int () in
  let a2 = read_int () in
  let x2 = read_int () in
  let y2 = read_int () in
  try
    let (t1,p1) = cyclize m h1 a1 x1 y1 in
    let (t2,p2) = cyclize m h2 a2 x2 y2 in
    Printf.printf "Stopped at (%d,%d) and (%d,%d)\n" t1 p1 t2 p2;
    Printf.printf "%Ld\n" (timize t1 p1 t2 p2)
  with
      Not_found -> Printf.printf "-1\n"


Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point $$$(x_1,y_1)$$$ to the point $$$(x_2,y_2)$$$.He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly $$$1$$$ unit away from the box in the direction of one of two coordinate axes. He will pull the box to where he is standing before moving out of the way in the same direction by $$$1$$$ unit.   For example, if the box is at the point $$$(1,2)$$$ and Wabbit is standing at the point $$$(2,2)$$$, he can pull the box right by $$$1$$$ unit, with the box ending up at the point $$$(2,2)$$$ and Wabbit ending at the point $$$(3,2)$$$.Also, Wabbit can move $$$1$$$ unit to the right, left, up, or down without pulling the box. In this case, it is not necessary for him to be in exactly $$$1$$$ unit away from the box. If he wants to pull the box again, he must return to a point next to the box. Also, Wabbit can't move to the point where the box is located.Wabbit can start at any point. It takes $$$1$$$ second to travel $$$1$$$ unit right, left, up, or down, regardless of whether he pulls the box while moving.Determine the minimum amount of time he needs to move the box from $$$(x_1,y_1)$$$ to $$$(x_2,y_2)$$$. Note that the point where Wabbit ends up at does not matter.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 1000)$$$: the number of test cases. The description of the test cases follows. Each of the next $$$t$$$ lines contains four space-separated integers $$$x_1, y_1, x_2, y_2$$$ $$$(1 \leq x_1, y_1, x_2, y_2 \leq 10^9)$$$, describing the next test case.

For each test case, print a single integer: the minimum time in seconds Wabbit needs to bring the box from $$$(x_1,y_1)$$$ to $$$(x_2,y_2)$$$.

NoteIn the first test case, the starting and the ending points of the box are $$$(1,2)$$$ and $$$(2,2)$$$ respectively. This is the same as the picture in the statement. Wabbit needs only $$$1$$$ second to move as shown in the picture in the statement.In the second test case, Wabbit can start at the point $$$(2,1)$$$. He pulls the box to $$$(2,1)$$$ while moving to $$$(3,1)$$$. He then moves to $$$(3,2)$$$ and then to $$$(2,2)$$$ without pulling the box. Then, he pulls the box to $$$(2,2)$$$ while moving to $$$(2,3)$$$. It takes $$$4$$$ seconds.

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

let solve_test() =
  let xs = Int32.of_int( read_int() ) and
      ys = Int32.of_int( read_int() ) and
      xf = Int32.of_int( read_int() ) and
      yf = Int32.of_int( read_int() ) in
  let d = Int32.add (Int32.abs (Int32.sub xs xf)) (Int32.abs (Int32.sub ys yf)) in
  let ans = if (xs = xf) || (ys = yf) then d else Int32.add d (Int32.of_int(2)) in
  print_string (Int32.to_string ans);
  print_newline()

let t = read_int();;

let () =
  for i = 1 to t do
    solve_test ()
  done

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

let myabs x =
  if x >= 0 then x else -x ;;

let solve_test() =
  let xs = read_int() and ys = read_int() and xf = read_int() and yf = read_int() in
  let d = abs (xs - xf) + abs (ys - yf) in
  let ans = if xs == xf || ys == yf then d else d + 2 in
  Printf.printf "%d\n" ans

let t = read_int();;

let () =
  for i = 1 to t do
    solve_test ()
  done

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

let myabs x =
  if x >= 0 then x else -x ;;

let solve_test() =
  let xs = read_int() and ys = read_int() and xf = read_int() and yf = read_int() in
  let d = abs (xs - xf) + abs (ys - yf) in
  let ans = if xs == yf || ys == yf then d else d + 2 in
  Printf.printf "%d\n" ans ;;

let t = read_int();;

let () =
  for i = 1 to t do
    solve_test ()
  done


You are fighting with Zmei Gorynich — a ferocious monster from Slavic myths, a huge dragon-like reptile with multiple heads!   Initially Zmei Gorynich has $$$x$$$ heads. You can deal $$$n$$$ types of blows. If you deal a blow of the $$$i$$$-th type, you decrease the number of Gorynich's heads by $$$min(d_i, curX)$$$, there $$$curX$$$ is the current number of heads. But if after this blow Zmei Gorynich has at least one head, he grows $$$h_i$$$ new heads. If $$$curX = 0$$$ then Gorynich is defeated. You can deal each blow any number of times, in any order.For example, if $$$curX = 10$$$, $$$d = 7$$$, $$$h = 10$$$ then the number of heads changes to $$$13$$$ (you cut $$$7$$$ heads off, but then Zmei grows $$$10$$$ new ones), but if $$$curX = 10$$$, $$$d = 11$$$, $$$h = 100$$$ then number of heads changes to $$$0$$$ and Zmei Gorynich is considered defeated.Calculate the minimum number of blows to defeat Zmei Gorynich!You have to answer $$$t$$$ independent queries.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) – the number of queries. The first line of each query contains two integers $$$n$$$ and $$$x$$$ ($$$1 \le n \le 100$$$, $$$1 \le x \le 10^9$$$) — the number of possible types of blows and the number of heads Zmei initially has, respectively. The following $$$n$$$ lines of each query contain the descriptions of types of blows you can deal. The $$$i$$$-th line contains two integers $$$d_i$$$ and $$$h_i$$$ ($$$1 \le d_i, h_i \le 10^9$$$) — the description of the $$$i$$$-th blow.

For each query print the minimum number of blows you have to deal to defeat Zmei Gorynich.  If Zmei Gorynuch cannot be defeated print $$$-1$$$.

NoteIn the first query you can deal the first blow (after that the number of heads changes to $$$10 - 6 + 3 = 7$$$), and then deal the second blow.In the second query you just deal the first blow three times, and Zmei is defeated. In third query you can not defeat Zmei Gorynich. Maybe it's better to convince it to stop fighting?

let pow a n =
  let rec loop a n acc =
    if n = 0 then acc
    else if n mod 2 = 0 then loop (a * a) (n / 2) acc
    else loop (a * a) (n / 2) (acc * a) in
  loop a n 1

let ceil_div x y = if x > 0
  then (x + y - 1) / y
  else 0

let repeat f =
  let rec loop acc = function
    | 0 -> List.rev acc
    | n -> loop (f () :: acc) (n - 1) in
  loop []

let max_list key default ls =
  List.fold_left (fun x y -> if key x < key y then y else x) default ls

let solve x dhs =
  let (d, h) = max_list (fun (d, h) -> d - h) (List.hd dhs) dhs in
  let last = List.fold_left (fun x (d, h) -> max x d) (-1) dhs in
  if last < x && d - h <= 0
  then -1
  else 1 + ceil_div (x - last) (d - h)

let () =
  let t = Scanf.scanf "%d\n" (fun t -> t) in
  for tc = 1 to t do
    let n, x = Scanf.scanf "%d %d\n" (fun n x -> (n, x)) in
    let dhs = repeat (fun () -> Scanf.scanf "%d %d\n" (fun d h -> (d, h))) n in
    Printf.printf "%d\n" (solve x dhs);
    flush stdout
  done

let pow a n =
  let rec loop a n acc =
    if n = 0 then acc
    else if n mod 2 = 0 then loop (a * a) (n / 2) acc
    else loop (a * a) (n / 2) (acc * a) in
  loop a n 1

let ceil_div x y = (x + y - 1) / y

let repeat f =
  let rec loop acc = function
    | 0 -> List.rev acc
    | n -> loop (f () :: acc) (n - 1) in
  loop []

let max_list key default ls =
  List.fold_left (fun x y -> if key x < key y then y else x) default ls

let solve x dhs =
  let (d, h) = max_list (fun (d, h) -> d - h) (List.hd dhs) dhs in
  let last = List.fold_left (fun x (d, h) -> max x d) (-1) dhs in
  if d < x && d - h <= 0 then
    -1
  else
    1 + ceil_div (x - last) (d - h)

let () =
  let t = Scanf.scanf "%d\n" (fun t -> t) in
  for tc = 1 to t do
    let n, x = Scanf.scanf "%d %d\n" (fun n x -> (n, x)) in
    let dhs = repeat (fun () -> Scanf.scanf "%d %d\n" (fun d h -> (d, h))) n in
    Printf.printf "%d\n" (solve x dhs);
    flush stdout
  done

let pow a n =
  let rec loop a n acc =
    if n = 0 then acc
    else if n mod 2 = 0 then loop (a * a) (n / 2) acc
    else loop (a * a) (n / 2) (acc * a) in
  loop a n 1

let ceil_div x y = (x + y - 1) / y

let repeat f =
  let rec loop acc = function
    | 0 -> List.rev acc
    | n -> loop (f () :: acc) (n - 1) in
  loop []

let max_list key default ls =
  List.fold_left (fun x y -> if key x < key y then y else x) default ls

let solve x dhs =
  let (d, h) = max_list (fun (d, h) -> d - h) (List.hd dhs) dhs in
  if d - h <= 0 then
    -1
  else
    1 + ceil_div (x - d) (d - h)

let () =
  let t = Scanf.scanf "%d\n" (fun t -> t) in
  for tc = 1 to t do
    let n, x = Scanf.scanf "%d %d\n" (fun n x -> (n, x)) in
    let dhs = repeat (fun () -> Scanf.scanf "%d %d\n" (fun d h -> (d, h))) n in
    Printf.printf "%d\n" (solve x dhs);
    flush stdout
  done

let pow a n =
  let rec loop a n acc =
    if n = 0 then acc
    else if n mod 2 = 0 then loop (a * a) (n / 2) acc
    else loop (a * a) (n / 2) (acc * a) in
  loop a n 1

let ceil_div x y = (x + y - 1) / y

let repeat f =
  let rec loop acc = function
    | 0 -> List.rev acc
    | n -> loop (f () :: acc) (n - 1) in
  loop []

let max_list key default ls =
  List.fold_left (fun x y -> if key x < key y then y else x) default ls

let solve x dhs =
  let (d, h) = max_list (fun (d, h) -> d - h) (List.hd dhs) dhs in
  let last = List.fold_left (fun x (d, h) -> max x d) (-1) dhs in
  if d - h <= 0 then
    -1
  else
    1 + ceil_div (x - last) (d - h)

let () =
  let t = Scanf.scanf "%d\n" (fun t -> t) in
  for tc = 1 to t do
    let n, x = Scanf.scanf "%d %d\n" (fun n x -> (n, x)) in
    let dhs = repeat (fun () -> Scanf.scanf "%d %d\n" (fun d h -> (d, h))) n in
    Printf.printf "%d\n" (solve x dhs);
    flush stdout
  done

let pow a n =
  let rec loop a n acc =
    if n = 0 then acc
    else if n mod 2 = 0 then loop (a * a) (n / 2) acc
    else loop (a * a) (n / 2) (acc * a) in
  loop a n 1

let ceil_div x y = (x + y - 1) / y

let repeat f =
  let rec loop acc = function
    | 0 -> List.rev acc
    | n -> loop (f () :: acc) (n - 1) in
  loop []

let max_list key default ls =
  List.fold_left (fun x y -> if key x < key y then y else x) default ls

let solve x dhs =
  let (d, h) = max_list (fun (d, h) -> d - h) (List.hd dhs) dhs in
  let last = List.fold_left (fun x (d, h) -> max x d) (-1) dhs in
  if last < x && d - h <= 0 then
    -1
  else
    1 + ceil_div (x - last) (d - h)

let () =
  let t = Scanf.scanf "%d\n" (fun t -> t) in
  for tc = 1 to t do
    let n, x = Scanf.scanf "%d %d\n" (fun n x -> (n, x)) in
    let dhs = repeat (fun () -> Scanf.scanf "%d %d\n" (fun d h -> (d, h))) n in
    Printf.printf "%d\n" (solve x dhs);
    flush stdout
  done


The determinant of a matrix 2 × 2 is defined as follows:A matrix is called degenerate if its determinant is equal to zero. The norm ||A|| of a matrix A is defined as a maximum of absolute values of its elements.You are given a matrix . Consider any degenerate matrix B such that norm ||A - B|| is minimum possible. Determine ||A - B||.

The first line contains two integers a and b (|a|, |b| ≤ 109), the elements of the first row of matrix A.  The second line contains two integers c and d (|c|, |d| ≤ 109) the elements of the second row of matrix A.

Output a single real number, the minimum possible value of ||A - B||. Your answer is considered to be correct if its absolute or relative error does not exceed 10 - 9.

NoteIn the first sample matrix B is In the second sample matrix B is

open Printf
open Scanf

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

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

  let det = (long a) ** (long d) -- (long b) ** (long c) in
  if det = 0L then printf "0.0\n" else

    let (a,b,c,d) = (float a, float b, float c, float d) in
    let big = (max (max (abs_float a) (abs_float b)) (max (abs_float c) (abs_float d))) in
    let (a,b,c,d) = if (big = 0.0) then (a,b,c,d) else (a/.big, b/.big, c/.big, d/.big) in

    let lohi a b e =
      let x1 = (a -. e) *. (b -. e) in
      let x2 = (a +. e) *. (b -. e) in
      let x3 = (a -. e) *. (b +. e) in
      let x4 = (a +. e) *. (b +. e) in
      let hi = max (max x1 x2) (max x3 x4) in
      let lo = min (min x1 x2) (min x3 x4) in
      (lo,hi)
    in

    let intervals_intersect (lo1, hi1) (lo2, hi2) =
      if hi1 < lo2 then false
      else if hi2 < lo1 then false
      else true
    in

    let test e =
      intervals_intersect (lohi a d e) (lohi b c e)
    in

    let rec bsearch x y =
      let m = (x +. y) /. 2.0 in
      if abs_float (x -. y) < (1e-13) *. m then m
      else if test m then bsearch x m else bsearch m y
    in

    let answer = bsearch 0.0 1.0 in

    printf "%.10f\n" (answer *. big)

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let a = float (read_int()) in
  let b = float (read_int()) in
  let c = float (read_int()) in
  let d = float (read_int()) in

  let lohi a b e =
    let x1 = (a -. e) *. (b -. e) in
    let x2 = (a +. e) *. (b -. e) in
    let x3 = (a -. e) *. (b +. e) in
    let x4 = (a +. e) *. (b +. e) in
    let hi = max (max x1 x2) (max x3 x4) in
    let lo = min (min x1 x2) (min x3 x4) in
    (lo,hi)
  in

  let intervals_intersect (lo1, hi1) (lo2, hi2) =
    if hi1 < lo2 then false
    else if hi2 < lo1 then false
    else true
  in

  let test e =
    intervals_intersect (lohi a d e) (lohi b c e)
  in

  let rec bsearch x y n =
    let m = (x +. y) /. 2.0 in
    if n=0 then m
    else if test m then bsearch x m (n-1) else bsearch m y (n-1)
  in

  printf "%.10f\n" (bsearch 0.0 1e10 200)

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let a = float (read_int()) in
  let b = float (read_int()) in
  let c = float (read_int()) in
  let d = float (read_int()) in

  let big = (max (max (abs_float a) (abs_float b)) (max (abs_float c) (abs_float d))) in

  let (a,b,c,d) = if (big = 0.0) then (a,b,c,d) else (a/.big, b/.big, c/.big, d/.big) in

  let lohi a b e =
    let x1 = (a -. e) *. (b -. e) in
    let x2 = (a +. e) *. (b -. e) in
    let x3 = (a -. e) *. (b +. e) in
    let x4 = (a +. e) *. (b +. e) in
    let hi = max (max x1 x2) (max x3 x4) in
    let lo = min (min x1 x2) (min x3 x4) in
    (lo,hi)
  in

  let intervals_intersect (lo1, hi1) (lo2, hi2) =
    if hi1 < lo2 then false
    else if hi2 < lo1 then false
    else true
  in

  let test e =
    intervals_intersect (lohi a d e) (lohi b c e)
  in

  let rec bsearch x y =
    let m = (x +. y) /. 2.0 in
    if abs_float (x -. y) < 1e-15 then m
    else if test m then bsearch x m else bsearch m y
  in

  let answer = bsearch 0.0 1.0 in

  printf "%.9f\n" (answer *. big)

open Printf
open Scanf

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

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

  let det = (long a) ** (long d) -- (long b) ** (long c) in
  if det = 0L then printf "0.0\n" else

    let (a,b,c,d) = (float a, float b, float c, float d) in
    let big = (max (max (abs_float a) (abs_float b)) (max (abs_float c) (abs_float d))) in
    let (a,b,c,d) = if (big = 0.0) then (a,b,c,d) else (a/.big, b/.big, c/.big, d/.big) in

    let lohi a b e =
      let x1 = (a -. e) *. (b -. e) in
      let x2 = (a +. e) *. (b -. e) in
      let x3 = (a -. e) *. (b +. e) in
      let x4 = (a +. e) *. (b +. e) in
      let hi = max (max x1 x2) (max x3 x4) in
      let lo = min (min x1 x2) (min x3 x4) in
      (lo,hi)
    in

    let intervals_intersect (lo1, hi1) (lo2, hi2) =
      if hi1 < lo2 then false
      else if hi2 < lo1 then false
      else true
    in

    let test e =
      intervals_intersect (lohi a d e) (lohi b c e)
    in

    let rec bsearch x y =
      let m = (x +. y) /. 2.0 in
      if abs_float (x -. y) < 1e-13 then m
      else if test m then bsearch x m else bsearch m y
    in

    let answer = bsearch 0.0 1.0 in

    printf "%.9f\n" (answer *. big)


Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs?If Vasya presses the button such that some bulbs connected to it are already turned on, they do not change their state, i.e. remain turned on.

The first line of the input contains integers n and m (1 ≤ n, m ≤ 100) — the number of buttons and the number of bulbs respectively.  Each of the next n lines contains xi (0 ≤ xi ≤ m) — the number of bulbs that are turned on by the i-th button, and then xi numbers yij (1 ≤ yij ≤ m) — the numbers of these bulbs.

If it's possible to turn on all m bulbs print "YES", otherwise print "NO".

NoteIn the first sample you can press each button once and turn on all the bulbs. In the 2 sample it is impossible to turn on the 3-rd lamp.

let read1 () = Scanf.scanf "%d\n" ( fun x -> x );;
let read2 () = Scanf.scanf "%d %d\n" ( fun x y -> x, y );;
let read3 () = Scanf.scanf "%d %d %d\n" ( fun x y z -> x, y, z);;
let read x = (if x = 0 then Scanf.scanf "%d\n" else Scanf.scanf "%d ") ( fun x -> x );;

let (+$) x y =
  if x > max_int - y then max_int
  else x + y;;

let rec ( *$ ) x y =
  if y = 0 then 0 else
  if y mod 2 = 1 then x *$ (y-1) +$ x
  else let a = x *$ (y/2) in a +$ a;;

let rec loop n tab =
  if n >= 0 then
  let x = read n in
  tab.(x) <- true;
  loop (n-1) tab
  else ();;

let _ =
  let (n, m) = read2 () in
  let tab = Array.make (m+1) false in
  tab.(0) <- true;
  for i=1 to n do
    let k = Scanf.scanf "%d " ( fun x -> x ) in
    loop (k-1) tab
  done;
  Printf.printf "%s\n" (Array.fold_left ( fun a x -> if not x then "NO" else a ) "YES" tab);;

open Printf
open Scanf

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

let () =
  let (n,m) = read_pair () in
  let mark = Array.make m false in
  for i=0 to n-1 do
    let x = read_int () in
    for j=0 to x-1 do
      let y = -1 + read_int() in
      mark.(y) <- true;
    done
  done;

  if forall 0 (m-1) (fun i -> mark.(i)) then printf "YES\n" else printf "NO\n"

open Printf
open Scanf

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

let () =
  let (n,m) = read_pair () in
  let mark = Array.make m false in
  for i=0 to n-1 do
    let x = read_int () in
    for j=0 to x-1 do
      let y = -1 + read_int() in
      mark.(y) <- true;
    done
  done;

  if forall 0 (n-1) (fun i -> mark.(i)) then printf "YES\n" else printf "NO\n"


You are given an integer $$$n$$$. Check if $$$n$$$ has an odd divisor, greater than one (does there exist such a number $$$x$$$ ($$$x > 1$$$) that $$$n$$$ is divisible by $$$x$$$ and $$$x$$$ is odd).For example, if $$$n=6$$$, then there is $$$x=3$$$. If $$$n=4$$$, then such a number does not exist.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case contains one integer $$$n$$$ ($$$2 \le n \le 10^{14}$$$). Please note, that the input for some test cases won't fit into $$$32$$$-bit integer type, so you should use at least $$$64$$$-bit integer type in your programming language.

For each test case, output on a separate line:    "YES" if $$$n$$$ has an odd divisor, greater than one;  "NO" otherwise.  You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).

(** https://codeforces.com/problemset/problem/1475/A *)

let (+>>) = Int64.shift_right and
(+&) = Int64.logand

let odd64 n =
    n +& 1L = 1L

let has_odd_divisor n =
    let rec helper i =
		if odd64 i
		then (if i > 1L then true else false)
		else helper (i +>> 1) in
	helper n

let solve_n nb_cases =
    let rec helper i =
        if i > 0
        then (
            let n = read_line () |> Int64.of_string in
            (if has_odd_divisor n then "YES" else "NO")
            |> print_endline;
            helper (i-1)
        ) in
    helper nb_cases

let () =
    let nb_cases = read_int () in
    solve_n nb_cases


Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w":   "vvvv"  "vvvv"  "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows:  "vvvovvv"  "vvvovvv"  "vvvovvv"  "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov".

The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$.

Output a single integer, the wow factor of $$$s$$$.

NoteThe first example is explained in the legend.

let readString () = Scanf.scanf " %s" (fun s -> s)

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

let solve s =
  let n = String.length s in
  let l = Array.make (n+1) 0L in
  let r = Array.make (n+1) 0L in
  for i=0 to n-1 do
    l.(i+1) <- l.(i) ++ (if i > 0 && String.sub s (i-1) 2 = "vv" then 1L else 0L)
  done;
  let i = ref (n-1) in
  while !i >= 0 do
    r.(!i) <- r.(!i+1) ++ (if !i < n-1 && String.sub s !i 2 = "vv" then 1L else 0L);
    decr i
  done;
  let sum = ref 0L in
  for i=0 to n-1 do
    if s.[i] = 'o' then sum := !sum ++ l.(i)**r.(i)
  done;
  !sum

let main () =
  let s = readString () in
  Printf.printf "%Ld\n" (solve s)

let () = main ()


You are given a grid, consisting of $$$2$$$ rows and $$$n$$$ columns. Each cell of this grid should be colored either black or white.Two cells are considered neighbours if they have a common border and share the same color. Two cells $$$A$$$ and $$$B$$$ belong to the same component if they are neighbours, or if there is a neighbour of $$$A$$$ that belongs to the same component with $$$B$$$.Let's call some bicoloring beautiful if it has exactly $$$k$$$ components.Count the number of beautiful bicolorings. The number can be big enough, so print the answer modulo $$$998244353$$$.

The only line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 1000$$$, $$$1 \le k \le 2n$$$) — the number of columns in a grid and the number of components required.

Print a single integer — the number of beautiful bicolorings modulo $$$998244353$$$.

NoteOne of possible bicolorings in sample $$$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 (+$) = (+) 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
end open MyInt64

module ModCalc = struct
	(* let md = 1000000007L *)
	let md = 998244353L
	let validate v =
		(v + (labs(v) / md + 1L) * md) mod md
	let _add_mod md u v = u mod md + v mod md |> validate
	let _sub_mod md u v = u mod md - v mod md |> validate
	let _mul_mod md u v = u mod md * v mod md |> validate
	let rec pw u v =
		if v=0L then 1L
		else if v=1L then u mod md
		else let p = pw u (v/2L) in
			if v mod 2L = 0L then _mul_mod md p p
			else _mul_mod md (_mul_mod md p p) u
	let _inv md v = pw v (md-2L)
	let _div_mod md u v =
		_mul_mod md u (_inv md v)

	let (+%)  u v = _add_mod md u v
	let (-%)  u v = _sub_mod md u v
	let ( *%) u v = _mul_mod md u v
	let (/%)  u v = _div_mod md u v
	let rec pow x n = if n = 0L then 1L
		else if n mod 2L = 1L then x *% pow x (n-1L)
		else let w = pow x (n/2L) in w *% w
	let fact n = let rec f0 n v = if n = 0L then v else f0 (n-1L) (n*%v) in f0 n 1L
end open ModCalc

let make_3darray p q r d = Array.init (~|p) (fun _ -> Array.make_matrix (~|q) (~|r) d)
let make_4darray p q r s d = Array.init (~|p) (fun _ -> make_3darray q r s d)
let (@~) a (i,j,k,l) = try a.(~|i).(~|j).(~|k).(~|l) with | Invalid_argument _ -> 0L
let (<@~) a (i,j,k,l,v) = a.(~|i).(~|j).(~|k).(~|l) <- v
let dp = make_4darray 1024L 2048L 2L 2L 0L

let () =
	let n,k = get_2_i64 0 in
	dp.(1).(1).(0).(0) <- 1L;
	dp.(1).(2).(0).(1) <- 1L;
	dp.(1).(2).(1).(0) <- 1L;
	dp.(1).(1).(1).(1) <- 1L;
	rep 2L n (fun i ->
		rep 1L (i*2L+2L) (fun j ->
			dp<@~(i,j,0L,0L,(
				(dp@~(i-1L,j,0L,0L))
				+% (dp@~(i-1L,j-1L,0L,1L))
				+% (dp@~(i-1L,j-1L,1L,0L))
				+% (dp@~(i-1L,j-2L,1L,1L))
			));
			dp<@~(i,j,1L,1L,(
				(dp@~(i-1L,j,1L,1L))
				+% (dp@~(i-1L,j-1L,0L,1L))
				+% (dp@~(i-1L,j-1L,1L,0L))
				+% (dp@~(i-1L,j-2L,0L,0L))
			));
			dp<@~(i,j,1L,0L,(
				(dp@~(i-1L,j,1L,0L))
				+% (dp@~(i-1L,j-1L,1L,1L))
				+% (dp@~(i-1L,j-1L,0L,0L))
				+% (dp@~(i-1L,j-2L,0L,1L))
			));
			dp<@~(i,j,0L,1L,(
				(dp@~(i-1L,j,0L,1L))
				+% (dp@~(i-1L,j-1L,1L,1L))
				+% (dp@~(i-1L,j-1L,0L,0L))
				+% (dp@~(i-1L,j-2L,1L,0L))
			));
			`Ok
		);
		`Ok
	);
	printf "%Ld\n" (
		(dp@~(n,k,0L,0L))
		+% (dp@~(n,k,0L,1L))
		+% (dp@~(n,k,1L,0L))
		+% (dp@~(n,k,1L,1L))
	)

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 (+$) = (+) 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
end open MyInt64

module ModCalc = struct
	(* let md = 1000000007L *)
	let md = 998244353L
	let validate v =
		(v + (labs(v) / md + 1L) * md) mod md
	let _add_mod md u v = u mod md + v mod md |> validate
	let _sub_mod md u v = u mod md - v mod md |> validate
	let _mul_mod md u v = u mod md * v mod md |> validate
	let rec pw u v =
		if v=0L then 1L
		else if v=1L then u mod md
		else let p = pw u (v/2L) in
			if v mod 2L = 0L then _mul_mod md p p
			else _mul_mod md (_mul_mod md p p) u
	let _inv md v = pw v (md-2L)
	let _div_mod md u v =
		_mul_mod md u (_inv md v)

	let (+%)  u v = _add_mod md u v
	let (-%)  u v = _sub_mod md u v
	let ( *%) u v = _mul_mod md u v
	let (/%)  u v = _div_mod md u v
	let rec pow x n = if n = 0L then 1L
		else if n mod 2L = 1L then x *% pow x (n-1L)
		else let w = pow x (n/2L) in w *% w
	let fact n = let rec f0 n v = if n = 0L then v else f0 (n-1L) (n*%v) in f0 n 1L
end open ModCalc

let make_3darray p q r d = Array.init (~|p) (fun _ -> Array.make_matrix (~|q) (~|r) d)
let make_4darray p q r s d = Array.init (~|p) (fun _ -> make_3darray q r s d)
let (@~) a (i,j,k,l) = try a.(~|i).(~|j).(~|k).(~|l) with | Invalid_argument _ -> 0L
let (<@~) a (i,j,k,l,v) = a.(~|i).(~|j).(~|k).(~|l) <- v
let dp = make_4darray 1024L 2048L 2L 2L 0L

let () =
	let n,k = get_2_i64 0 in
	dp.(1).(1).(0).(0) <- 1L;
	dp.(1).(2).(0).(1) <- 1L;
	dp.(1).(2).(1).(0) <- 1L;
	dp.(1).(1).(1).(1) <- 1L;
	rep 2L n (fun i ->
		rep 1L (i*2L+2L) (fun j ->
			dp<@~(i,j,0L,0L,(
				(dp@~(i-1L,j,0L,0L))
				+% (dp@~(i-1L,j-1L,0L,1L))
				+% (dp@~(i-1L,j-1L,1L,0L))
				+% (dp@~(i-1L,j-1L,1L,1L))
			));
			dp<@~(i,j,1L,1L,(
				(dp@~(i-1L,j,1L,1L))
				+% (dp@~(i-1L,j-1L,0L,1L))
				+% (dp@~(i-1L,j-1L,1L,0L))
				+% (dp@~(i-1L,j-1L,0L,0L))
			));
			dp<@~(i,j,1L,0L,(
				(dp@~(i-1L,j,1L,0L))
				+% (dp@~(i-1L,j-1L,1L,1L))
				+% (dp@~(i-1L,j-1L,0L,0L))
				+% (dp@~(i-1L,j-2L,0L,1L))
			));
			dp<@~(i,j,0L,1L,(
				(dp@~(i-1L,j,0L,1L))
				+% (dp@~(i-1L,j-1L,1L,1L))
				+% (dp@~(i-1L,j-1L,0L,0L))
				+% (dp@~(i-1L,j-2L,1L,0L))
			));
			`Ok
		);
		`Ok
	);
	printf "%Ld\n" (
		(dp@~(n,k,0L,0L))
		+% (dp@~(n,k,0L,1L))
		+% (dp@~(n,k,1L,0L))
		+% (dp@~(n,k,1L,1L))
	)


On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost of item xj is axj + xj·k for 1 ≤ j ≤ k. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor k.Sagheer wants to buy as many souvenirs as possible without paying more than S Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task?

The first line contains two integers n and S (1 ≤ n ≤ 105 and 1 ≤ S ≤ 109) — the number of souvenirs in the market and Sagheer's budget. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 105) — the base costs of the souvenirs.

On a single line, print two integers k, T — the maximum number of souvenirs Sagheer can buy and the minimum total cost to buy these k souvenirs.

NoteIn the first example, he cannot take the three items because they will cost him [5, 9, 14] with total cost 28. If he decides to take only two items, then the costs will be [4, 7, 11]. So he can afford the first and second items.In the second example, he can buy all items as they will cost him [5, 10, 17, 22].In the third example, there is only one souvenir in the market which will cost him 8 pounds, so he cannot buy it.

(* start:1:36 done: 1:55*)

let ( ** ) a b = Int64.mul a b
let ( ++ ) a b = Int64.add a b
let ( -- ) a b = Int64.sub a b
let ( // ) a b = Int64.div a b
let ( %% ) a b = Int64.rem a b

let long x = Int64.of_int x
let short x = Int64.to_int x

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

open Printf
open Scanf

let read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let s = long (read_int ()) in
  let a = Array.init n (fun _ -> long (read_int())) in
  let c = Array.make n 0L in

  let min_cost k =
  (* the minimum cost to buy k things *)
    for i=0 to n-1 do
      c.(i) <- a.(i) ++ (long k)**(long (i+1))
    done;

    Array.sort compare c;

    sum 0 (k-1) (fun i -> c.(i))
  in

  let rec bsearch lo c_lo hi c_hi =
  (*  min_cost lo <= s, and min_cost hi > s *)
    if lo + 1 = hi then (lo,c_lo)
    else
      let m = (lo+hi)/2 in
      let c_m = min_cost m in
      if c_m <= s then bsearch m c_m hi c_hi else bsearch lo c_lo m c_m
  in

  let rec run_search hi0 c_hi0 =
    (* c_hi0 <= s *)
    let hi1 = min n (2*(max 1 hi0)) in
    let c_hi1 = min_cost hi1 in
    if c_hi1 > s then bsearch hi0 c_hi0 hi1 c_hi1 else run_search hi1 c_hi1
  in

  let cost_of_all = min_cost n in

  let (k, c_k) = if cost_of_all <= s then (n, cost_of_all) else run_search 0 0L in

  printf "%d %Ld\n" k c_k


There is a special offer in Vasya's favourite supermarket: if the customer buys $$$a$$$ chocolate bars, he or she may take $$$b$$$ additional bars for free. This special offer can be used any number of times.Vasya currently has $$$s$$$ roubles, and he wants to get as many chocolate bars for free. Each chocolate bar costs $$$c$$$ roubles. Help Vasya to calculate the maximum possible number of chocolate bars he can get!

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of testcases. Each of the next $$$t$$$ lines contains four integers $$$s, a, b, c~(1 \le s, a, b, c \le 10^9)$$$ — the number of roubles Vasya has, the number of chocolate bars you have to buy to use the special offer, the number of bars you get for free, and the cost of one bar, respectively.

Print $$$t$$$ lines. $$$i$$$-th line should contain the maximum possible number of chocolate bars Vasya can get in $$$i$$$-th test.

NoteIn the first test of the example Vasya can buy $$$9$$$ bars, get $$$3$$$ for free, buy another bar, and so he will get $$$13$$$ bars.In the second test Vasya buys $$$1000000000$$$ bars and gets $$$1000000000000000000$$$ for free. So he has $$$1000000001000000000$$$ bars.

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 s,a,b,c = get_4_i64 0 in
		let buy = s / c in
		let d = buy / a in
		(d*(a+b) + (buy - d*a)) |> printf "%Ld\n";
		(* printf "%Ld %Ld\n" buy d; *)
		`Ok
	)

let scan_int () = Scanf.scanf " %d" (fun x -> x);;
let scan_string () = Scanf.scanf " %s" (fun x -> x);;
let psp () = print_string " ";;
let b2i x = if x == true then 1 else 0;;

open Int64;;
let t = scan_int();;

let f s a b c =
  let c1 = mul a c in
  let ile = div s c1 in
  add (mul ile (add a b)) (div (sub s (mul ile c1)) c);;

for i = 0 to t - 1 do
  let a = Int64.of_int(scan_int()) and
      b = Int64.of_int(scan_int()) and
      c = Int64.of_int(scan_int()) and
      d = Int64.of_int(scan_int()) in
  print_string(Int64.to_string(f a b c d)); print_newline();
done;;


Little Vitaly loves different algorithms. Today he has invented a new algorithm just for you. Vitaly's algorithm works with string s, consisting of characters "x" and "y", and uses two following operations at runtime:  Find two consecutive characters in the string, such that the first of them equals "y", and the second one equals "x" and swap them. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string.  Find in the string two consecutive characters, such that the first of them equals "x" and the second one equals "y". Remove these characters from the string. If there are several suitable pairs of characters, we choose the pair of characters that is located closer to the beginning of the string. The input for the new algorithm is string s, and the algorithm works as follows:  If you can apply at least one of the described operations to the string, go to step 2 of the algorithm. Otherwise, stop executing the algorithm and print the current string.  If you can apply operation 1, then apply it. Otherwise, apply operation 2. After you apply the operation, go to step 1 of the algorithm. Now Vitaly wonders, what is going to be printed as the result of the algorithm's work, if the input receives string s.

The first line contains a non-empty string s.  It is guaranteed that the string only consists of characters "x" and "y". It is guaranteed that the string consists of at most 106 characters. It is guaranteed that as the result of the algorithm's execution won't be an empty string.

In the only line print the string that is printed as the result of the algorithm's work, if the input of the algorithm input receives string s.

NoteIn the first test the algorithm will end after the first step of the algorithm, as it is impossible to apply any operation. Thus, the string won't change.In the second test the transformation will be like this:  string "yxyxy" transforms into string "xyyxy";  string "xyyxy" transforms into string "xyxyy";  string "xyxyy" transforms into string "xxyyy";  string "xxyyy" transforms into string "xyy";  string "xyy" transforms into string "y". As a result, we've got string "y". In the third test case only one transformation will take place: string "xxxxxy" transforms into string "xxxx". Thus, the answer will be string "xxxx".

(* Codeforces 252B RazborCode 255B *)

open Filename;;
open String;;

(* you can use either gr or rdln but not both *)
let use_input_txt = false;;
let fn = (Filename.dirname Filename.current_dir_name);;
let filename = Filename.concat "." "input.txt";;
let cin = if use_input_txt then Scanf.Scanning.open_in filename
	else Scanf.Scanning.stdin;;

let cout = open_out "output.txt";;
let gr () = Scanf.bscanf cin " %d" (fun i -> i);;
let grf () = Scanf.scanf " %f" (fun i -> i);;
let grl () = Scanf.scanf " %Ld" (fun i -> i);;
let rdln() = input_line Pervasives.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;;

let rec cntxy s idx cntx cnty =
	if idx >= (length s) then (cntx, cnty)
	else begin
		let c = s.[idx] in
		let id1 = idx +1 in
		if c = 'x' then
			cntxy s id1 (cntx + 1) cnty
		else cntxy s id1 cntx (cnty + 1)
	end;;

let rec reppri s n = match n with
	| 0 -> ()
	| _ -> begin
				print_string s;
				reppri s (n -1)
			end;;

let main () =
	let s = rdln() in
	let (cx, cy) = cntxy s 0 0 0 in
	begin
		(* print_string " cx,cy = "; print_int cx; print_string " "; print_int *)
		(* cy;                                                                 *)
		if cx < cy then reppri "y" (cy - cx)
			else reppri "x" (cx - cy);
		print_newline()
	end;;

main();;

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

let explode s =
    let rec exp i l =
        if i < 0 then l else exp (i - 1) (s.[i] :: l)
    in exp (String.length s - 1) [] ;;

let s = explode (read_string ()) ;;

let count s =
    let rec loop (x, y) = function
        | [] -> (x, y)
        | h :: t ->
            if h = 'x' then loop (x + 1, y) t
            else loop (x, y + 1) t
    in loop (0, 0) s ;;

let result =
    let (x, y) = count s in
    if x > y then String.make (x - y) 'x'
    else String.make (y - x) 'y' ;;

Printf.printf "%s\n" result ;;

let () =
  let s = read_line() in
  let c = Array.make 2 0 in
    for i = 0 to (String.length s)-1 do
      let w = if s.[i] = 'x' then 0 else 1 in
	c.(w) <- c.(w) + 1
    done;

    let b = if c.(0) > c.(1) then 'x' else 'y' in
    let n = abs (c.(0) - c.(1)) in
      for i=0 to n-1 do
	print_char b
      done;
      print_newline()


For the New Year, Polycarp decided to send postcards to all his $$$n$$$ friends. He wants to make postcards with his own hands. For this purpose, he has a sheet of paper of size $$$w \times h$$$, which can be cut into pieces.Polycarp can cut any sheet of paper $$$w \times h$$$ that he has in only two cases:   If $$$w$$$ is even, then he can cut the sheet in half and get two sheets of size $$$\frac{w}{2} \times h$$$;  If $$$h$$$ is even, then he can cut the sheet in half and get two sheets of size $$$w \times \frac{h}{2}$$$; If $$$w$$$ and $$$h$$$ are even at the same time, then Polycarp can cut the sheet according to any of the rules above.After cutting a sheet of paper, the total number of sheets of paper is increased by $$$1$$$.Help Polycarp to find out if he can cut his sheet of size $$$w \times h$$$ at into $$$n$$$ or more pieces, using only the rules described above.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing three integers $$$w$$$, $$$h$$$, $$$n$$$ ($$$1 \le w, h \le 10^4, 1 \le n \le 10^9$$$) — the width and height of the sheet Polycarp has and the number of friends he needs to send a postcard to.

For each test case, output on a separate line:    "YES", if it is possible to cut a sheet of size $$$w \times h$$$ into at least $$$n$$$ pieces;  "NO" otherwise.  You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).

NoteIn the first test case, you can first cut the $$$2 \times 2$$$ sheet into two $$$2 \times 1$$$ sheets, and then cut each of them into two more sheets. As a result, we get four sheets $$$1 \times 1$$$. We can choose any three of them and send them to our friends.In the second test case, a $$$3 \times 3$$$ sheet cannot be cut, so it is impossible to get two sheets.In the third test case, you can cut a $$$5 \times 10$$$ sheet into two $$$5 \times 5$$$ sheets.In the fourth test case, there is no need to cut the sheet, since we only need one sheet.In the fifth test case, you can first cut the $$$1 \times 4$$$ sheet into two $$$1 \times 2$$$ sheets, and then cut each of them into two more sheets. As a result, we get four sheets $$$1 \times 1$$$.

(** https://codeforces.com/problemset/problem/1472/A *)

let max_friends width height =
    let rec helper num i =
        if num land 1 = 1
        then i
        else helper (num lsr 1) (i+1) in
    let cut_width = helper width 0 and
    cut_height = helper height 0 in
    let rec pow2 i res =
        if i = 0
        then res
        else pow2 (i-1) (res lsl 1) in
    pow2 (cut_width+cut_height) 1

let solve_n nb_cases =
    let rec helper i =
        if i > 0
        then (
            let [width; height; friends] =
                read_line ()
                |> Str.split (Str.regexp " ")
                |> List.map int_of_string in
            (if max_friends width height >= friends then "YES" else "NO")
            |> print_endline;
            helper (i-1)
        ) in
    helper nb_cases

let () =
    let nb_cases = read_int () in
    solve_n nb_cases

(* #load "str.cma" *)
module Stdlib = Pervasives;;
(* let std_inp = Stdlib.open_in "input.txt";; *)
let std_inp = Stdlib.stdin;;
let std_outp = Stdlib.stdout;;

let identity x = x;;
let tup3 x1 x2 x3 = (x1, x2, x3);;

let rec slices n =
  if n mod 2 == 0 then 1 + slices (n / 2)
  else 0;;

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

let solution inp outp =
  let (w, h, n) = let line = input_line inp in Scanf.sscanf line "%d %d %d" tup3 in
  let w_count = slices w and h_count = slices h in
  (* let _ = Printf.printf "W: %d; H: %d; N: %d\n" w h n in *)
  (* let _ = Printf.printf "WC: %d; HC: %d\n" w_count h_count in *)
  let _ =
    if (pow 2 w_count) * (pow 2 h_count) >= n then Printf.printf "YES\n"
    else Printf.printf "NO\n"
  in
  ();;
let rec run_test = function
| (0, _, _) -> ()
| (t, inp, outp) ->
  let _ = solution inp outp in
  run_test (t - 1, inp, outp);;

let (_:unit) =
  let inp = std_inp and outp = std_outp in
  let tests_count = let line = input_line inp in Scanf.sscanf line "%d" identity in
  let _ = run_test (tests_count, inp, outp) in
  ();;


Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x, y) either y = 0, or there is a cube with coordinates (x - 1, y - 1), (x, y - 1) or (x + 1, y - 1).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109 + 9.

The first line contains number m (2 ≤ m ≤ 105). The following m lines contain the coordinates of the cubes xi, yi ( - 109 ≤ xi ≤ 109, 0 ≤ yi ≤ 109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place.

In the only line print the answer to the problem.

open Printf
open Scanf

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

let ( ** ) a b = Int64.mul a b
let ( ++ ) a b = Int64.add a b
let ( -- ) a b = Int64.sub a b
let ( // ) a b = Int64.div a b
let ( %% ) a b = Int64.rem a b

let long x = Int64.of_int x

let mm = 1_000_000_009L

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_pair () = let u = read_int() in (u,read_int())
let () =
  let m = read_int () in
  let cube = Array.init m (fun _ -> read_pair()) in

  let h = Hashtbl.create 10 in

  for i=0 to m-1 do
    Hashtbl.replace h cube.(i) i
  done;

  let btoi p = if p then 1 else 0 in

  let count_support (x,y) =
    if y=0 || not (Hashtbl.mem h (x,y)) then 3 else
      btoi (Hashtbl.mem h (x-1,y-1))
      + btoi (Hashtbl.mem h (x,y-1))
      + btoi (Hashtbl.mem h (x+1,y-1))
  in

  let removable p =
    (* returns true if p is removable in the current configuration *)
    let (x,y) = cube.(p) in
    (count_support (x-1,y+1)>1)
    && (count_support (x,y+1)>1)
    && (count_support (x+1,y+1)>1)
  in

  let remove_it p set =
    let (x,y) = cube.(p) in
    Hashtbl.remove h (x,y);
    let update_set (xx,yy) set =
      if not (Hashtbl.mem h (xx,yy)) then set else
	let i = Hashtbl.find h (xx,yy) in
	if removable i then Iset.add i set else Iset.remove i set
    in
    let set = update_set (x-1,y-1) set in
    let set = update_set (x,y-1) set in
    let set = update_set (x+1,y-1) set in
    let set = update_set (x-2,y) set in
    let set = update_set (x-1,y) set in
    let set = update_set (x+1,y) set in
    let set = update_set (x+2,y) set in
    set
  in

  let rec build_removable i ac = if i=m then ac else
      let ac = if removable i then Iset.add i ac else ac in
      build_removable (i+1) ac
  in

  let initial_set = build_removable 0 Iset.empty in

  let rec simulate move_num set ac = if move_num = m then ac else
      let remove_me =
	if move_num land 1 = 0 then Iset.max_elt set else Iset.min_elt set
      in
      let set = Iset.remove remove_me set in
      let set = remove_it remove_me set in
      simulate (move_num+1) set (remove_me::ac)
  in

  let li = simulate 0 initial_set [] in

  let rec eval li ac = match li with [] -> ac
    | d::tail ->
      let ac = (ac ** (long m) ++ (long d)) %% mm in
      eval tail ac
  in

  let answer = eval (List.rev li) 0L in

  printf "%Ld\n" answer

open Printf
open Scanf

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

let ( ** ) a b = Int64.mul a b
let ( ++ ) a b = Int64.add a b
let ( -- ) a b = Int64.sub a b
let ( // ) a b = Int64.div a b
let ( %% ) a b = Int64.rem a b

let long x = Int64.of_int x

let mm = 1_000_000_009L

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_pair () = let u = read_int() in (u,read_int())
let () =
  let m = read_int () in
  let cube = Array.init m (fun _ -> read_pair()) in

  let h = Hashtbl.create 10 in

  for i=0 to m-1 do
    Hashtbl.replace h cube.(i) i
  done;

  let btoi p = if p then 1 else 0 in

  let count_support (x,y) =
    if y=0 || not (Hashtbl.mem h (x,y)) then 3 else
      btoi (Hashtbl.mem h (x-1,y-1))
      + btoi (Hashtbl.mem h (x,y-1))
      + btoi (Hashtbl.mem h (x+1,y-1))
  in

  let removable p =
    (* returns true if p is removable in the current configuration *)
    let (x,y) = cube.(p) in
    (count_support (x-1,y+1)>1)
    && (count_support (x,y+1)>1)
    && (count_support (x+1,y+1)>1)
  in

  let remove_it p set =
    let (x,y) = cube.(p) in
    Hashtbl.remove h (x,y);
    let update_set (xx,yy) set =
      if not (Hashtbl.mem h (xx,yy)) then set else
	let i = Hashtbl.find h (xx,yy) in
	if removable i then Iset.add i set else Iset.remove i set
    in
    let set = update_set (x-1,y-1) set in
    let set = update_set (x,y-1) set in
    let set = update_set (x+1,y-1) set in
    set
  in

  let rec build_removable i ac = if i=m then ac else
      let ac = if removable i then Iset.add i ac else ac in
      build_removable (i+1) ac
  in

  let initial_set = build_removable 0 Iset.empty in

  let rec simulate move_num set ac = if move_num = m then ac else
      let remove_me =
	if move_num land 1 = 0 then Iset.max_elt set else Iset.min_elt set
      in
      let set = Iset.remove remove_me set in
      let set = remove_it remove_me set in
      simulate (move_num+1) set (remove_me::ac)
  in

  let li = simulate 0 initial_set [] in

  let rec eval li ac = match li with [] -> ac
    | d::tail ->
      let ac = (ac ** (long m) ++ (long d)) %% mm in
      eval tail ac
  in

  let answer = eval (List.rev li) 0L in

  printf "%Ld\n" answer

open Printf
open Scanf

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

let ( ** ) a b = Int64.mul a b
let ( ++ ) a b = Int64.add a b
let ( -- ) a b = Int64.sub a b
let ( // ) a b = Int64.div a b
let ( %% ) a b = Int64.rem a b

let long x = Int64.of_int x

let mm = 1_000_000_009L

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_pair () = let u = read_int() in (u,read_int())
let () =
  let m = read_int () in
  let cube = Array.init m (fun _ -> read_pair()) in

  let h = Hashtbl.create 10 in

  for i=0 to m-1 do
    Hashtbl.replace h cube.(i) i
  done;

  let btoi p = if p then 1 else 0 in

  let count_support (x,y) =
    if y=0 || not (Hashtbl.mem h (x,y)) then 3 else
      btoi (Hashtbl.mem h (x-1,y-1))
      + btoi (Hashtbl.mem h (x,y-1))
      + btoi (Hashtbl.mem h (x+1,y-1))
  in

  let removable p =
    (* returns true if p is removable in the current configuration *)
    let (x,y) = cube.(p) in
    (count_support (x-1,y+1)>1)
    && (count_support (x,y+1)>1)
    && (count_support (x+1,y+1)>1)
  in

  let remove_it p set =
    let (x,y) = cube.(p) in
    Hashtbl.remove h (x,y);
    if y=0 then set else
      let update_set (xx,yy) set =
	if not (Hashtbl.mem h (xx,yy)) then set else
	  let i = Hashtbl.find h (xx,yy) in
	  if removable i then Iset.add i set else Iset.remove i set
      in
      let set = update_set (x-1,y-1) set in
      let set = update_set (x,y-1) set in
      let set = update_set (x+1,y-1) set in
      set
  in

  let rec build_removable i ac = if i=m then ac else
      let ac = if removable i then Iset.add i ac else ac in
      build_removable (i+1) ac
  in

  let initial_set = build_removable 0 Iset.empty in

  let rec simulate move_num set ac = if move_num = m then ac else
      let remove_me =
	if move_num land 1 = 0 then Iset.max_elt set else Iset.min_elt set
      in
      let set = Iset.remove remove_me set in
      let set = remove_it remove_me set in
      simulate (move_num+1) set (remove_me::ac)
  in

  let li = simulate 0 initial_set [] in

  let rec eval li ac = match li with [] -> ac
    | d::tail ->
      let ac = (ac ** (long m) ++ (long d)) %% mm in
      eval tail ac
  in

  let answer = eval (List.rev li) 0L in

  printf "%Ld\n" answer


The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.The head of the SSU OPTC is recently gathering teams to participate in the world championship. Each team must consist of exactly three people, at that, any person cannot be a member of two or more teams. What maximum number of teams can the head make if he wants each team to participate in the world championship with the same members at least k times?

The first line contains two integers, n and k (1 ≤ n ≤ 2000; 1 ≤ k ≤ 5). The next line contains n integers: y1, y2, ..., yn (0 ≤ yi ≤ 5), where yi shows the number of times the i-th person participated in the ACM ICPC world championship.

Print a single number — the answer to the problem.

NoteIn the first sample only one team could be made: the first, the fourth and the fifth participants.In the second sample no teams could be created.In the third sample two teams could be created. Any partition into two teams fits.

let read () = Scanf.scanf "%d " (fun n -> n)

let input () =
    let n = read () in
    let k = read () in
    let rec loop i list =
        if i < n
        then
            let temp = read () in
            loop (i + 1) (temp :: list)
        else
            (k, list)
    in loop 0 []

let solve (k, list) =
    let qualified = List.filter (fun m -> m + k <= 5) list in
    List.length qualified / 3

let print result = Printf.printf "%d\n" result
let () = print (solve (input ()))

let read_int()=Scanf.scanf "%d " (fun x->x);;
let n=read_int();;
let k=read_int();;
let nb=ref 0;;
for i=1 to n-1 do
   let x=read_int() in
   if x<=5-k then incr nb
done;;
let a=Scanf.scanf "%d" (fun x->x) in if a<=5-k then incr nb;;
print_int( (!nb)/3);;

let k = List.nth (read_line () |> Str.split (Str.regexp " +") ) 1 |> int_of_string and
    ys = read_line() |> Str.split (Str.regexp " +") |> List.map int_of_string in

    ys |> List.map (fun x -> x + k) |> List.filter (fun x -> x <=5) |> List.length |> fun x -> x / 3 |> print_int

(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)

open Printf
open Scanf
open Array

module S = String
module Q = Queue
module T = Stack
module L = List

(* misc *)
let neg_compare x y = - compare x y
let min3 a b c = min a (min b c)
let mid3 a b c = if a < b then max a (min b c) else max b (min a c)
let max3 a b c = max a (max b c)
let min4 a b c d = min (min a b) (min c d)
let max4 a b c d = max (max a b) (max c d)
let itb a = a <> 0
let bti b = if b then 1 else 0
(* int *)
let intsqrt n =
  if n < 0 then raise (Invalid_argument "sqrt of negative int") else
  let rec bs a b = begin
    if b - a = 1 then a else
    let mid = (a+b)/2 in
    if mid*mid <= n then bs mid b else bs a mid
  end in
  bs 0 (1 lsl 31)
(* float *)
let round f = truncate (f +. 0.5)
let inv_float f = 1. /. f
(* functional *)
let id x = x
let const x _ = x
let (|>) x f = f x
let (^>) x f = f x
let (@@) a b = a b
let on g f a b = g (f a) (f b)
let rec fix f = f (fun x -> fix f x)
let ift cond a = if cond then a
let ifte cond a b = if cond then a else b
let rec for_ i len c f = if i = len then c else for_ (i+1) len (f i c) f
(* predicate *)
let is_odd x = x land 1 = 1
let is_even x = x land 1 = 0
(* option *)
let is_none = function | Some _ -> false | None -> true
let is_some = function | Some _ -> true | None -> false
let default x = function Some y -> y | None -> x
(* ref *)
let (+=) a b = a := !a + b
let (-=) a b = a := !a - b
let ( *= ) a b = a := !a * b
let assign_min x y = x := min !x y
let assign_max x y = x := max !x y
(* array *)
let set_min x i v = x.(i) <- min x.(i) v
let set_max x i v = x.(i) <- max x.(i) v
let swap arr i j = let t = arr.(i) in arr.(i) <- arr.(j); arr.(j) <- t
(* tuple *)
let (+:) (a,b) (c,d) = (a+c,b+d)
let (-:) (a,b) (c,d) = (a-c,b-d)
(* Arithmetic *)
let negate x = -x
let rec factorial n = if n = 0 then 1 else n * factorial (n-1)
let rec gcd a b = if b = 0 then a else gcd b (a mod b)
let rec extgcd a b =
  if b = 0 then 1,0,a else
  let x,y,g = extgcd b (a mod b) in
  y,x-(a/b)*y,g
let rec pow x n = if n = 0 then 1 else
  let n' = n/2 in
  let p = pow x n' in
  if is_odd n then x*p*p else p*p
let rec modpow m x n =
  if n = 0 then 1 else
  let n' = n/2 in
  let p = modpow m x n' in
  if is_even n then (p*p mod m) else
  (x*(p*p mod m) mod m)
let modinv m i = let _,x,_ = extgcd m i in x
(* IO *)
let is_digit c =
  let i = int_of_char c in
  48 <= i && i < 58
let is_space c = c = ' ' || c = '\n' || c = '\t' || c = '\r'
let read_char () = try input_char stdin with End_of_file -> '\000'
let rec read_letter () =
  let c = read_char() in
  if is_space c then read_letter() else c
let read_int () =
  let digit c = int_of_char c - 48 in
  let rec read n =
    let c = read_char() in
    if is_digit c then read (10*n + (digit c)) else
    n
  in
  let rec run c =
    if is_digit c then read (digit c) else
    if c = '-' then begin
      let c = read_char() in
      if is_digit c then -read (digit c) else run c
    end else
    if c = '\000' then 0 else
    run (read_char())
  in
  run (read_char())
let read_float () =
  let digit c = float (int_of_char c - 48) in
  let rec read_decimial m f =
    let c = read_char () in
    if is_digit c then read_decimial (m /. 10.) (f +. m *. digit c) else f
  in
  let rec read_integral n =
    let c = read_char () in
    if is_digit c then read_integral (10. *. n +. digit c) else
    if c = '.' then n +. read_decimial 0.1 0.0 else
    n
  in
  let rec run c = begin
    if is_digit c then read_integral (digit c) else
    if c = '-' then begin
      let c = read_char() in
      if is_digit c then -. read_integral (digit c) else
      run c
    end else
    if c = '.' then read_decimial 0.1 0.0 else
    if c = '\000' then 0.0 else
    run (read_char())
  end in
  run (read_char())
let read_word () =
  let open Buffer in
  let buf = create 1_000_000 in
  let rec read c =
    if is_space c || c = '\000' then contents buf else begin
      add_char buf c;
      read (read_char())
    end
  in
  let rec run c =
    if is_space c then run (read_char()) else
    if c = '\000' then "" else
    read c
  in
  run (read_char())
let read_line () =
  let open Buffer in
  let buf = create 1_000_000 in
  let rec run c =
    if c = '\n' || c = '\000' then contents buf else begin
      add_char buf c;
      run (read_char())
    end
  in
  run (read_char())
let newline () = print_newline()
let print_tuple s (x,y) = printf s x y
let print_array s arr = Array.iter (printf s) arr; print_newline()
let print_matrix s mat = Array.iter (print_array s) mat
let print_list s lis = List.iter (printf s) lis; print_newline()
;;

let _ =
  let len = read_int() in
  let k = read_int() in
  let arr = init len (fun i -> read_int() ) in
  sort compare arr;
  let rec upper_bound a b =
    if b - a = 1 then b else
    let mid = (a+b)/2 in
    if arr.(mid) <= 5-k then upper_bound mid b else upper_bound a mid
  in
  printf "%d\n" ((upper_bound (-1) len)/3)


Monocarp has just learned a new card trick, and can't wait to present it to you. He shows you the entire deck of $$$n$$$ cards. You see that the values of cards from the topmost to the bottommost are integers $$$a_1, a_2, \dots, a_n$$$, and all values are different.Then he asks you to shuffle the deck $$$m$$$ times. With the $$$j$$$-th shuffle, you should take $$$b_j$$$ topmost cards and move them under the remaining $$$(n - b_j)$$$ cards without changing the order.And then, using some magic, Monocarp tells you the topmost card of the deck. However, you are not really buying that magic. You tell him that you know the topmost card yourself. Can you surprise Monocarp and tell him the topmost card before he shows it?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of cards in the deck. The second line contains $$$n$$$ pairwise distinct integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$) — the values of the cards. The third line contains a single integer $$$m$$$ ($$$1 \le m \le 2 \cdot 10^5$$$) — the number of shuffles. The fourth line contains $$$m$$$ integers $$$b_1, b_2, \dots, b_m$$$ ($$$1 \le b_j \le n - 1$$$) — the amount of cards that are moved on the $$$j$$$-th shuffle. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase, print a single integer — the value of the card on the top of the deck after the deck is shuffled $$$m$$$ times.

NoteIn the first testcase, each shuffle effectively swaps two cards. After three swaps, the deck will be $$$[2, 1]$$$.In the second testcase, the second shuffle cancels what the first shuffle did. First, three topmost cards went underneath the last card, then that card went back below the remaining three cards. So the deck remained unchanged from the initial one — the topmost card has value $$$3$$$.

    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 read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
    let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))
    let () =

      let cases = read_int()in
      for case = 1 to cases do
        let n = read_int() in
        let a = Array.init n read_int in
        let m = read_int() in
        let b = Array.init m read_int in
	let sum i j f = fold i j (fun i a -> ((f i) + a) mod n) 0 in
        let bsum = sum 0 (m-1) (fun i -> b.(i)) in
        printf "%d\n" a.(bsum)
      done

open Printf
open Scanf

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

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

  let cases = read_int()in
  for case = 1 to cases do
    let n = read_int() in
    let a = Array.init n read_int in
    let m = read_int() in
    let b = Array.init m read_int in
    let bsum = sum 0 (m-1) (fun i -> b.(i)) in
    printf "%d\n" a.(bsum mod n)
  done