You have array of $$$n$$$ numbers $$$a_{1}, a_{2}, \ldots, a_{n}$$$. Rearrange these numbers to satisfy $$$|a_{1} - a_{2}| \le |a_{2} - a_{3}| \le \ldots \le |a_{n-1} - a_{n}|$$$, where $$$|x|$$$ denotes absolute value of $$$x$$$. It's always possible to find such rearrangement.Note that all numbers in $$$a$$$ are not necessarily different. In other words, some numbers of $$$a$$$ may be same.You have to answer independent $$$t$$$ test cases.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^{4}$$$) — the number of test cases. The first line of each test case contains single integer $$$n$$$ ($$$3 \le n \le 10^{5}$$$) — the length of array $$$a$$$. It is guaranteed that the sum of values of $$$n$$$ over all test cases in the input does not exceed $$$10^{5}$$$. The second line of each test case contains $$$n$$$ integers $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$-10^{9} \le a_{i} \le 10^{9}$$$).

For each test case, print the rearranged version of array $$$a$$$ which satisfies given condition. If there are multiple valid rearrangements, print any of them.

NoteIn the first test case, after given rearrangement, $$$|a_{1} - a_{2}| = 0 \le |a_{2} - a_{3}| = 1 \le |a_{3} - a_{4}| = 2 \le |a_{4} - a_{5}| = 2 \le |a_{5} - a_{6}| = 10$$$. There are other possible answers like "5 4 5 6 -2 8".In the second test case, after given rearrangement, $$$|a_{1} - a_{2}| = 1 \le |a_{2} - a_{3}| = 2 \le |a_{3} - a_{4}| = 4$$$. There are other possible answers like "2 4 8 1".

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
    let a = Array.init n read_int in
    Array.sort compare a;
    let rec loop i j side ac = if i>j then ac else (
      if side = 0 then loop (i+1) j (1-side) (a.(i)::ac)
      else loop i (j-1) (1-side) (a.(j)::ac)
    )
    in
    List.iter (printf "%d ") (loop 0 (n-1) 1 []);
    print_newline()
  done


There are $$$n$$$ people participating in some contest, they start participating in $$$x$$$ minutes intervals. That means the first participant starts at time $$$0$$$, the second participant starts at time $$$x$$$, the third — at time $$$2 \cdot x$$$, and so on.Duration of contest is $$$t$$$ minutes for each participant, so the first participant finishes the contest at time $$$t$$$, the second — at time $$$t + x$$$, and so on. When a participant finishes the contest, their dissatisfaction equals to the number of participants that started the contest (or starting it now), but haven't yet finished it.Determine the sum of dissatisfaction of all participants.

The first line contains a single integer $$$k$$$ ($$$1 \le k \le 1000$$$) — the number of test cases. Each of the next $$$k$$$ lines contains three integers $$$n$$$, $$$x$$$, $$$t$$$ ($$$1 \le n, x, t \le 2 \cdot 10^9$$$) — the number of participants, the start interval and the contest duration.

Print $$$k$$$ lines, in the $$$i$$$-th line print the total dissatisfaction of participants in the $$$i$$$-th test case.

NoteIn the first example the first participant starts at $$$0$$$ and finishes at time $$$5$$$. By that time the second and the third participants start, so the dissatisfaction of the first participant is $$$2$$$. The second participant starts at time $$$2$$$ and finishes at time $$$7$$$. By that time the third the fourth participants start, so the dissatisfaction of the second participant is $$$2$$$. The third participant starts at $$$4$$$ and finishes at $$$9$$$. By that time the fourth participant starts, so the dissatisfaction of the third participant is $$$1$$$.The fourth participant starts at $$$6$$$ and finishes at $$$11$$$. By time $$$11$$$ everyone finishes the contest, so the dissatisfaction of the fourth participant is $$$0$$$.In the second example the first participant starts at $$$0$$$ and finishes at time $$$2$$$. By that time the second participants starts, and the third starts at exactly time $$$2$$$. So the dissatisfaction of the first participant is $$$2$$$. The second participant starts at time $$$1$$$ and finishes at time $$$3$$$. At that time the third participant is solving the contest.

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

let print x = Printf.fprintf stdout "%Ld\n" x;;

let cal n x t =
  let k = Int64.div t x in
  if k < n then
    let p1 = Int64.mul (Int64.sub n  k) k in
    let p2 = Int64.mul k  (Int64.sub k  1L) in
    Int64.add p1 (Int64.div p2 2L)
  else
    Int64.div (Int64.mul n  (Int64.sub n  1L)) 2L

let t = read_int ();;

let () =
  for i = 1 to t do
    let n = scan_int () in
    let x = scan_int () in
    let t = scan_int () in
    print (cal n x t)
  done

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

let print x = Printf.fprintf stdout "%Ld\n" x;;

let cal n x t =
  let k = Int64.div t x in
  let p1 = Int64.mul (Int64.sub n  k) k in
  let p2 = Int64.mul k  (Int64.sub k  1L) in
  Int64.add p1 (Int64.div p2 2L);;

let t = read_int ();;

let () =
  for i = 1 to t do
    let n = scan_int () in
    let x = scan_int () in
    let t = scan_int () in
    print (cal n x t)
  done

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

let print x = Printf.printf "%lld\n" x;;

let cal n x t =
  let k = t / x in
  (n - k) * k + k * (k - 1) / 2;;

let t = scan_int ();;

let () =
  for i = 1 to t - 1 do
    let n = scan_int () in
    let x = scan_int () in
    let t = scan_int () in
    print (cal n x t)
  done

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

let print x = Printf.printf "%d\n" x;;

let cal n x t =
  let k = t / x in
  (n - k) * k + k * (k - 1) / 2;;

let t = scan_int ();;

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


Vivek has encountered a problem. He has a maze that can be represented as an $$$n \times m$$$ grid. Each of the grid cells may represent the following:  Empty — '.'  Wall — '#'  Good person  — 'G'  Bad person — 'B' The only escape from the maze is at cell $$$(n, m)$$$.A person can move to a cell only if it shares a side with their current cell and does not contain a wall. Vivek wants to block some of the empty cells by replacing them with walls in such a way, that all the good people are able to escape, while none of the bad people are able to. A cell that initially contains 'G' or 'B' cannot be blocked and can be travelled through.Help him determine if there exists a way to replace some (zero or more) empty cells with walls to satisfy the above conditions.It is guaranteed that the cell $$$(n,m)$$$ is empty. Vivek can also block this cell.

The first line contains one integer $$$t$$$ $$$(1 \le t \le 100)$$$ — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$m$$$ $$$(1 \le n, m \le 50)$$$ — the number of rows and columns in the maze. Each of the next $$$n$$$ lines contain $$$m$$$ characters. They describe the layout of the maze. If a character on a line equals '.', the corresponding cell is empty. If it equals '#', the cell has a wall. 'G' corresponds to a good person and 'B' corresponds to a bad person.

For each test case, print "Yes" if there exists a way to replace some empty cells with walls to satisfy the given conditions. Otherwise print "No" You may print every letter in any case (upper or lower).

NoteFor the first and second test cases, all conditions are already satisfied.For the third test case, there is only one empty cell $$$(2,2)$$$, and if it is replaced with a wall then the good person at $$$(1,2)$$$ will not be able to escape.For the fourth test case, the good person at $$$(1,1)$$$ cannot escape.For the fifth test case, Vivek can block the cells $$$(2,3)$$$ and $$$(2,2)$$$.For the last test case, Vivek can block the destination cell $$$(2, 2)$$$.

open Printf
open Scanf

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

let read_string _ = bscanf Scanning.stdin " %s " (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,m) = read_pair() in
    let board = Array.init n read_string in
    let getb i j = board.(i).[j] in
    let mm = Array.make_matrix n m 'x' in

    for i=0 to n-1 do
      for j=0 to m-1 do
	mm.(i).(j) <- getb i j
      done
    done;

    let inbounds i j =
      0 <= i && i < n && 0 <= j && j < m
    in

    let okmove di dj = (abs di) + (abs dj) = 1 in

    let adj = ref false in

    for i=0 to n-1 do
      for j=0 to m-1 do
	if getb i j = 'B' then (
	  for di = -1 to 1 do
	    for dj = -1 to 1 do
	      let (i',j') = (i+di, j+dj) in
	      if okmove di dj && inbounds i' j' then (
		if getb i' j' = '.' then mm.(i').(j') <- '#';
		if getb i' j' = 'G' then adj := true
	      )
	    done
	  done
	)
      done
    done;

    let getm i j = mm.(i).(j) in

    (* can we reach all Gs from destination? *)

    let reached = Array.make_matrix n m false in

    let grow li =
      let newli = ref [] in
      List.iter (fun (i,j) ->
	for di = -1 to 1 do
	  for dj = -1 to 1 do
	    let (i',j') = (i + di, j+dj) in
	    if okmove di dj && inbounds i' j' && (not reached.(i').(j')) && getm i' j' <> '#' then (
	      reached.(i').(j') <- true;
	      newli := (i',j'):: !newli
	    )
	  done
	done
      ) li;
      !newli
    in

    let rec loop li =
      if li <> [] then loop (grow li)
    in

    loop [(n-1,m-1)];

    let works = ref true in
    let existsG = ref false in

    for i=0 to n-1 do
      for j=0 to m-1 do
	if getb i j = 'G' && (not reached.(i).(j)) then works := false;
	if getb i j = 'G' then existsG := true
      done
    done;

    if (not !existsG) || ((not !adj) && !works && getm (n-1) (m-1) <> '#')
    then printf "Yes\n" else printf "No\n"
  done

    (* finished 18 minutes late *)

open Printf
open Scanf

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

let read_string _ = bscanf Scanning.stdin " %s " (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,m) = read_pair() in
    let board = Array.init n read_string in
    let getb i j = board.(i).[j] in
    let mm = Array.make_matrix n m 'x' in

    for i=0 to n-1 do
      for j=0 to m-1 do
	mm.(i).(j) <- getb i j
      done
    done;

    let inbounds i j =
      0 <= i && i < n && 0 <= j && j < m
    in

    let okmove di dj = (abs di) + (abs dj) = 1 in

    for i=0 to n-1 do
      for j=0 to m-1 do
	if getb i j = 'B' then (
	  for di = -1 to 1 do
	    for dj = -1 to 1 do
	      let (i',j') = (i + di, j+dj) in
	      if okmove di dj && inbounds i' j' then (
		if (i',j') <> (i,j) && (getb i' j' = '.') then
		  mm.(i').(j') <- '#'
	      )
	    done
	  done
	)
      done
    done;

    let getm i j = mm.(i).(j) in

    (* can we reach all Gs from destination? *)

    let reached = Array.make_matrix n m false in

    let grow li =
      let newli = ref [] in
      List.iter (fun (i,j) ->
	for di = -1 to 1 do
	  for dj = -1 to 1 do
	    let (i',j') = (i + di, j+dj) in
	    if okmove di dj && inbounds i' j' && (not reached.(i').(j')) && getm i' j' <> '#' then (
	      reached.(i').(j') <- true;
	      newli := (i',j'):: !newli
	    )
	  done
	done
      ) li;
      !newli
    in

    let rec loop li =
      if li <> [] then loop (grow li)
    in

    loop [(n-1,m-1)];

    let works = ref true in
    let existsG = ref false in

    for i=0 to n-1 do
      for j=0 to m-1 do
	if getb i j = 'G' && (not reached.(i).(j)) then works := false;
	if getb i j = 'G' then existsG := true
      done
    done;

    if (not !existsG) || (!works && getm (n-1) (m-1) <> '#')
    then printf "Yes\n" else printf "No\n"
  done

    (* finished 18 minutes late *)

open Printf
open Scanf

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

let read_string _ = bscanf Scanning.stdin " %s " (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,m) = read_pair() in
    let board = Array.init n read_string in
    let getb i j = board.(i).[j] in
    let mm = Array.make_matrix n m 'x' in

    for i=0 to n-1 do
      for j=0 to m-1 do
	mm.(i).(j) <- getb i j
      done
    done;

    let inbounds i j =
      0 <= i && i < n && 0 <= j && j < m
    in

    for i=0 to n-1 do
      for j=0 to m-1 do
	if getb i j = 'B' then (
	  for di = -1 to 1 do
	    for dj = -1 to 1 do
	      let (i',j') = (i + di, j+dj) in
	      if inbounds i' j' then (
		if (i',j') <> (i,j) && (getb i' j' = '.') then
		  mm.(i').(j') <- '#'
	      )
	    done
	  done
	)
      done
    done;

    let getm i j = mm.(i).(j) in

    (* can we reach all Gs from destination? *)

    let reached = Array.make_matrix n m false in

    let grow li =
      let newli = ref [] in
      List.iter (fun (i,j) ->
	for di = -1 to 1 do
	  for dj = -1 to 1 do
	    let (i',j') = (i + di, j+dj) in
	    if inbounds i' j' && (not reached.(i').(j')) && getm i' j' <> '#' then (
	      reached.(i').(j') <- true;
	      newli := (i',j'):: !newli
	    )
	  done
	done
      ) li;
      !newli
    in

    let rec loop li =
      if li <> [] then loop (grow li)
    in

    loop [(n-1,m-1)];

    let works = ref true in
    let existsG = ref false in

    for i=0 to n-1 do
      for j=0 to m-1 do
	if getb i j = 'G' && (not reached.(i).(j)) then works := false;
	if getb i j = 'G' then existsG := true
      done
    done;

    if (not !existsG) || (!works && getm (n-1) (m-1) <> '#')
    then printf "Yes\n" else printf "No\n"
  done

    (* finished 18 minutes late *)

open Printf
open Scanf

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

let read_string _ = bscanf Scanning.stdin " %s " (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,m) = read_pair() in
    let board = Array.init n read_string in
    let getb i j = board.(i).[j] in
    let mm = Array.make_matrix n m 'x' in

    for i=0 to n-1 do
      for j=0 to m-1 do
	mm.(i).(j) <- getb i j
      done
    done;

    if case=63 then (
	printf "%s      %s\n" board.(0) board.(1)
    ) ;

    let inbounds i j =
      0 <= i && i < n && 0 <= j && j < m
    in

    for i=0 to n-1 do
      for j=0 to m-1 do
	if getb i j = 'B' then (
	  for di = -1 to 1 do
	    for dj = -1 to 1 do
	      let (i',j') = (i + di, j+dj) in
	      if inbounds i' j' then (
		if (i',j') <> (i,j) && (getb i' j' = '.') then
		  mm.(i').(j') <- '#'
	      )
	    done
	  done
	)
      done
    done;

    let getm i j = mm.(i).(j) in

    (* can we reach all Gs from destination? *)

    let reached = Array.make_matrix n m false in

    let grow li =
      let newli = ref [] in
      List.iter (fun (i,j) ->
	for di = -1 to 1 do
	  for dj = -1 to 1 do
	    let (i',j') = (i + di, j+dj) in
	    if inbounds i' j' && (not reached.(i').(j')) && getm i' j' <> '#' then (
	      reached.(i').(j') <- true;
	      newli := (i',j'):: !newli
	    )
	  done
	done
      ) li;
      !newli
    in

    let rec loop li =
      if li <> [] then loop (grow li)
    in

    loop [(n-1,m-1)];

    let works = ref true in
    let existsG = ref false in

    for i=0 to n-1 do
      for j=0 to m-1 do
	if getb i j = 'G' && (not reached.(i).(j)) then works := false;
	if getb i j = 'G' then existsG := true
      done
    done;

    if (not !existsG) || (!works && getm (n-1) (m-1) <> '#')
    then printf "Yes\n" else printf "No\n"
  done

    (* finished 18 minutes late *)


You are given an array $$$a$$$ consisting of $$$n$$$ positive integers.You are allowed to perform this operation any number of times (possibly, zero):   choose an index $$$i$$$ ($$$2 \le i \le n$$$), and change $$$a_i$$$ to $$$a_i - a_{i-1}$$$. Is it possible to make $$$a_i=0$$$ for all $$$2\le i\le n$$$?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 100$$$)  — the number of test cases. The description of the test cases follows. The first line contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the length of array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ ($$$1 \le a_i \le 10^9$$$).

For each test case, print "YES" (without quotes), if it is possible to change $$$a_i$$$ to $$$0$$$ for all $$$2 \le i \le n$$$, and "NO" (without quotes) otherwise. You can print letters in any case (upper or lower).

NoteIn the first test case, the initial array is $$$[5,10]$$$. You can perform $$$2$$$ operations to reach the goal:  Choose $$$i=2$$$, and the array becomes $$$[5,5]$$$.  Choose $$$i=2$$$, and the array becomes $$$[5,0]$$$. In the second test case, the initial array is $$$[1,2,3]$$$. You can perform $$$4$$$ operations to reach the goal:   Choose $$$i=3$$$, and the array becomes $$$[1,2,1]$$$.  Choose $$$i=2$$$, and the array becomes $$$[1,1,1]$$$.  Choose $$$i=3$$$, and the array becomes $$$[1,1,0]$$$.  Choose $$$i=2$$$, and the array becomes $$$[1,0,0]$$$. In the third test case, you can choose indices in the order $$$4$$$, $$$3$$$, $$$2$$$.

(* From @Darooha's code (https://codeforces.com/profile/Darooha) *)

open Printf
open Scanf

let ( ** ) a b = Int64.mul a b
let ( ++ ) a b = Int64.add a b
let long x = Int64.of_int x
let short x = Int64.to_int x

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

(* Main Code file *)

let rec sum = function
        | [] -> 0
        | h::t -> h + sum(t)

let rec all = function
        | [] -> true
        | h::t -> if h then all(t) else false

let divis a b = b mod a = 0

let () =
    let t = read_int() in
    for i=1 to t do
        let n = read_int() in
        let arr = Array.init n read_int in
        if all (Array.to_list (Array.map (divis arr.(0)) arr))
        then printf "Yes\n"
        else printf "No\n"
    done;


User ainta loves to play with cards. He has a cards containing letter "o" and b cards containing letter "x". He arranges the cards in a row, and calculates the score of the deck by the formula below.  At first, the score is 0.  For each block of contiguous "o"s with length x the score increases by x2.  For each block of contiguous "x"s with length y the score decreases by y2.   For example, if a = 6, b = 3 and ainta have arranged the cards in the order, that is described by string "ooxoooxxo", the score of the deck equals 22 - 12 + 32 - 22 + 12 = 9. That is because the deck has 5 blocks in total: "oo", "x", "ooo", "xx", "o".User ainta likes big numbers, so he wants to maximize the score with the given cards. Help ainta make the score as big as possible. Note, that he has to arrange all his cards.

The first line contains two space-separated integers a and b (0 ≤ a, b ≤ 105; a + b ≥ 1) — the number of "o" cards and the number of "x" cards.

In the first line print a single integer v — the maximum score that ainta can obtain. In the second line print a + b characters describing the deck. If the k-th card of the deck contains "o", the k-th character must be "o". If the k-th card of the deck contains "x", the k-th character must be "x". The number of "o" characters must be equal to a, and the number of "x " characters must be equal to b. If there are many ways to maximize v, print any. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

open Printf
open Scanf

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

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

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

let pr sym c = for i=1 to c do printf "%c" sym done
let sq x = x**x

let tl x = Int64.of_int x

let () =
  let a = read_int() in (* number of os *)
  let b = read_int() in (* number of xs *)
  let maxg = min b (a+1) in
  if maxg < 2 then (
    printf "%Ld\n" ((sq (tl a)) -- (sq (tl b)));
    pr 'o' a;
    pr 'x' b;
    printf "\n"
  ) else (
    let rec loop g bestg best_score = if g > maxg then (bestg,best_score) else
    (* g = number of groups of xs.  g-1 groups of os. *)
	let oscore = (tl (g-2)) ++ (sq (tl (a-(g-2)))) in
	let lo = b/g in
	let hi = (b+g-1)/g in
	let nhi = (b - g*lo) in
	let nlo = g - nhi in
(*	let xscore = sum 0 (g-1) (fun i -> sq ((b+i)/g)) in *)
	let xscore = (tl nhi) ** (sq (tl hi)) ++ (tl nlo) ** (sq (tl lo)) in
	let score = oscore -- xscore in
	if score > best_score then
	  loop (g+1) g score
	else
	  loop (g+1) bestg best_score
    in

    let (g,s) = loop 2 0 (0L -- (sq (tl (a+b)))) in
    printf "%Ld\n" s;
    pr 'x' (b/g);
    for i=1 to g-1 do
      pr 'o' (if i<g-1 then 1 else (a-(g-2)));
      pr 'x' ((b+i)/g);
    done;
    printf "\n";
  )


Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the first student with the second one as well as the second student with the first one.To restore order, Anna and Maria do the following. First, for each student Anna finds out what other students he is tied to. If a student is tied to exactly one other student, Anna reprimands him. Then Maria gathers in a single group all the students who have been just reprimanded. She kicks them out from the club. This group of students immediately leaves the club. These students takes with them the laces that used to tie them. Then again for every student Anna finds out how many other students he is tied to and so on. And they do so until Anna can reprimand at least one student.Determine how many groups of students will be kicked out of the club.

The first line contains two integers n and m — the initial number of students and laces (). The students are numbered from 1 to n, and the laces are numbered from 1 to m. Next m lines each contain two integers a and b — the numbers of students tied by the i-th lace (1 ≤ a, b ≤ n, a ≠ b). It is guaranteed that no two students are tied with more than one lace. No lace ties a student to himself.

Print the single number — the number of groups of students that will be kicked out from the club.

NoteIn the first sample Anna and Maria won't kick out any group of students — in the initial position every student is tied to two other students and Anna won't be able to reprimand anyone.In the second sample four students are tied in a chain and two more are running by themselves. First Anna and Maria kick out the two students from both ends of the chain (1 and 4), then — two other students from the chain (2 and 3). At that the students who are running by themselves will stay in the club.In the third sample Anna and Maria will momentarily kick out all students except for the fourth one and the process stops at that point. The correct answer is one.

open Scanf
open Printf

type grahp_t = {n:int; g:int list array};;
let create n = {n = n; g = Array.init (n+1) (fun _ -> [])};;

let ($+) {g;_} (u, v) = g.(u) <- (v::g.(u));g.(v) <- (u::g.(v));;
let ($-) {g;_} (u, v) =
  let edges = g.(v) in
  let rec aux acc = function
    | [] -> acc
    | hd :: tl when hd = u -> acc @ tl
    | hd :: tl -> aux (hd::acc) tl
  in
  g.(v) <- (aux [] edges)

let kick_out g =
  let len, hd = List.length, List.hd in
  let k = ref [] in
  Array.iteri (fun u e -> if (len e) = 1 then (k := (u, hd e)::(!k);g.g.(u) <- []) else ()) g.g;
  List.iter (fun e -> g$-e) !k;
  len !k

let main () =
  let read2 () = scanf " %d %d " (fun x y -> x, y) in
  let n, m = read2 () in
  let g = create n in
  let () = for i = 1 to m do
      let u, v = read2 () in
      g$+(u,v)
    done in
  let ans = ref 0 in
  while (kick_out g) > 0 do incr ans done;
  printf "%d\n" !ans

let () = main ()


One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution. Otherwise, the friends won't write the problem's solution.This contest offers n problems to the participants. For each problem we know, which friend is sure about the solution. Help the friends find the number of problems for which they will write a solution.

The first input line contains a single integer n (1 ≤ n ≤ 1000) — the number of problems in the contest. Then n lines contain three integers each, each integer is either 0 or 1. If the first number in the line equals 1, then Petya is sure about the problem's solution, otherwise he isn't sure. The second number shows Vasya's view on the solution, the third number shows Tonya's view. The numbers on the lines are separated by spaces.

Print a single integer — the number of problems the friends will implement on the contest.

NoteIn the first sample Petya and Vasya are sure that they know how to solve the first problem and all three of them know how to solve the second problem. That means that they will write solutions for these problems. Only Petya is sure about the solution for the third problem, but that isn't enough, so the friends won't take it. In the second sample the friends will only implement the second problem, as Vasya and Tonya are sure about the solution.

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 rec loop n a =
  if n <= 0 then a
  else
    let (x,y,z) = read3() in
    loop (n-1) ( if x+y+z >= 2 then (a+1) else a );;

let _ =
  let n = read1() in
  Printf.printf "%d\n" ( loop n 0 );;

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

let if_certain d = match d with
    |0 -> false
    |_-> true

let remove_uncertainity l = List.filter(if_certain) l

let rec getting_statuses n k =
    if n > 0
    then
        let status = Scanf.scanf "%d %d %d " (fun s0 s1 s2 -> [s0; s1; s2]) in
        if (List.length (remove_uncertainity status)) >= 2
        then
            getting_statuses(n - 1) (k + 1)
        else
            getting_statuses(n - 1) k
    else
        Printf.printf ("%d\n") k

let () = getting_statuses number_of_problems 0

let input () = let number_of_problems = Scanf.scanf "%d " (fun n -> n) in
    let rec getting_statuses n =
    if n > 0
    then
        let status = Scanf.scanf "%d %d %d " (fun s0 s1 s2 -> [s0; s1; s2]) in
        let rest = getting_statuses (n - 1) in
        (status :: rest)
    else
        []
    in getting_statuses number_of_problems

let if_certain d = match d with
    |0 -> false
    |_-> true

let count f l = List.length (List.filter f l)

let solve : int list list -> int = count (fun l -> count if_certain l >= 2)

let print k = Printf.printf "%d\n" k

let () = print (solve (input ()))

let rec loop n =
  if n == 0 then
    0
  else
    let score = Scanf.scanf "%d %d %d\n" (fun x y z -> if x+y+z >= 2 then 1 else 0) in
    score + loop (n-1);;

let _ =
  let n = read_int() in
  print_int(loop n) in
  print_newline()

let n=Scanf.scanf "%d" (fun a->a);;
let ans= ref 0;;
for i=1 to n do
    ans:=!ans+(Scanf.scanf " %d %d %d" (fun a b c->if a+b+c>=2 then 1 else 0))
done;;
print_int(!ans)

let n=Scanf.scanf "%d" (fun a->a);;
let ans= ref 0;;
for i=1 to n do
    let (a,b,c)=(Scanf.scanf " %d %d %d" (fun a b c->(a,b,c))) in
    if a+b+c>=2 then ans:=!ans+1
done;;
print_int(!ans)

let check lst = 2 <= List.fold_left (+) 0 lst
;;

let solve llst = List.length (List.filter check llst)
;;

let make_nums n =
  let arr = Array.init n (fun _ -> Scanf.scanf "%d %d %d "
                                               (fun n m k -> [n; m; k;]))
  in
  Array.to_list arr
;;

let () =
  let nums = Scanf.scanf "%d "
                          (fun n -> make_nums n)
  in
  Printf.printf "%d\n" (solve nums)
;;

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

let n = read_int ();;

let a = Array.init n (fun i -> (read_int3 () ));;

let vote = function
  | (0,0,0) -> 0
  | (1,0,0) -> 0
  | (0,1,0) -> 0
  | (0,0,1) -> 0
  | (_,_,_) -> 1
;;

let b = Array.map (fun x -> vote x) a
        |> Array.fold_left (+) 0
    in print_int b; print_endline ""

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

let solve n =
  let rec check_opinions acc = function
    | 0 -> acc
    | n -> let o1 = read_int ()
           and o2 = read_int ()
           and o3 = read_int () in
           if o1 + o2 + o3 > 1
           then check_opinions (acc + 1) (n - 1)
           else check_opinions acc (n - 1)
  in check_opinions 0 n

let () =
  let n = read_int () in
  Printf.printf "%d\n" (solve n)

open Scanf

let rec solve n =
  if n =  0 then 0
  else
    begin
      scanf "%d %d %d\n" (fun x y z ->
	let rest = solve (n - 1) in
	if (x = 0 && y = 0 || x = 0 && z = 0 || y = 0 && z = 0) then rest
	else 1 + rest)
    end

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

let read_one () = Scanf.scanf " %d" (fun x -> x)
let read_two () = Scanf.scanf " %d %d" (fun x y -> (x,y))
let read_three () = Scanf.scanf " %d %d %d" (fun x y z -> (x,y,z))

let read_many n =
  let rec helper i acc =
    if i >= n then List.rev acc
    else Scanf.scanf " %d" (fun n -> helper (i+1) (n::acc)) in
  helper 0 []

let list_iteri f lst = List.fold_left (fun j b -> f j b; j+1) 0 lst

let main =
  let t = Scanf.scanf "%d" (fun t -> t) in
  let sum = ref 0 in
  for case = 1 to t do
    let (a,b,c) = read_three() in
    sum := !sum + if a+b+c >= 2 then 1 else 0;
  done;
  Printf.printf "%d\n" !sum

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

let (|>) x f = f x;;
let (@@) f x = f x;;
let read0() = sf "%d " (fun x -> x)
let read1() = sf "%d\n" (fun x -> x)
let read2() = sf "%d %d\n" (fun x y -> x, y)
let read3() = sf "%d %d %d\n" (fun x y z -> x, y, z)

exception Error of string

let inf = 1000000000;;
let eps = 1e-11;;

let _ =
  let n = read1() in
  let res = ref 0 in
  for i = 1 to n do
    let (x, y, z) = read3() in
    if x + y + z >= 2 then res := !res + 1
  done;
  pf "%d\n" !res
;;

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

let rec solve n =
  if n == 0 then 0
  else if read_int () + read_int () + read_int () > 1 then 1 + solve (n - 1)
  else 0 + solve (n - 1)

let () =
  Printf.printf "%d" (solve (read_int ()))

let n = int_of_string (input_line stdin) ;;

let sum a b c = a + b + c ;;

let rec solve i count =
    if i == 0 then count
    else let input = Scanf.bscanf Scanf.Scanning.stdin "%d %d %d\n" sum in
      if input > 1 then solve (i - 1) (count + 1)
      else solve (i - 1) count ;;

Printf.printf "%d\n" (solve n 0) ;;

open Printf

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

let sum xs = Array.fold_left (+) 0 xs

let main =
    let n = read_int() in
    let answer = ref 0 in
    for i = 1 to n do
        let xs = read_ints() in
        if (sum xs) >= 2 then
            answer := !answer + 1;
    done;
    printf "%d\n" !answer;;

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

let if_certain d = match d with
    |0 -> false
    |_-> true

let remove_uncertainity l = List.filter(if_certain) l

let rec getting_statuses n k =
    if n > 0
    then
        let status = Scanf.scanf "%d %d %d " (fun s0 s1 s2 -> [s0; s1; s2]) in
        if (List.length (remove_uncertainity status)) >= 2
        then
            getting_statuses(n - 1) (k + 1)
        else
            ()
    else
        Printf.printf ("%d\n") k

let () = getting_statuses number_of_problems 0

open Scanf

let rec solve n =
  if n =  0 then 0
  else
    begin
      scanf "%d %d %d\n" (fun x y z ->
	let rest = solve (n - 1) in
	if x = 0 && y = 0 && z = 0 then rest
	else 1 + rest)
    end

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

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

let rec solve n =
  if n == 0 then 0
  else if read_int + read_int + read_int > 1 then 1 + solve (n - 1)
  else 0 + solve (n - 1)

let () =
  Printf.printf "%d" (solve read_int)


Nick's company employed n people. Now Nick needs to build a tree hierarchy of «supervisor-surbodinate» relations in the company (this is to say that each employee, except one, has exactly one supervisor). There are m applications written in the following form: «employee ai is ready to become a supervisor of employee bi at extra cost ci». The qualification qj of each employee is known, and for each application the following is true: qai > qbi. Would you help Nick calculate the minimum cost of such a hierarchy, or find out that it is impossible to build it.

The first input line contains integer n (1 ≤ n ≤ 1000) — amount of employees in the company. The following line contains n space-separated numbers qj (0 ≤ qj ≤ 106)— the employees' qualifications. The following line contains number m (0 ≤ m ≤ 10000) — amount of received applications. The following m lines contain the applications themselves, each of them in the form of three space-separated numbers: ai, bi and ci (1 ≤ ai, bi ≤ n, 0 ≤ ci ≤ 106). Different applications can be similar, i.e. they can come from one and the same employee who offered to become a supervisor of the same person but at a different cost. For each application qai > qbi.

Output the only line — the minimum cost of building such a hierarchy, or -1 if it is impossible to build it.

NoteIn the first sample one of the possible ways for building a hierarchy is to take applications with indexes 1, 2 and 4, which give 11 as the minimum total cost. In the second sample it is impossible to build the required hierarchy, so the answer is -1.

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

let () =
  let n = read_int 0 in
  for i = 1 to n do read_int 0 |> ignore done;
  let d = Array.make n max_int in
  for i = 1 to read_int 0 do
    read_int 0 |> ignore;
    let x = read_int 0 - 1 in
    let y = read_int 0 in
    d.(x) <- min d.(x) y
  done;
  let t = Array.fold_left (fun x y -> x + (if y = max_int then 1 else 0)) 0 d in
  if t > 1 then
    print_endline "-1"
  else
    Array.fold_left (+) (-max_int) d |> Printf.printf "%d\n"


Polygon is not only the best platform for developing problems but also a square matrix with side $$$n$$$, initially filled with the character 0.On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly $$$2n$$$ cannons were placed.    Initial polygon for $$$n=4$$$. Cannons shoot character 1. At any moment of time, no more than one cannon is shooting. When a 1 flies out of a cannon, it flies forward (in the direction of the shot) until it collides with a polygon border or another 1. After that, it takes the cell in which it was before the collision and remains there. Take a look at the examples for better understanding.More formally:   if a cannon stands in the row $$$i$$$, to the left of the first column, and shoots with a 1, then the 1 starts its flight from the cell ($$$i, 1$$$) and ends in some cell ($$$i, j$$$);  if a cannon stands in the column $$$j$$$, above the first row, and shoots with a 1, then the 1 starts its flight from the cell ($$$1, j$$$) and ends in some cell ($$$i, j$$$). For example, consider the following sequence of shots:   1. Shoot the cannon in the row $$$2$$$.                         2. Shoot the cannon in the row $$$2$$$.                         3. Shoot the cannon in column $$$3$$$. You have a report from the military training on your desk. This report is a square matrix with side length $$$n$$$ consisting of 0 and 1. You wonder if the training actually happened. In other words, is there a sequence of shots such that, after the training, you get the given matrix?Each cannon can make an arbitrary number of shots. Before the training, each cell of the polygon contains 0.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case starts with a line containing an integer $$$n$$$ ($$$1 \le n \le 50$$$) — the size of the polygon. This is followed by $$$n$$$ lines of length $$$n$$$, consisting of 0 and 1 — the polygon matrix after the training. The total area of the matrices in all test cases in one test does not exceed $$$10^5$$$.

For each test case print:   YES if there is a sequence of shots leading to a given matrix;  NO if such a sequence does not exist.  The letters in the words YES and NO can be printed in any case.

NoteThe first test case was explained in the statement.The answer to the second test case is NO, since a 1 in a cell ($$$1, 1$$$) flying out of any cannon would continue its flight further.

let split_string ?(pattern="") = Str.split @@ Str.regexp pattern
let t = Scanf.sscanf (read_line ()) "%d" @@ fun t -> t

let () = for _ = 1 to t do
  let n = Scanf.sscanf (read_line ()) "%d" @@ fun n -> n in
  let f = Array.init n @@ fun _ -> read_line () |> split_string |> List.map int_of_string |> Array.of_list in
  let ans = ref true in
  for i = 0 to n - 2 do
    for j = 0 to n - 2 do
      let c = f.(i).(j) in
      if c = 1 && f.(i + 1).(j) = 0 && f.(i).(j + 1) = 0 then ans := false
    done
  done;
  print_endline @@ if !ans then "YES" else "NO"
done


Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players.Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the resulting word must be prefix of at least one string from the group. A player loses if he cannot move.Andrew and Alex decided to play this game k times. The player who is the loser of the i-th game makes the first move in the (i + 1)-th game. Guys decided that the winner of all games is the player who wins the last (k-th) game. Andrew and Alex already started the game. Fedor wants to know who wins the game if both players will play optimally. Help him.

The first line contains two integers, n and k (1 ≤ n ≤ 105; 1 ≤ k ≤ 109). Each of the next n lines contains a single non-empty string from the given group. The total length of all strings from the group doesn't exceed 105. Each string of the group consists only of lowercase English letters.

If the player who moves first wins, print "First", otherwise print "Second" (without the quotes).

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

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

module Array = ArrayLabels ;;
module List  = struct
  include ListLabels ;;
  let rec repeat n a = if n = 0 then [] else a :: repeat (n - 1) a ;;
  let rec drop n a =
    if n = 0 then a
    else match a with
    | [] -> failwith "cannot take"
    | x :: xs -> drop (n - 1) xs ;;
end
module H = Hashtbl ;;

type t =
| Node of (char, t) H.t

let idx c = Char.code c - Char.code 'a' ;;

let create (ss : string list) =
  let rec insert tr s i n =
    if i = n then ()
    else
      let Node tr = tr in
      try
        let t = H.find tr s.[i] in
        insert t s (i + 1) n
      with
      | Not_found -> begin
        let nd = Node (H.create 10) in
        H.add tr s.[i] nd;
        insert nd s (i + 1) n;
      end in

  let tr = Node (H.create 10) in
  List.iter ss ~f:(fun s -> insert tr s 0 (String.length s));
  tr
;;

let is_nil tr = H.length tr = 0 ;;

type res = W | L | C | NC

let rec search (Node tr) =
  if is_nil tr then L
  else
    let vs = H.fold (fun c tr acc -> search tr :: acc) tr [] in
    if List.exists vs ~f:(fun v -> v = NC) then C
    else if List.exists vs ~f:(fun v -> v = W) && List.exists vs ~f:(fun v -> v = L) then C
    else if List.exists vs ~f:(fun v -> v = L) then W
    else if List.exists vs ~f:(fun v -> v = W) then L
    else NC
;;

let f v = if v = 0 then "First" else "Second" ;;

let main k (Node tr) =
  let res = search (Node tr) in
  match res with
  | C -> pf "First\n"
  | NC -> pf "Second\n"
  | W -> pf "%s\n" (f ((k + 1) mod 2))
  | L -> pf "Second\n"
;;

let () =
  sf "%d %d " (fun n k ->
    let acc = ref [] in
    for i = 0 to n - 1 do
      acc := sf "%s " (fun v -> v) :: !acc
    done;
    main k (create !acc))
;;

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

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

module Array = ArrayLabels ;;
module List  = struct
  include ListLabels ;;
  let rec repeat n a = if n = 0 then [] else a :: repeat (n - 1) a ;;
  let rec drop n a =
    if n = 0 then a
    else match a with
    | [] -> failwith "cannot take"
    | x :: xs -> drop (n - 1) xs ;;
end
module H = Hashtbl ;;

type t =
| Node of (char, t) H.t

let idx c = Char.code c - Char.code 'a' ;;

let create (ss : string list) =
  let rec insert tr s i n =
    if i = n then ()
    else
      let Node tr = tr in
      try
        let t = H.find tr s.[i] in
        insert t s (i + 1) n
      with
      | Not_found -> begin
        let nd = Node (H.create 10) in
        H.add tr s.[i] nd;
        insert nd s (i + 1) n;
      end in

  let tr = Node (H.create 10) in
  List.iter ss ~f:(fun s -> insert tr s 0 (String.length s));
  tr
;;

let is_nil tr = H.length tr = 0 ;;

type res = A | B | AB | ABC

let rec search (Node tr) =
  if is_nil tr then B
  else
    let vs = H.fold (fun c tr acc -> search tr :: acc) tr [] in
    if List.for_all vs ~f:(fun v -> v = B) then A
    else if List.for_all vs ~f:(fun v -> v = A) then B
    else if List.for_all vs ~f:(fun v -> v = AB) then ABC
    else if List.for_all vs ~f:(fun v -> v = ABC) then AB
    else if List.exists vs ~f:(fun v -> v = A) && List.exists vs ~f:(fun v -> v = B) then AB
    else if List.exists vs ~f:(fun v -> v = ABC) then AB
    else List.find vs ~f:(fun v -> v = A || v = B)
;;

let f v = if v = 0 then "First" else "Second" ;;

let main k (Node tr) =
  let res = search (Node tr) in
  match res with
  | AB -> pf "First\n"
  | ABC -> pf "Second\n"
  | A -> pf "%s\n" (f ((k + 1) mod 2))
  | B -> pf "Second\n"
;;

let () =
  sf "%d %d " (fun n k ->
    let acc = ref [] in
    for i = 0 to n - 1 do
      acc := sf "%s " (fun v -> v) :: !acc
    done;
    main k (create !acc))
;;

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

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

module Array = ArrayLabels ;;
module List  = struct
  include ListLabels ;;
  let rec repeat n a = if n = 0 then [] else a :: repeat (n - 1) a ;;
  let rec drop n a =
    if n = 0 then a
    else match a with
    | [] -> failwith "cannot take"
    | x :: xs -> drop (n - 1) xs ;;
end
module H = Hashtbl ;;

type t =
| Node of (char, t) H.t

let idx c = Char.code c - Char.code 'a' ;;

let create (ss : string list) =
  let rec insert tr s i n =
    if i = n then ()
    else
      let Node tr = tr in
      try
        let t = H.find tr s.[i] in
        insert t s (i + 1) n
      with
      | Not_found -> begin
        let nd = Node (H.create 10) in
        H.add tr s.[i] nd;
        insert nd s (i + 1) n;
      end in

  let tr = Node (H.create 10) in
  List.iter ss ~f:(fun s -> insert tr s 0 (String.length s));
  tr
;;

let is_nil tr = H.length tr = 0 ;;

type res = W | L | C | NC

let rec search (Node tr) =
  if is_nil tr then L
  else
    let vs = H.fold (fun c tr acc -> search tr :: acc) tr [] in
    if List.for_all vs ~f:(fun v -> v = L) then W
    else if List.for_all vs ~f:(fun v -> v = W) then L
    else if List.for_all vs ~f:(fun v -> v = C) then NC
    else if List.for_all vs ~f:(fun v -> v = NC) then C
    else if List.exists vs ~f:(fun v -> v = W) && List.exists vs ~f:(fun v -> v = L) then C
    else if List.exists vs ~f:(fun v -> v = NC) then C
    else if List.mem W vs then W
    else L
;;

let f v = if v = 0 then "First" else "Second" ;;

let main k (Node tr) =
  let res = search (Node tr) in
  match res with
  | C -> pf "First\n"
  | NC -> pf "Second\n"
  | W -> pf "%s\n" (f ((k + 1) mod 2))
  | L -> pf "Second\n"
;;

let () =
  sf "%d %d " (fun n k ->
    let acc = ref [] in
    for i = 0 to n - 1 do
      acc := sf "%s " (fun v -> v) :: !acc
    done;
    main k (create !acc))
;;


Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≤ ai + 1 ≤ 2·ai for any positive integer i (i < n).Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will get an expression consisting of n summands. The value of the resulting expression is the sum of all its elements. The task is to add signs "+" and "-" before each number so that the value of expression s meets the limits 0 ≤ s ≤ a1. Print a sequence of signs "+" and "-", satisfying the given limits. It is guaranteed that the solution for the problem exists.

The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 109) — the original array.  It is guaranteed that the condition ai ≤ ai + 1 ≤ 2·ai fulfills for any positive integer i (i < n).

In a single line print the sequence of n characters "+" and "-", where the i-th character is the sign that is placed in front of number ai. The value of the resulting expression s must fit into the limits 0 ≤ s ≤ a1. If there are multiple solutions, you are allowed to print any of them.

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

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

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

  let rec pass i s ac = if i<0 then ac else
    if s <= a.(i) then (
      let ac = 1::ac in
      let s = - (s-a.(i)) in
	pass (i-1) s ac
    ) else (
      let ac = 0::ac in
      let s = s-a.(i) in
	pass (i-1) s ac
    )
  in

  let sign_list = pass (n-1) 0 [] in

  let rec print p li = match li with [] -> ()
    | h::t ->
	let p = (p+h) mod 2 in
	  print_char(if p=0 then  '+' else '-');
	  print p t
  in
    print 1 sign_list;
    print_newline()


Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and k.

The only line of the input contains a single integer n (2 ≤ n ≤ 100 000).

The first line of the output contains a single integer k — maximum possible number of primes in representation. The second line should contain k primes with their sum equal to n. You can print them in any order. If there are several optimal solution, print any of them.

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

let print_looper n a =
    let rec loop i =
        if i < n
        then
            (Printf.printf "%d " a;
            loop (i + 1))
        else
            ()
    in loop 0

let wrapper (n, a, b) =
    Printf.printf "%d\n" n;
    print_looper a 2;
    print_looper b 3;
    Printf.printf "\n"

let solve n =
    let total = n / 2 in
    let modulo = n mod 2 in
    if modulo = 1
    then
        (total, total - 1, 1)
    else
        (total, total, 0)

let () = wrapper (solve (input ()))

open Printf
open Scanf

let rec print2 k = if k = 0 then () else let () = print2(k-1) in printf "%d " 2

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x) in
let () =
    let n = read_int() in
    let () = printf "%d\n" (n/2) in
    if n mod 2 = 0 then
        print2 (n/2)
    else let () = print2 (n/2-1) in printf "%d" 3 in
()

let main () =
  let n = read_int () in
    let k = n / 2 in
    print_int k; print_newline ();
    for i = 1 to k-1 do
      print_string "2 "
    done;
    print_int (n - 2 * (k-1))

let () = main ()

open Printf
open Scanf

(* int -> int list
   create_range(n) = [2,..., k-1] len = k-2
 *)
let rec create_range k = if k <= 2 then [] else
                        List.append (create_range (k-1)) [k-1] in

(* int -> bool
   true iff n is a prime
 *)
let isPrime n = if n < 2 then false else
                if n == 2 then true else
                let divisible k = if (n mod k) = 0 then true else false in
                let range = create_range n in
                not (List.exists divisible range) in

(* int -> int list
   length(res) = n-1 and res[i] = answer for i+2 *)

let rec produce_table n range primes = if n = 2 then [1] else
                      let res_table = produce_table (n-1) primes range in
                      let fold_help prime res = if n-prime < 2 then res else
                                                let index = n-prime-2 in
                                                let pot = List.nth res_table index in
                                                if pot > res then pot else res in
                      let new_val = 1 + List.fold_right fold_help primes 0 in
                      List.append res_table [new_val] in

(* int -> int list
   returns a list of primes
   *)

let rec produce_primes n res_table range primes = if n = 2 then [2] else
                       let help a = let fst = List.nth res_table (a-2) in
                                    let snd = List.nth res_table (n-2) in
                                    if snd = fst + 1 then true else false in
                        let fold_help a b = if n-a > 2 && help (n-a) then
                                            [a] else b in
                        let index = List.fold_right fold_help primes [] in
                        match index with
                              [prime] -> prime::(produce_primes (n-prime) res_table range primes)
                            |  _ -> [n] in

(* processing input *)

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x) in
let () =
    let n = read_int() in
    let range = create_range(n) in
    let primes = List.filter isPrime range in
    let res_table = produce_table n range primes in
    let answer = produce_primes n res_table range primes in
    let len = List.length answer in
    let () = printf "%d\n" len in
    let helpero a = printf "%d " a in
    List.iter helpero answer in
()


You are given two arrays $$$a$$$ and $$$b$$$ of length $$$n$$$. Array $$$a$$$ contains each odd integer from $$$1$$$ to $$$2n$$$ in an arbitrary order, and array $$$b$$$ contains each even integer from $$$1$$$ to $$$2n$$$ in an arbitrary order.You can perform the following operation on those arrays:   choose one of the two arrays  pick an index $$$i$$$ from $$$1$$$ to $$$n-1$$$  swap the $$$i$$$-th and the $$$(i+1)$$$-th elements of the chosen array  Compute the minimum number of operations needed to make array $$$a$$$ lexicographically smaller than array $$$b$$$.For two different arrays $$$x$$$ and $$$y$$$ of the same length $$$n$$$, we say that $$$x$$$ is lexicographically smaller than $$$y$$$ if in the first position where $$$x$$$ and $$$y$$$ differ, the array $$$x$$$ has a smaller element than the corresponding element in $$$y$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the arrays. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 2n$$$, all $$$a_i$$$ are odd and pairwise distinct) — array $$$a$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 2n$$$, all $$$b_i$$$ are even and pairwise distinct) — array $$$b$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print one integer: the minimum number of operations needed to make array $$$a$$$ lexicographically smaller than array $$$b$$$. We can show that an answer always exists.

NoteIn the first example, the array $$$a$$$ is already lexicographically smaller than array $$$b$$$, so no operations are required.In the second example, we can swap $$$5$$$ and $$$3$$$ and then swap $$$2$$$ and $$$4$$$, which results in $$$[3, 5, 1]$$$ and $$$[4, 2, 6]$$$. Another correct way is to swap $$$3$$$ and $$$1$$$ and then swap $$$5$$$ and $$$1$$$, which results in $$$[1, 5, 3]$$$ and $$$[2, 4, 6]$$$. Yet another correct way is to swap $$$4$$$ and $$$6$$$ and then swap $$$2$$$ and $$$6$$$, which results in $$$[5, 3, 1]$$$ and $$$[6, 2, 4]$$$.

open Printf
open Scanf

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

let l2n c = (int_of_char c) - (int_of_char '0')

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_string _ = bscanf Scanning.stdin " %s " (fun x -> x)
let () =
  let cases = read_int() in
  for case = 1 to cases do
    let n = read_int() in
    let a = Array.init n (fun i -> (read_int(), i)) in
    let b = Array.init n (fun j -> (read_int(), j)) in

    Array.sort compare a;
    Array.sort compare b;

    let sm = Array.make n 0 in  (* suffix min *)

    sm.(n-1) <- snd b.(n-1);
    for k = n-2 downto 0 do
      sm.(k) <- min sm.(k+1) (snd b.(k))
    done;

    let answer = minf 0 (n-1) (fun i -> (snd a.(i)) + sm.(i)) in
    printf "%d\n" answer
  done


Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions:  She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her .  Let ui be the cost of the i-th cheapest stone (the cost that will be on the i-th place if we arrange all the stone costs in non-decreasing order). This time she will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should tell her . For every question you should give the correct answer, or Kuriyama Mirai will say "fuyukai desu" and then become unhappy.

The first line contains an integer n (1 ≤ n ≤ 105). The second line contains n integers: v1, v2, ..., vn (1 ≤ vi ≤ 109) — costs of the stones.  The third line contains an integer m (1 ≤ m ≤ 105) — the number of Kuriyama Mirai's questions. Then follow m lines, each line contains three integers type, l and r (1 ≤ l ≤ r ≤ n; 1 ≤ type ≤ 2), describing a question. If type equal to 1, then you should output the answer for the first question, else you should output the answer for the second one.

Print m lines. Each line must contain an integer — the answer to Kuriyama Mirai's question. Print the answers to the questions in the order of input.

NotePlease note that the answers to the questions may overflow 32-bit integer type.

let read_int()=Scanf.scanf "%d " (fun x->x);;
let n=read_int();;
let tab1=Array.make n 0;;
let tab2=Array.make n 0;;
let sum1=Array.make n Int64.zero;;
let sum2=Array.make n Int64.zero;;
for i=0 to n-1 do
   let x=read_int() in tab1.(i)<-x;tab2.(i)<-x
done;;
Array.sort (fun x y -> if x=y then 0 else if x<y then -1 else 1) tab2;;
sum1.(0)<-Int64.of_int(tab1.(0));;
sum2.(0)<-Int64.of_int(tab2.(0));;
for i=1 to n-1 do
   sum1.(i)<-Int64.add sum1.(i-1) (Int64.of_int(tab1.(i)));
   sum2.(i)<-Int64.add sum2.(i-1) (Int64.of_int(tab2.(i)))
done;;

let m=read_int();;
for i=1 to m do
   let typ=read_int() and l=read_int() and r=read_int() in
   if typ=1 then
      begin
      Printf.printf "%s\n" (if l=1 then Int64.to_string(sum1.(r-1)) else Int64.to_string(Int64.sub sum1.(r-1) sum1.(l-2)))
      end
   else
      begin
      Printf.printf "%s\n" (if l=1 then Int64.to_string(sum2.(r-1)) else Int64.to_string(Int64.sub sum2.(r-1) sum2.(l-2)))
      end
done;;

let read_int()=Scanf.scanf "%d " (fun x->x);;
let n=read_int();;
let tab1=Array.make n 0;;
let tab2=Array.make n 0;;
let sum1=Array.make n 0;;
let sum2=Array.make n 0;;
for i=0 to n-1 do
   let x=read_int() in tab1.(i)<-x;tab2.(i)<-x
done;;
Array.sort (fun x y -> if x=y then 0 else if x<y then -1 else 1) tab2;;
sum1.(0)<-tab1.(0);;
sum2.(0)<-tab2.(0);;
for i=1 to n-1 do
   sum1.(i)<-sum1.(i-1)+tab1.(i);
   sum2.(i)<-sum2.(i-1)+tab2.(i)
done;;

let m=read_int();;
for i=1 to m do
   let typ=read_int() and l=read_int() and r=read_int() in
   if typ=1 then
      begin
      Printf.printf "%d\n" (if l=1 then sum1.(r-1) else sum1.(r-1)-sum1.(l-2))
      end
   else
      begin
      Printf.printf "%d\n" (if l=1 then sum2.(r-1) else sum2.(r-1)-sum2.(l-2))
      end
done;;


Ivan is a novice painter. He has $$$n$$$ dyes of different colors. He also knows exactly $$$m$$$ pairs of colors which harmonize with each other.Ivan also enjoy playing chess. He has $$$5000$$$ rooks. He wants to take $$$k$$$ rooks, paint each of them in one of $$$n$$$ colors and then place this $$$k$$$ rooks on a chessboard of size $$$10^{9} \times 10^{9}$$$.Let's call the set of rooks on the board connected if from any rook we can get to any other rook in this set moving only through cells with rooks from this set. Assume that rooks can jump over other rooks, in other words a rook can go to any cell which shares vertical and to any cell which shares horizontal.Ivan wants his arrangement of rooks to have following properties: For any color there is a rook of this color on a board; For any color the set of rooks of this color is connected; For any two different colors $$$a$$$ $$$b$$$ union of set of rooks of color $$$a$$$ and set of rooks of color $$$b$$$ is connected if and only if this two colors harmonize with each other.Please help Ivan find such an arrangement.

The first line of input contains $$$2$$$ integers $$$n$$$, $$$m$$$ ($$$1 \le n \le 100$$$, $$$0 \le m \le min(1000, \,\, \frac{n(n-1)}{2})$$$) — number of colors and number of pairs of colors which harmonize with each other. In next $$$m$$$ lines pairs of colors which harmonize with each other are listed. Colors are numbered from $$$1$$$ to $$$n$$$. It is guaranteed that no pair occurs twice in this list.

Print $$$n$$$ blocks, $$$i$$$-th of them describes rooks of $$$i$$$-th color. In the first line of block print one number $$$a_{i}$$$ ($$$1 \le a_{i} \le 5000$$$) — number of rooks of color $$$i$$$. In each of next $$$a_{i}$$$ lines print two integers $$$x$$$ and $$$y$$$ ($$$1 \le x, \,\, y \le 10^{9}$$$) — coordinates of the next rook. All rooks must be on different cells. Total number of rooks must not exceed $$$5000$$$. It is guaranteed that the solution exists.

NoteRooks arrangements for all three examples (red is color $$$1$$$, green is color $$$2$$$ and blue is color $$$3$$$).

open Printf open Scanf
module Lib = struct
	let i32,i64,ist = Int64.(to_int,of_int,to_string)
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)
	let labs = Int64.abs
	let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)
	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 (%=) r v = r := !r % v
	(* math *)
	let ceildiv p q = (p+q-1L) / q
	let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
	let lcm m n = m / gcd m n * n
	module I64_infix = struct
		let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =
			let open Int64 in
			(logand),(logor),(logxor),lognot,
			(fun u v -> shift_left u (i32 v)),
			(fun u v -> shift_right u (i32 v)),
			(fun u v -> shift_right_logical u (i32 v))
	end
	(* input *)
	let input_i64_array n = Array.init (i32 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 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)
	(* utils *)
	external id : 'a -> 'a = "%identity"
	let alen a = i64 @@ Array.length a
	let llen l = i64 @@  List.length l
	let string_of_list ?(separator=" ") f ls = ls |> List.map f |> String.concat separator
	let string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
	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 fail _ = failwith "fail"
	let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]
	let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev
	let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten
	let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a
	let binary_search ng ok f = let d = if ng < ok then 1L else -1L in
		let rec f0 ng ok =
			if labs (ok - ng) <= 1L then ok
			else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
		in f0 (ng-1L*d) (ok+1L*d)
	(* imperative *)
	let rep f t fbod =
		let rep0 f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i + 1L done
		in rep0 f t fbod
	let repb f t fbod =
		let rep0 f t fbod = let i,c = ref f,ref true in while !i <= t && !c do match fbod !i with | `Break -> c := false | `Ok -> i := !i + 1L done; !c
		in if f<=t then rep0 f t fbod
		else rep0 t f @@ fun v -> fbod @@ f + t - v
	let repm f t m0 fbod =
		let rep0 f t m0 fbod =
			let i,c,m = ref f,ref true,ref m0 in while !i<=t && !c do match fbod !m !i with | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + 1L done; !m
		in if f<=t then rep0 f t m0 fbod
		else rep0 t f m0 @@ fun u v -> fbod u @@ f + t - v
	let repi f t fbod =
		let rep0 f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ 1 done
		in if f<=t then rep0 f t fbod else rep0 t f @@ fun v -> fbod @@ f +$ t -$ v
	let repb f t fbod =
		let rep0 f t fbod = let i,c = ref f,ref true in while !i <= t && !c do
		match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ 1 done
		in if f<=t then rep0 f t fbod
		else rep0 t f @@ fun v -> fbod @@ f +$ t -$ v
	let repm f t m0 fbod =
		let rep0 f t m0 fbod =
			let i,c,m = ref f,ref true,ref m0 in while !i<=t && !c do match fbod !m !i with | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ 1 done; !m
		in if f<=t then rep0 f t m0 fbod
		else rep0 t f m0 @@ fun u v -> fbod u @@ f +$ t -$ v
	(* output *)
	let print_list_mle f ls = string_of_list f ls |> print_endline
	let print_array_mle f a = string_of_array f a |> print_endline
	let print_list f ls = ls |> List.iter (fun v -> printf "%s " @@ f v); print_newline ()
	let print_array f a = a |> Array.iter (fun v -> printf "%s " @@ f v); print_newline ()
	(* debug *)
	let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)
	let dump_i64_list ls = print_list ist ls
	let dump_i64_array a = print_array ist a
end open Lib

let () =
	let n,m = get_2_i64 0 in
	let add = Array.make (i32 n) [] in
	rep 1L m (fun idx ->
		let p,q = get_2_i64 0 in
		let i,j = i32 p-$1,i32 q-$1 in
		add.(i) <- (10000L+idx)::add.(i);
		add.(j) <- (10000L+idx)::add.(j);
	);
	Array.iteri (fun i v ->
		let i=i+$1 in
		printf "%Ld\n%d %d\n" (llen v+1L) i i;
		List.iter (fun w ->
			printf "%d %Ld\n" i w
		) v
	) add

open Printf open Scanf
module Lib = struct
	let i32,i64,ist = Int64.(to_int,of_int,to_string)
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)
	let labs = Int64.abs
	let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)
	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 (%=) r v = r := !r % v
	(* math *)
	let ceildiv p q = (p+q-1L) / q
	let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
	let lcm m n = m / gcd m n * n
	module I64_infix = struct
		let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =
			let open Int64 in
			(logand),(logor),(logxor),lognot,
			(fun u v -> shift_left u (i32 v)),
			(fun u v -> shift_right u (i32 v)),
			(fun u v -> shift_right_logical u (i32 v))
	end
	(* input *)
	let input_i64_array n = Array.init (i32 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 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)
	(* utils *)
	external id : 'a -> 'a = "%identity"
	let alen a = i64 @@ Array.length a
	let llen l = i64 @@  List.length l
	let string_of_list ?(separator=" ") f ls = ls |> List.map f |> String.concat separator
	let string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
	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 fail _ = failwith "fail"
	let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]
	let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev
	let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten
	let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a
	let binary_search ng ok f = let d = if ng < ok then 1L else -1L in
		let rec f0 ng ok =
			if labs (ok - ng) <= 1L then ok
			else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
		in f0 (ng-1L*d) (ok+1L*d)
	(* imperative *)
	let rep f t fbod =
		let rep0 f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i + 1L done
		in if f<=t then rep0 f t fbod else rep0 t f @@ fun v -> fbod @@ f + t - v
	let repb f t fbod =
		let rep0 f t fbod = let i,c = ref f,ref true in while !i <= t && !c do match fbod !i with | `Break -> c := false | `Ok -> i := !i + 1L done; !c
		in if f<=t then rep0 f t fbod
		else rep0 t f @@ fun v -> fbod @@ f + t - v
	let repm f t m0 fbod =
		let rep0 f t m0 fbod =
			let i,c,m = ref f,ref true,ref m0 in while !i<=t && !c do match fbod !m !i with | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + 1L done; !m
		in if f<=t then rep0 f t m0 fbod
		else rep0 t f m0 @@ fun u v -> fbod u @@ f + t - v
	let repi f t fbod =
		let rep0 f t fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ 1 done
		in if f<=t then rep0 f t fbod else rep0 t f @@ fun v -> fbod @@ f +$ t -$ v
	let repb f t fbod =
		let rep0 f t fbod = let i,c = ref f,ref true in while !i <= t && !c do
		match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ 1 done
		in if f<=t then rep0 f t fbod
		else rep0 t f @@ fun v -> fbod @@ f +$ t -$ v
	let repm f t m0 fbod =
		let rep0 f t m0 fbod =
			let i,c,m = ref f,ref true,ref m0 in while !i<=t && !c do match fbod !m !i with | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ 1 done; !m
		in if f<=t then rep0 f t m0 fbod
		else rep0 t f m0 @@ fun u v -> fbod u @@ f +$ t -$ v
	(* output *)
	let print_list_mle f ls = string_of_list f ls |> print_endline
	let print_array_mle f a = string_of_array f a |> print_endline
	let print_list f ls = ls |> List.iter (fun v -> printf "%s " @@ f v); print_newline ()
	let print_array f a = a |> Array.iter (fun v -> printf "%s " @@ f v); print_newline ()
	(* debug *)
	let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)
	let dump_i64_list ls = print_list ist ls
	let dump_i64_array a = print_array ist a
end open Lib

let () =
	let n,m = get_2_i64 0 in
	let add = Array.make (i32 n) [] in
	rep 1L m (fun _ ->
		let p,q = get_2_i64 0 in
		let i = i32 p -$ 1 in
		add.(i) <- q::add.(i);
	);
	Array.iteri (fun i v ->
		let i=i+$1 in
		printf "%Ld\n%d %d\n" (llen v+1L) i i;
		List.iter (fun w ->
			printf "%d %Ld\n" i w
		) v
	) add


Notice that the memory limit is non-standard.Recently Arthur and Sasha have studied correct bracket sequences. Arthur understood this topic perfectly and become so amazed about correct bracket sequences, so he even got himself a favorite correct bracket sequence of length 2n. Unlike Arthur, Sasha understood the topic very badly, and broke Arthur's favorite correct bracket sequence just to spite him.All Arthur remembers about his favorite sequence is for each opening parenthesis ('(') the approximate distance to the corresponding closing one (')'). For the i-th opening bracket he remembers the segment [li, ri], containing the distance to the corresponding closing bracket.Formally speaking, for the i-th opening bracket (in order from left to right) we know that the difference of its position and the position of the corresponding closing bracket belongs to the segment [li, ri].Help Arthur restore his favorite correct bracket sequence!

The first line contains integer n (1 ≤ n ≤ 600), the number of opening brackets in Arthur's favorite correct bracket sequence.  Next n lines contain numbers li and ri (1 ≤ li ≤ ri < 2n), representing the segment where lies the distance from the i-th opening bracket and the corresponding closing one.  The descriptions of the segments are given in the order in which the opening brackets occur in Arthur's favorite sequence if we list them from left to right.

If it is possible to restore the correct bracket sequence by the given data, print any possible choice. If Arthur got something wrong, and there are no sequences corresponding to the given information, print a single line "IMPOSSIBLE" (without the quotes).

let () = Scanf.scanf "%d\n" (fun n ->
  let s = Stack.create () in
  let a = Array.create n (0, 0) in
  let b = Buffer.create (2 * n) in
  let p = ref 1 in
  for i = 0 to n - 1 do
    (* add bounds to array *)
    Scanf.scanf "%d %d\n" (fun x y -> a.(i) <- (x + !p, y + !p));
    (* push this bracket to the stack as open *)
    Stack.push i s;
    Buffer.add_char b '(';
    incr p;

    (* greedily close brackets *)
    while not (Stack.is_empty s) && !p >= fst a.(Stack.top s) && !p <= snd a.(Stack.top s) do
      Buffer.add_char b ')';
      ignore (Stack.pop s);
      incr p
    done;
  done;
  if Stack.is_empty s then
    print_endline (Buffer.contents b)
  else
    print_endline "IMPOSSIBLE"
)


Pavel has several sticks with lengths equal to powers of two.He has $$$a_0$$$ sticks of length $$$2^0 = 1$$$, $$$a_1$$$ sticks of length $$$2^1 = 2$$$, ..., $$$a_{n-1}$$$ sticks of length $$$2^{n-1}$$$. Pavel wants to make the maximum possible number of triangles using these sticks. The triangles should have strictly positive area, each stick can be used in at most one triangle.It is forbidden to break sticks, and each triangle should consist of exactly three sticks.Find the maximum possible number of triangles.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 300\,000$$$) — the number of different lengths of sticks. The second line contains $$$n$$$ integers $$$a_0$$$, $$$a_1$$$, ..., $$$a_{n-1}$$$ ($$$1 \leq a_i \leq 10^9$$$), where $$$a_i$$$ is the number of sticks with the length equal to $$$2^i$$$.

Print a single integer — the maximum possible number of non-degenerate triangles that Pavel can make.

NoteIn the first example, Pavel can, for example, make this set of triangles (the lengths of the sides of the triangles are listed): $$$(2^0, 2^4, 2^4)$$$, $$$(2^1, 2^3, 2^3)$$$, $$$(2^1, 2^2, 2^2)$$$.In the second example, Pavel cannot make a single triangle.In the third example, Pavel can, for example, create this set of triangles (the lengths of the sides of the triangles are listed): $$$(2^0, 2^0, 2^0)$$$, $$$(2^1, 2^1, 2^1)$$$, $$$(2^2, 2^2, 2^2)$$$.

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

let () =
  let n = Scanf.scanf "%d\n" (fun x -> x) in
  let a = Array.make n Int64.zero in
  let res = ref Int64.zero in
  let ones = ref Int64.zero in
  for i = 0 to n-1 do
    let m = Scanf.scanf "%Ld " (fun x -> x) in
    let m2 = m / 2L in
    let x = min (m / 2L) !ones in
    res := !res + x;
    ones := !ones -- x;
    let m = m -- x * 2L in
    a.(i) <- m;
    let m3 = m / 3L in
    res := !res + m3;
    ones := !ones + m -- m3 * 3L;
  done;
  Printf.printf "%Ld" !res
;;

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

let () =
  let n = Scanf.scanf "%d\n" (fun x -> x) in
  let a = Array.make n Int64.zero in
  let res = ref Int64.zero in
  let ones = ref Int64.zero in
  for i = 0 to n-1 do
    let m = Scanf.scanf "%Ld " (fun x -> x) in
    let m2 = m / (Int64.of_int 2) in
    let x = min (m / (Int64.of_int 2)) !ones in
    res := !res + x;
    ones := !ones -- x;
    let m = m -- x * Int64.of_int 2 in
    a.(i) <- m;
    let m3 = m / (Int64.of_int 3) in
    res := !res + m3;
    ones := !ones + m -- m3 * (Int64.of_int 3);
  done;
  Printf.printf "%Ld" !res
;;

let () =
  let n = Scanf.scanf "%d\n" (fun x -> x) in
  let a = Array.make n 0 in
  let res = ref 0 in
  let ones = ref 0 in
  for i = 0 to n-1 do
    let m = Scanf.scanf "%d " (fun x -> x) in
    let m2 = m / 2 in
    let x = min (m / 2) !ones in
    res := !res + x;
    ones := !ones - x;
    let m = m - x * 2 in
    let m3 = m / 3 in
    res := !res + m3;
    ones := !ones + m - m3 * 3;
  done;
  Printf.printf "%d" !res
;;

let () =
  let n = Scanf.scanf "%d\n" (fun x -> x) in
  let res = ref 0 in
  for i = 0 to n-1 do
    let m = Scanf.scanf "%d " (fun x -> x/3) in
    res := !res + m
  done;
  Printf.printf "%d" !res
;;

let () =
  let n = Scanf.scanf "%d\n" (fun x -> x) in
  let a = Array.make n 0 in
  let res = ref 0 in
  for i = 0 to n-1 do
    let m = Scanf.scanf "%d " (fun x -> x) in
    let m3 = m / 3 in
    res := !res + m3;
    a.(i) <- m - m3 * 3;
  done;
  let ones = ref 0 in
  Array.iter (function
      | 2 when !ones > 0 -> decr ones; incr res;
      | 2 -> incr ones; incr ones;
      | 1 -> incr ones;
      | _ -> ()
    ) a;
  Printf.printf "%d" !res
;;

let () =
  let n = Scanf.scanf "%d\n" (fun x -> x) in
  let a = Array.make n 0 in
  let res = ref 0 in
  for i = 0 to n-1 do
    let m = Scanf.scanf "%d " (fun x -> x) in
    let m3 = m / 3 in
    res := !res + m3;
    a.(i) <- m - m3;
  done;
  let ones = ref 0 in
  Array.iter (function
      | 2 when !ones > 0 -> decr ones; incr res;
      | 2 -> incr ones; incr ones;
      | 1 -> incr ones;
      | _ -> ()
    ) a;
  Printf.printf "%d" !res
;;


Let's call an array good if there is an element in the array that equals to the sum of all other elements. For example, the array $$$a=[1, 3, 3, 7]$$$ is good because there is the element $$$a_4=7$$$ which equals to the sum $$$1 + 3 + 3$$$.You are given an array $$$a$$$ consisting of $$$n$$$ integers. Your task is to print all indices $$$j$$$ of this array such that after removing the $$$j$$$-th element from the array it will be good (let's call such indices nice).For example, if $$$a=[8, 3, 5, 2]$$$, the nice indices are $$$1$$$ and $$$4$$$:   if you remove $$$a_1$$$, the array will look like $$$[3, 5, 2]$$$ and it is good;  if you remove $$$a_4$$$, the array will look like $$$[8, 3, 5]$$$ and it is good. You have to consider all removals independently, i. e. remove the element, check if the resulting array is good, and return the element into the array.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$) — elements of the array $$$a$$$.

In the first line print one integer $$$k$$$ — the number of indices $$$j$$$ of the array $$$a$$$ such that after removing the $$$j$$$-th element from the array it will be good (i.e. print the number of the nice indices). In the second line print $$$k$$$ distinct integers $$$j_1, j_2, \dots, j_k$$$ in any order — nice indices of the array $$$a$$$. If there are no such indices in the array $$$a$$$, just print $$$0$$$ in the first line and leave the second line empty or do not print it at all.

NoteIn the first example you can remove any element with the value $$$2$$$ so the array will look like $$$[5, 1, 2, 2]$$$. The sum of this array is $$$10$$$ and there is an element equals to the sum of remaining elements ($$$5 = 1 + 2 + 2$$$).In the second example you can remove $$$8$$$ so the array will look like $$$[3, 5, 2]$$$. The sum of this array is $$$10$$$ and there is an element equals to the sum of remaining elements ($$$5 = 3 + 2$$$). You can also remove $$$2$$$ so the array will look like $$$[8, 3, 5]$$$. The sum of this array is $$$16$$$ and there is an element equals to the sum of remaining elements ($$$8 = 3 + 5$$$).In the third example you cannot make the given array good by removing exactly one element.

(* Problem 2 of round 521*)
open Scanf;;
open String;;
open Num;;

(*These are some utility functions*)
module U = struct
  let mprint z =
    print_endline (Num.string_of_num z);;

  let read_one format =
    let n = Scanf.scanf format (fun x -> x) in
    n;;

  let read_one_number () =
    let n = read_one "%d " in
    n

  let read_array n a =
    for i = 0 to n-1 do
      let n = read_one_number () in
      a.(i) <- n
    done

end

(*The solutions*)

let n = U.read_one_number ()
let a = Array.make n 0
let () = U.read_array n a

module H = Hashtbl
let t = H.create n

(*
let () =
  Array.iter (fun x-> print_int x; print_endline "") a
*)

open Num;;
let n1 = num_of_int 1;;

let total = ref (num_of_int 0)
let () =
  Array.iter (fun x-> H.add t (num_of_int x) (num_of_int 0)) a;
  Array.iter (fun x-> H.replace t (num_of_int x) (n1+/(H.find t (num_of_int x)))) a;
  Array.iter (fun x -> total := !total +/ (num_of_int x)) a;;

(*
print_int !total; print_endline ""
let () =
  H.iter (fun k v -> Printf.printf "%d %d\n" k v) t
*)

let my_find x =
  try H.find t x
  with Not_found -> num_of_int 0

let n0 = num_of_int 0;;

let is_good x =
  let r = !total -/ x in
  let m = int_of_num (mod_num r (num_of_int 2)) in
  match m with
    1 -> false
  | _ -> begin
      let r1 = r // (num_of_int 2) in
      let rslt = int_of_num (my_find r1) in
      match rslt with
        0 -> false
      | 1 -> begin
          if eq_num r1 x then
            false
          else
            true
        end
      | _ -> true
    end

let s = H.create n;;

let () =
  Array.iteri (fun i x -> if (is_good (num_of_int x)) then
                  begin H.add s (num_of_int (i + 1) ) n0 end
              ) a
;;

let () =
  print_int (H.length s); print_endline "";
  H.iter (fun k v -> Printf.printf "%d " (int_of_num k)) s

open Printf open Scanf
module Lib = struct
  let i32,i64,ist = Int64.(to_int,of_int,to_string)
  let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)
  let labs = Int64.abs
  let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)
  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 (%=) r v = r := !r % v
  let max_i64,min_i64 = Int64.(max_int,min_int)
  (* math *)
  let ceildiv p q = (p+q-1L) / q
  let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
  let lcm m n = m / gcd m n * n
  module I64_infix = struct
    let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =
      let open Int64 in
      (logand),(logor),(logxor),lognot,
      (fun u v -> shift_left u (i32 v)),
      (fun u v -> shift_right u (i32 v)),
      (fun u v -> shift_right_logical u (i32 v))
  end
  (* input *)
  let input_i64_array n = Array.init (i32 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 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)
  (* utils *)
  external id : 'a -> 'a = "%identity"
  let ( *< ) f g x = f (g x)
  let ( *> ) f g x = g (f x)
  let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)
  let alen a = i64 @@ Array.length a
  let llen l = i64 @@  List.length l
  let string_of_list ?(separator=" ") f ls = ls |> List.map f |> String.concat separator
  let string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
  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 fail _ = failwith "fail"
  let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]
  let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev
  let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten
  let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a
  let binary_search ng ok f = let d = if ng < ok then 1L else -1L in
    let rec f0 ng ok =
      if labs (ok - ng) <= 1L then ok
      else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
    in f0 (ng-1L*d) (ok+1L*d)
  let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)
  let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >  v)
  let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)
  let rec fix f x = f (fix f) x
  let fix_memo ?(size=10000) f x =
    let tb = Hashtbl.create ~random:true size in
    let rec f0 x =
      try Hashtbl.find tb x with
      | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)
    in f0 x
  (* imperative *)
  let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done
  let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done
  let repm f t ?(stride=1L) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m
  let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done
  let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done
  let repim f t ?(stride=1) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m
  let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v
  let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v
  let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v
  let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v
  (* output *)
  let print_list_mle f ls = string_of_list f ls |> print_endline
  let print_array_mle f a = string_of_array f a |> print_endline
  let print_list f ls = ls |> List.iter (fun v -> printf "%s " @@ f v); print_newline ()
  let print_array f a = a |> Array.iter (fun v -> printf "%s " @@ f v); print_newline ()
  (* debug *)
  let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)
  let dump_i64_list ls = print_list ist ls
  let dump_i64_array a = print_array ist a
end open Lib open Array
module IMap = Map.Make (Int64)
let count a = (* (value,count) *)
  Array.fold_left (fun u v -> IMap.add v (1L + try IMap.find v u with Not_found -> 0L) u) IMap.empty a
let () =
  let n = get_i64 0 in
  let a = input_i64_array n in
  let mp = count a in
  let sum = fold_left (+) 0L a in
  let ans = ref [] in
  iteri (fun i v ->
    let rest = sum - v in
    if rest mod 2L = 0L then
    try
      let c = IMap.find (rest/2L) mp in
      if v = rest/2L then (
        if c >= 2L then ans := (i+$1) :: !ans
      ) else if c >= 1L then ans := (i+$1) :: !ans
    with Not_found -> ()
  ) a;
  printf "%Ld\n" @@ llen !ans;
  print_list string_of_int !ans

(* Problem 2 of round 521*)
open Scanf;;
open String;;
open Num;;

(*These are some utility functions*)
module U = struct
  let mprint z =
    print_endline (Num.string_of_num z);;

  let read_one format =
    let n = Scanf.scanf format (fun x -> x) in
    n;;

  let read_one_number () =
    let n = read_one "%d " in
    n

  let read_array n a =
    for i = 0 to n-1 do
      let n = read_one_number () in
      a.(i) <- n
    done

end

(*The solutions*)

let n = U.read_one_number ()
let a = Array.make n 0
let () = U.read_array n a

module H = Hashtbl
let t = H.create n

(*
let () =
  Array.iter (fun x-> print_int x; print_endline "") a
*)

open Num;;
let n1 = num_of_int 1;;

let total = ref (num_of_int 0)
let () =
  Array.iter (fun x-> H.add t (num_of_int x) (num_of_int 0)) a;
  Array.iter (fun x-> H.replace t (num_of_int x) (n1+/(H.find t (num_of_int x)))) a;
  Array.iter (fun x -> total := !total +/ (num_of_int x)) a;;

(*
print_int !total; print_endline ""
let () =
  H.iter (fun k v -> Printf.printf "%d %d\n" k v) t
*)

let my_find x =
  try H.find t x
  with Not_found -> num_of_int 0

let n0 = num_of_int 0;;

let is_good x =
  let r = !total -/ x in
  let m = int_of_num (mod_num r (num_of_int 2)) in
  match m with
    1 -> false
  | _ -> begin
      let r1 = r // (num_of_int 2) in
      let rslt = int_of_num (my_find r1) in
      match rslt with
        0 -> false
      | 1 -> begin
          if r1 == x then
            false
          else
            true
        end
      | _ -> true
    end

let s = H.create n;;

let () =
  Array.iteri (fun i x -> if (is_good (num_of_int x)) then
                  begin H.add s (num_of_int (i + 1) ) n0 end
              ) a
;;

let () =
  print_int (H.length s); print_endline "";
  H.iter (fun k v -> Printf.printf "%d " (int_of_num k)) s

(* Problem 2 of round 521*)
open Scanf;;
open String;;
open Num;;

(*These are some utility functions*)
module U = struct
  let mprint z =
    print_endline (Num.string_of_num z);;

  let read_one format =
    let n = Scanf.scanf format (fun x -> x) in
    n;;

  let read_one_number () =
    let n = read_one "%d " in
    n

  let read_array n a =
    for i = 0 to n-1 do
      let n = read_one_number () in
      a.(i) <- n
    done

end

(*The solutions*)

let n = U.read_one_number ()
let a = Array.make n 0
let () = U.read_array n a

module H = Hashtbl
let t = H.create n

(*
let () =
  Array.iter (fun x-> print_int x; print_endline "") a
*)

let total = ref 0
let () =
  Array.iter (fun x-> H.add t x 0) a;
  Array.iter (fun x-> H.replace t x (1+(H.find t x))) a;
  Array.iter (fun x -> total := !total + x) a;;

(*
print_int !total; print_endline ""
let () =
  H.iter (fun k v -> Printf.printf "%d %d\n" k v) t
*)

let my_find x =
  try H.find t x
  with Not_found -> 0

let is_good x =
  let r = !total -x in
  match r mod 2 with
    1 -> false
  | _ -> begin
      let r1 = r / 2 in
      let rslt = my_find r1 in
      match rslt with
        0 -> false
      | 1 -> begin
          if r1 == x then
            false
          else
            true
        end
      | _ -> true
    end

let s = H.create n;;

let () =
  Array.iteri (fun i x -> if (is_good x) then
                  begin H.add s (i+1) 0 end
              ) a
;;

let () =
  print_int (H.length s); print_endline "";
  H.iter (fun k v -> Printf.printf "%d " k) s

open Printf open Scanf
module Lib = struct
  let i32,i64,ist = Int64.(to_int,of_int,to_string)
  let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)
  let labs = Int64.abs
  let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)
  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 (%=) r v = r := !r % v
  let max_i64,min_i64 = Int64.(max_int,min_int)
  (* math *)
  let ceildiv p q = (p+q-1L) / q
  let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
  let lcm m n = m / gcd m n * n
  module I64_infix = struct
    let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) =
      let open Int64 in
      (logand),(logor),(logxor),lognot,
      (fun u v -> shift_left u (i32 v)),
      (fun u v -> shift_right u (i32 v)),
      (fun u v -> shift_right_logical u (i32 v))
  end
  (* input *)
  let input_i64_array n = Array.init (i32 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 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)
  (* utils *)
  external id : 'a -> 'a = "%identity"
  let ( *< ) f g x = f (g x)
  let ( *> ) f g x = g (f x)
  let rv f p q = f q p (* ex. 24 |> rv (/) 6 *)
  let alen a = i64 @@ Array.length a
  let llen l = i64 @@  List.length l
  let string_of_list ?(separator=" ") f ls = ls |> List.map f |> String.concat separator
  let string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
  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 fail _ = failwith "fail"
  let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]
  let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev
  let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten
  let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a
  let binary_search ng ok f = let d = if ng < ok then 1L else -1L in
    let rec f0 ng ok =
      if labs (ok - ng) <= 1L then ok
      else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
    in f0 (ng-1L*d) (ok+1L*d)
  let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)
  let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >  v)
  let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)
  let rec fix f x = f (fix f) x
  let fix_memo ?(size=10000) f x =
    let tb = Hashtbl.create ~random:true size in
    let rec f0 x =
      try Hashtbl.find tb x with
      | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)
    in f0 x
  (* imperative *)
  let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done
  let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done
  let repm f t ?(stride=1L) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m
  let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done
  let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done
  let repim f t ?(stride=1) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m
  let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v
  let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v
  let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v
  let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v
  (* output *)
  let print_list_mle f ls = string_of_list f ls |> print_endline
  let print_array_mle f a = string_of_array f a |> print_endline
  let print_list f ls = ls |> List.iter (fun v -> printf "%s " @@ f v); print_newline ()
  let print_array f a = a |> Array.iter (fun v -> printf "%s " @@ f v); print_newline ()
  (* debug *)
  let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)
  let dump_i64_list ls = print_list ist ls
  let dump_i64_array a = print_array ist a
end open Lib open Array

module CumulSumArray = struct
  let make a =
    let ln = Array.length a
    in let a1 = Array.make (ln+$1) 0L in for i=1 to ln do a1.(i) <- a1.(i-$1) + a.(i-$1) done; a1
  let sum l r a = (* 0-origin,closed *)
    if l>r then 0L else (a.(r+$1) - a.(l))
  let sum_1orig l r a = sum (l-$1) (r-$1) a
end
let () =
  let n = get_i64 0 in
  let a = input_i64_array n in
  let b = init (i32 n) (fun i -> a.(i)) in
  sort compare b;
  (* let c = CumulSumArray.make a in *)
  let s = fold_left (+) 0L a in
  let r = ref [] in
  repi 0 (i32 n-$1) (fun i ->
    (* let rest = CumulSumArray.sum i 0 in *)
    let rest = s - a.(i) in
    let j = lower_bound b (rest/2L) in
    (* printf "%Ld, %Ld\n" rest j; *)
    if 0L<=j && j<n && b.(i32 j)*2L = rest then (
      r := (i+$1)::!r
    )
  );
  printf "%Ld\n" @@ llen !r;
  print_list string_of_int !r