Vanya plays a game of balloons on the field of size n × n, where each cell contains a balloon with one of the values 0, 1, 2 or 3. The goal is to destroy a cross, such that the product of all values of balloons in the cross is maximum possible. There are two types of crosses: normal and rotated. For example:**o****o**ooooo**o****o**oro***o*o*o***o***o*o*o***oFormally, the cross is given by three integers r, c and d, such that d ≤ r, c ≤ n - d + 1. The normal cross consists of balloons located in cells (x, y) (where x stay for the number of the row and y for the number of the column), such that |x - r|·|y - c| = 0 and |x - r| + |y - c| < d. Rotated cross consists of balloons located in cells (x, y), such that |x - r| = |y - c| and |x - r| < d.Vanya wants to know the maximum possible product of the values of balls forming one cross. As this value can be large, output it modulo 109 + 7.

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of rows and columns in the table with balloons. The each of the following n lines contains n characters '0', '1', '2' or '3' — the description of the values in balloons.

Print the maximum possible product modulo 109 + 7. Note, that you are not asked to maximize the remainder modulo 109 + 7, but to find the maximum value and print it this modulo.

NoteIn the first sample, the maximum product is achieved for a rotated cross with a center in the cell (3, 3) and radius 1: 2·2·3·3·3 = 108.

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

let _ =
  let mm = 1000000007 in
  let mmm = Int64.of_int mm in
  let mmod n =
    let r = Int64.rem n mmm in
      if r < 0L
      then r +| mmm
      else r
  in
  let min (x : int) y = if x < y then x else y in
  let max (x : int) y = if x > y then x else y in
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n "" in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%s " (fun s -> s)
    done;
  in
  let make dx dy =
    let b = Array.make_matrix n n 0 in
    let rec fill y x =
      if x >= 0 && y >= 0 && x < n && y < n then (
	let x' = x - dx
	and y' = y - dy in
	  if a.(y).[x] = '0' then (
	    b.(y).(x) <- 0;
	  ) else (
	    let d =
	      if x' >= 0 && y' >= 0 && x' < n && y' < n
	      then b.(y').(x') + 1
	      else 1
	    in
	      if b.(y).(x) < d
	      then b.(y).(x) <- d;
	  );
	  fill (y + dy) (x + dx)
      )
    in
      for i = 0 to n - 1 do
	fill 0 i;
	fill i 0;
	fill (n - 1) i;
	fill i (n - 1);
      done;
      b
  in
  let al = make 1 0 in
  let ar = make (-1) 0 in
  let au = make 0 1 in
  let ad = make 0 (-1) in
  let aul = make 1 1 in
  let aur = make (-1) 1 in
  let adl = make 1 (-1) in
  let adr = make (-1) (-1) in
  let f = Array.make_matrix n n 0.0 in
  let _ =
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	let x =
	  match a.(i).[j] with
	    | '0' -> -1.0;
	    | '1' -> 0.0;
	    | '2' -> log 2.0;
	    | '3' -> log 3.0;
	    | _ -> assert false
	in
	  f.(i).(j) <- x
      done;
    done;
  in
  let get y x = Char.code a.(y).[x] - Char.code '0' in
  let fh = Array.make_matrix (n + 2) (n + 2) 0.0 in
  let fv = Array.make_matrix (n + 2) (n + 2) 0.0 in
  let fd1 = Array.make_matrix (n + 2) (n + 2) 0.0 in
  let fd2 = Array.make_matrix (n + 2) (n + 2) 0.0 in
  let _ =
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	fh.(i + 1).(j + 1) <- fh.(i + 1).(j) +. f.(i).(j)
      done
    done;
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	fv.(i + 1).(j + 1) <- fv.(i).(j + 1) +. f.(i).(j)
      done
    done;
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	fd1.(i + 1).(j + 1) <- fd1.(i).(j) +. f.(i).(j)
      done
    done;
    for i = 0 to n - 1 do
      for j = n - 1 downto 0 do
	fd2.(i + 1).(j + 1) <- fd2.(i).(j + 2) +. f.(i).(j)
      done
    done;
  in
  let b = ref (-1000000.0) in
  let br = ref 0 in
  let bc = ref 0 in
  let bd = ref 0 in
  let bt = ref false in
  let _ =
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	if a.(i).[j] <> '0' then (
	  let d =
	    min (min aul.(i).(j) aur.(i).(j)) (min adl.(i).(j) adr.(i).(j))
	  in
	  let s =
	    fd1.(i + d).(j + d) -. fd1.(i - d + 1).(j - d + 1) +.
	      fd2.(i + d).(j - d + 2) -. fd2.(i - d + 1).(j + d + 1) -. f.(i).(j)
	  in
(*Printf.printf "asd %d %d  %d %d %d %d  %f\n" i j aul.(i).(j) aur.(i).(j)
adl.(i).(j) adr.(i).(j) s;*)
	    if !b < s then (
	      b := s;
	      br := i;
	      bc := j;
	      bd := d;
	      bt := true;
	    )
	)
      done
    done;
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	if a.(i).[j] <> '0' then (
	  let d =
	    min (min al.(i).(j) ar.(i).(j)) (min au.(i).(j) ad.(i).(j))
	  in
	  let s =
	    fh.(i + 1).(j + d) -. fh.(i + 1).(j - d + 1) +.
	      fv.(i + d).(j + 1) -. fv.(i - d + 1).(j + 1) -. f.(i).(j)
	  in
(*Printf.printf "asd %d %d  %d %d %d %d  %f\n" i j al.(i).(j) ar.(i).(j)
au.(i).(j) ad.(i).(j) s;
Printf.printf "qwe %f %f %f %f  %f\n"
fh.(i + 1).(j + d) fh.(i + 1).(j - d + 1)
  fv.(i + d).(j + 1) fv.(i - d + 1).(j + 1) f.(i).(j);*)
	    if !b < s then (
	      b := s;
	      br := i;
	      bc := j;
	      bd := d;
	      bt := false;
	    )
	)
      done
    done;
  in
  let res = ref 1L in
(*Printf.printf "zxc %f  %d %d %d %b\n" !b !br !bc !bd !bt;*)
    if not !bt then (
      for i = !br - !bd + 1 to !br + !bd - 1 do
	res := mmod (!res *| Int64.of_int (get i !bc));
      done;
      for j = !bc - !bd + 1 to !bc + !bd - 1 do
	if j <> !bc
	then res := mmod (!res *| Int64.of_int (get !br j));
      done;
    ) else (
      for i = - !bd + 1 to !bd - 1 do
	res := mmod (!res *| Int64.of_int (get (!br + i) (!bc + i)));
      done;
      for i = - !bd + 1 to !bd - 1 do
	if i <> 0
	then res := mmod (!res *| Int64.of_int (get (!br + i) (!bc - i)));
      done;
    );
    if !bd = 0
    then res := 0L;
    Printf.printf "%Ld\n" !res

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

let _ =
  let mm = 1000000007 in
  let mmm = Int64.of_int mm in
  let mmod n =
    let r = Int64.rem n mmm in
      if r < 0L
      then r +| mmm
      else r
  in
  let min (x : int) y = if x < y then x else y in
  let max (x : int) y = if x > y then x else y in
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n "" in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%s " (fun s -> s)
    done;
  in
  let make dx dy =
    let b = Array.make_matrix n n 0 in
    let rec fill y x =
      if x >= 0 && y >= 0 && x < n && y < n then (
	let x' = x - dx
	and y' = y - dy in
	  if a.(y).[x] = '0' then (
	    b.(y).(x) <- 0;
	  ) else (
	    let d =
	      if x' >= 0 && y' >= 0 && x' < n && y' < n
	      then b.(y').(x') + 1
	      else 1
	    in
	      if b.(y).(x) < d
	      then b.(y).(x) <- d;
	  );
	  fill (y + dy) (x + dx)
      )
    in
      for i = 0 to n - 1 do
	fill 0 i;
	fill i 0;
	fill (n - 1) i;
	fill i (n - 1);
      done;
      b
  in
  let al = make 1 0 in
  let ar = make (-1) 0 in
  let au = make 0 1 in
  let ad = make 0 (-1) in
  let aul = make 1 1 in
  let aur = make (-1) 1 in
  let adl = make 1 (-1) in
  let adr = make (-1) (-1) in
  let f = Array.make_matrix n n 0.0 in
  let _ =
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	let x =
	  match a.(i).[j] with
	    | '0' -> -1.0;
	    | '1' -> 0.0;
	    | '2' -> log 2.0;
	    | '3' -> log 3.0;
	    | _ -> assert false
	in
	  f.(i).(j) <- x
      done;
    done;
  in
  let get y x = Char.code a.(y).[x] - Char.code '0' in
  let fh = Array.make_matrix (n + 2) (n + 2) 0.0 in
  let fv = Array.make_matrix (n + 2) (n + 2) 0.0 in
  let fd1 = Array.make_matrix (n + 2) (n + 2) 0.0 in
  let fd2 = Array.make_matrix (n + 2) (n + 2) 0.0 in
  let _ =
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	fh.(i + 1).(j + 1) <- fh.(i + 1).(j) +. f.(i).(j)
      done
    done;
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	fv.(i + 1).(j + 1) <- fv.(i).(j + 1) +. f.(i).(j)
      done
    done;
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	fd1.(i + 1).(j + 1) <- fd1.(i).(j) +. f.(i).(j)
      done
    done;
    for i = 0 to n - 1 do
      for j = n - 1 downto 0 do
	fd2.(i + 1).(j + 1) <- fd2.(i).(j + 2) +. f.(i).(j)
      done
    done;
  in
  let b = ref 0.0 in
  let br = ref 0 in
  let bc = ref 0 in
  let bd = ref 0 in
  let bt = ref false in
  let _ =
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	if a.(i).[j] <> '0' then (
	  let d =
	    min (min aul.(i).(j) aur.(i).(j)) (min adl.(i).(j) adr.(i).(j))
	  in
	  let s =
	    fd1.(i + d).(j + d) -. fd1.(i - d + 1).(j - d + 1) +.
	      fd2.(i + d).(j - d + 2) -. fd2.(i - d + 1).(j + d + 1) -. f.(i).(j)
	  in
(*Printf.printf "asd %d %d  %d %d %d %d  %f\n" i j aul.(i).(j) aur.(i).(j)
adl.(i).(j) adr.(i).(j) s;*)
	    if !b < s then (
	      b := s;
	      br := i;
	      bc := j;
	      bd := d;
	      bt := true;
	    )
	)
      done
    done;
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	if a.(i).[j] <> '0' then (
	  let d =
	    min (min al.(i).(j) ar.(i).(j)) (min au.(i).(j) ad.(i).(j))
	  in
	  let s =
	    fh.(i + 1).(j + d) -. fh.(i + 1).(j - d + 1) +.
	      fv.(i + d).(j + 1) -. fv.(i - d + 1).(j + 1) -. f.(i).(j)
	  in
(*Printf.printf "asd %d %d  %d %d %d %d  %f\n" i j al.(i).(j) ar.(i).(j)
au.(i).(j) ad.(i).(j) s;
Printf.printf "qwe %f %f %f %f  %f\n"
fh.(i + 1).(j + d) fh.(i + 1).(j - d + 1)
  fv.(i + d).(j + 1) fv.(i - d + 1).(j + 1) f.(i).(j);*)
	    if !b < s then (
	      b := s;
	      br := i;
	      bc := j;
	      bd := d;
	      bt := false;
	    )
	)
      done
    done;
  in
  let res = ref 1L in
(*Printf.printf "zxc %f  %d %d %d %b\n" !b !br !bc !bd !bt;*)
    if not !bt then (
      for i = !br - !bd + 1 to !br + !bd - 1 do
	res := mmod (!res *| Int64.of_int (get i !bc));
      done;
      for j = !bc - !bd + 1 to !bc + !bd - 1 do
	if j <> !bc
	then res := mmod (!res *| Int64.of_int (get !br j));
      done;
    ) else (
      for i = - !bd + 1 to !bd - 1 do
	res := mmod (!res *| Int64.of_int (get (!br + i) (!bc + i)));
      done;
      for i = - !bd + 1 to !bd - 1 do
	if i <> 0
	then res := mmod (!res *| Int64.of_int (get (!br + i) (!bc - i)));
      done;
    );
    Printf.printf "%Ld\n" !res

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

let _ =
  let mm = 1000000007 in
  let mmm = Int64.of_int mm in
  let mmod n =
    let r = Int64.rem n mmm in
      if r < 0L
      then r +| mmm
      else r
  in
  let min (x : int) y = if x < y then x else y in
  let max (x : int) y = if x > y then x else y in
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n "" in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%s " (fun s -> s)
    done;
  in
  let make dx dy =
    let b = Array.make_matrix n n 0 in
    let rec fill y x =
      if x >= 0 && y >= 0 && x < n && y < n then (
	let x' = x - dx
	and y' = y - dy in
	  if a.(y).[x] = '0' then (
	    b.(y).(x) <- 0;
	  ) else (
	    let d =
	      if x' >= 0 && y' >= 0 && x' < n && y' < n
	      then b.(y').(x') + 1
	      else 1
	    in
	      if b.(y).(x) < d
	      then b.(y).(x) <- d;
	  );
	  fill (y + dy) (x + dx)
      )
    in
      for i = 0 to n - 1 do
	fill 0 i;
	fill i 0;
	fill (n - 1) i;
	fill i (n - 1);
      done;
      b
  in
  let al = make 1 0 in
  let ar = make (-1) 0 in
  let au = make 0 1 in
  let ad = make 0 (-1) in
  let aul = make 1 1 in
  let aur = make (-1) 1 in
  let adl = make 1 (-1) in
  let adr = make (-1) (-1) in
  let f = Array.make_matrix n n 0.0 in
  let _ =
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	let x =
	  match a.(i).[j] with
	    | '0' -> -1.0;
	    | '1' -> 0.0;
	    | '2' -> log 2.0;
	    | '3' -> log 3.0;
	    | _ -> assert false
	in
	  f.(i).(j) <- x
      done;
    done;
  in
  let get y x = Char.code a.(y).[x] - Char.code '0' in
  let fh = Array.make_matrix (n + 2) (n + 2) 0.0 in
  let fv = Array.make_matrix (n + 2) (n + 2) 0.0 in
  let fd1 = Array.make_matrix (n + 2) (n + 2) 0.0 in
  let fd2 = Array.make_matrix (n + 2) (n + 2) 0.0 in
  let _ =
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	fh.(i + 1).(j + 1) <- fh.(i + 1).(j) +. f.(i).(j)
      done
    done;
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	fv.(i + 1).(j + 1) <- fv.(i).(j + 1) +. f.(i).(j)
      done
    done;
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	fd1.(i + 1).(j + 1) <- fd1.(i).(j) +. f.(i).(j)
      done
    done;
    for i = 0 to n - 1 do
      for j = n - 1 downto 0 do
	fd2.(i + 1).(j + 1) <- fd2.(i).(j + 2) +. f.(i).(j)
      done
    done;
  in
  let b = ref 0.0 in
  let br = ref 0 in
  let bc = ref 0 in
  let bd = ref 0 in
  let bt = ref false in
  let _ =
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	if a.(i).[j] <> '0' then (
	  let d =
	    min (min aul.(i).(j) aur.(i).(j)) (min adl.(i).(j) adr.(i).(j))
	  in
	  let s =
	    fd1.(i + d).(j + d) -. fd1.(i - d + 1).(j - d + 1) +.
	      fd2.(i + d).(j - d + 2) -. fd2.(i - d + 1).(j + d + 1) -. f.(i).(j)
	  in
(*Printf.printf "asd %d %d  %d %d %d %d  %f\n" i j aul.(i).(j) aur.(i).(j)
adl.(i).(j) adr.(i).(j) s;*)
	    if !b < s then (
	      b := s;
	      br := i;
	      bc := j;
	      bd := d;
	      bt := true;
	    )
	)
      done
    done;
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	if a.(i).[j] <> '0' then (
	  let d =
	    min (min al.(i).(j) ar.(i).(j)) (min au.(i).(j) ad.(i).(j))
	  in
	  let s =
	    fh.(i + 1).(j + d) -. fh.(i + 1).(j - d + 1) +.
	      fv.(i + d).(j + 1) -. fv.(i - d + 1).(j + 1) -. f.(i).(j)
	  in
(*Printf.printf "asd %d %d  %d %d %d %d  %f\n" i j al.(i).(j) ar.(i).(j)
au.(i).(j) ad.(i).(j) s;
Printf.printf "qwe %f %f %f %f  %f\n"
fh.(i + 1).(j + d) fh.(i + 1).(j - d + 1)
  fv.(i + d).(j + 1) fv.(i - d + 1).(j + 1) f.(i).(j);*)
	    if !b < s then (
	      b := s;
	      br := i;
	      bc := j;
	      bd := d;
	      bt := false;
	    )
	)
      done
    done;
  in
  let res = ref 1L in
(*Printf.printf "zxc %f  %d %d %d %b\n" !b !br !bc !bd !bt;*)
    if not !bt then (
      for i = !br - !bd + 1 to !br + !bd - 1 do
	res := mmod (!res *| Int64.of_int (get i !bc));
      done;
      for j = !bc - !bd + 1 to !bc + !bd - 1 do
	if j <> !bc
	then res := mmod (!res *| Int64.of_int (get !br j));
      done;
    ) else (
      for i = - !bd + 1 to !bd - 1 do
	res := mmod (!res *| Int64.of_int (get (!br + i) (!bc + i)));
      done;
      for i = - !bd + 1 to !bd - 1 do
	if i <> 0
	then res := mmod (!res *| Int64.of_int (get (!br + i) (!bc - i)));
      done;
    );
    if !bd = 0
    then res := 0L;
    Printf.printf "%Ld\n" !res


Just to remind, girls in Arpa's land are really nice.Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if there is a sequence of Hoses a1, a2, ..., ak such that ai and ai + 1 are friends for each 1 ≤ i < k, and a1 = x and ak = y.  Arpa allowed to use the amphitheater of palace to Mehrdad for this party. Arpa's amphitheater can hold at most w weight on it. Mehrdad is so greedy that he wants to invite some Hoses such that sum of their weights is not greater than w and sum of their beauties is as large as possible. Along with that, from each friendship group he can either invite all Hoses, or no more than one. Otherwise, some Hoses will be hurt. Find for Mehrdad the maximum possible total beauty of Hoses he can invite so that no one gets hurt and the total weight doesn't exceed w.

The first line contains integers n, m and w (1  ≤  n  ≤  1000, , 1 ≤ w ≤ 1000) — the number of Hoses, the number of pair of friends and the maximum total weight of those who are invited. The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 1000) — the weights of the Hoses. The third line contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 106) — the beauties of the Hoses. The next m lines contain pairs of friends, the i-th of them contains two integers xi and yi (1 ≤ xi, yi ≤ n, xi ≠ yi), meaning that Hoses xi and yi are friends. Note that friendship is bidirectional. All pairs (xi, yi) are distinct.

Print the maximum possible total beauty of Hoses Mehrdad can invite so that no one gets hurt and the total weight doesn't exceed w.

NoteIn the first sample there are two friendship groups: Hoses {1, 2} and Hos {3}. The best way is to choose all of Hoses in the first group, sum of their weights is equal to 5 and sum of their beauty is 6.In the second sample there are two friendship groups: Hoses {1, 2, 3} and Hos {4}. Mehrdad can't invite all the Hoses from the first group because their total weight is 12 > 11, thus the best way is to choose the first Hos from the first group and the only one from the second group. The total weight will be 8, and the total beauty will be 7.

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 read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let m = read_int () in
  let max_w = read_int () in
  let w = Array.init n (fun _ -> read_int()) in
  let b = Array.init n (fun _ -> read_int()) in

  let graph = Array.make n [] in

  let add_edge (u,v) =
    graph.(u) <- v::graph.(u);
    graph.(v) <- u::graph.(v)
  in

  for i=1 to m do
    add_edge (read_int() -1, read_int() -1)
  done;

  let comp = Array.make n (-1) in

  let rec dfs v c = if comp.(v) < 0 then (
    comp.(v) <- c;
    List.iter (fun w -> dfs w c) graph.(v)
  ) in

  let rec dfs_loop v c = if v=n then c
    else if comp.(v) >= 0 then
      dfs_loop (v+1) c
    else (
      dfs v c;
      dfs_loop (v+1) (c+1)
    )
  in

  let ncomps = dfs_loop 0 0 in

  let comp_weight = Array.make ncomps 0 in
  let comp_beauty = Array.make ncomps 0 in
  let comp_vertices = Array.make ncomps [] in

  for i=0 to n-1 do
    comp_weight.(comp.(i)) <- comp_weight.(comp.(i)) + w.(i);
    comp_beauty.(comp.(i)) <- comp_beauty.(comp.(i)) + b.(i);
    comp_vertices.(comp.(i)) <- i::comp_vertices.(comp.(i))
  done;

  (* pl is a list of pairs (weight, beauty) *)

  let rec prune lastb li ac =
    match li with
      | [] -> List.rev ac
      | (w,b)::tail ->
	if b > lastb then prune b tail ((w,b)::ac)
	else prune lastb tail ac
  in

  let merge l1 l2 =
    let h = Hashtbl.create 10 in
    List.iter (fun (w1,b1) ->
      List.iter (fun (w2,b2) ->
	if w1+w2 <= max_w then
	  let c = try Hashtbl.find h (w1+w2) with Not_found -> 0 in
	  Hashtbl.replace h (w1+w2) (max (b1+b2) c)
      ) l2
    ) l1;

    let l3 = Hashtbl.fold (fun w b ac -> (w,b)::ac) h [] in
    let l3 = List.sort compare l3 in

    prune (-1) l3 []
  in

  let pl_array = Array.init ncomps (fun c ->
    if comp_weight.(c) <= max_w
    then [(0,0);(comp_weight.(c), comp_beauty.(c))]
    else [(0,0)]
  ) in

  for u=0 to n-1 do
    if w.(u) <= max_w then
      pl_array.(comp.(u)) <- (w.(u), b.(u))::pl_array.(comp.(u))
  done;

  for c=0 to ncomps-1 do
    pl_array.(c) <- prune (-1) (List.sort compare pl_array.(c)) []
  done;

  let final_pl = fold 1 (ncomps-1)
    (fun c ac -> merge ac pl_array.(c)) pl_array.(0)
  in

  let max_beauty = List.fold_left (fun ac (w,b) -> max b ac) 0 final_pl in

  printf "%d\n" max_beauty

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 read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let m = read_int () in
  let max_w = read_int () in
  let w = Array.init n (fun _ -> read_int()) in
  let b = Array.init n (fun _ -> read_int()) in

  let graph = Array.make n [] in

  let add_edge (u,v) =
    graph.(u) <- v::graph.(u);
    graph.(v) <- u::graph.(v)
  in

  for i=1 to m do
    add_edge (read_int() -1, read_int() -1)
  done;

  let comp = Array.make n (-1) in

  let rec dfs v c = if comp.(v) < 0 then (
    comp.(v) <- c;
    List.iter (fun w -> dfs w c) graph.(v)
  ) in

  let rec dfs_loop v c = if v=n then c
    else if comp.(v) >= 0 then
      dfs_loop (v+1) c
    else (
      dfs v c;
      dfs_loop (v+1) (c+1)
    )
  in

  let ncomps = dfs_loop 0 0 in

  let comp_weight = Array.make ncomps 0 in
  let comp_beauty = Array.make ncomps 0 in
  let comp_vertices = Array.make ncomps [] in

  for i=0 to n-1 do
    comp_weight.(comp.(i)) <- comp_weight.(comp.(i)) + w.(i);
    comp_beauty.(comp.(i)) <- comp_beauty.(comp.(i)) + b.(i);
    comp_vertices.(comp.(i)) <- i::comp_vertices.(comp.(i))
  done;

  (* pl is a list of pairs (weight, beauty) *)

  let rec prune lastb li ac =
    match li with
      | [] -> List.rev ac
      | (w,b)::tail ->
	if b > lastb then prune b tail ((w,b)::ac)
	else prune lastb tail ac
  in

  let merge l1 l2 =
    let h = Hashtbl.create 10 in
    List.iter (fun (w1,b1) ->
      List.iter (fun (w2,b2) ->
	if w1+w2 <= max_w then
	  let c = try Hashtbl.find h (w1+w2) with Not_found -> 0 in
	  Hashtbl.replace h (w1+w2) (max (b1+b2) c)
      ) l2
    ) l1;

    let l3 = Hashtbl.fold (fun w b ac -> (w,b)::ac) h [] in
    let l3 = List.sort compare l3 in

    prune (-1) l3 []
  in

  let pl_array = Array.init ncomps (fun c ->
    if comp_weight.(c) <= max_w
    then [(0,0);(comp_weight.(c), comp_beauty.(c))]
    else [(0,0)]
  ) in

  for u=0 to n-1 do
    pl_array.(comp.(u)) <- (w.(u), b.(u))::pl_array.(comp.(u))
  done;

  for c=0 to ncomps-1 do
    pl_array.(c) <- prune (-1) (List.sort compare pl_array.(c)) []
  done;

  let final_pl = fold 1 (ncomps-1)
    (fun c ac -> merge ac pl_array.(c)) pl_array.(0)
  in

  let max_beauty = List.fold_left (fun ac (w,b) -> max b ac) 0 final_pl in

  printf "%d\n" max_beauty

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 read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let m = read_int () in
  let max_w = read_int () in
  let w = Array.init n (fun _ -> read_int()) in
  let b = Array.init n (fun _ -> read_int()) in

  let graph = Array.make n [] in

  let add_edge (u,v) =
    graph.(u) <- v::graph.(u);
    graph.(v) <- u::graph.(v)
  in

  for i=1 to m do
    add_edge (read_int() -1, read_int() -1)
  done;

  let comp = Array.make n (-1) in

  let rec dfs v c = if comp.(v) < 0 then (
    comp.(v) <- c;
    List.iter (fun w -> dfs w c) graph.(v)
  ) in

  let rec dfs_loop v c = if v=n then c
    else if comp.(v) >= 0 then
      dfs_loop (v+1) c
    else (
      dfs v c;
      dfs_loop (v+1) (c+1)
    )
  in

  let ncomps = dfs_loop 0 0 in

  let comp_weight = Array.make ncomps 0 in
  let comp_beauty = Array.make ncomps 0 in
  let comp_vertices = Array.make ncomps [] in

  for i=0 to n-1 do
    comp_weight.(comp.(i)) <- comp_weight.(comp.(i)) + w.(i);
    comp_beauty.(comp.(i)) <- comp_beauty.(comp.(i)) + b.(i);
    comp_vertices.(comp.(i)) <- i::comp_vertices.(comp.(i))
  done;

  (* pl is a list of pairs (weight, beauty) *)

  let rec prune lastb li ac =
    match li with
      | [] -> List.rev ac
      | (w,b)::tail ->
	if b > lastb then prune b tail ((w,b)::ac)
	else prune lastb tail ac
  in

  let merge l1 l2 =
    let h = Hashtbl.create 10 in
    List.iter (fun (w1,b1) ->
      List.iter (fun (w2,b2) ->
	if w1+w2 <= max_w then
	  let c = try Hashtbl.find h (w1+w2) with Not_found -> 0 in
	  Hashtbl.replace h (w1+w2) (max (b1+b2) c)
      ) l2
    ) l1;

    let l3 = Hashtbl.fold (fun w b ac -> (w,b)::ac) h [] in
    let l3 = List.sort compare l3 in

    prune (-1) l3 []
  in

  let pl_array = Array.make ncomps [] in

  for u=0 to n-1 do
    pl_array.(comp.(u)) <- (w.(u), b.(u))::pl_array.(comp.(u))
  done;

  for c=0 to ncomps-1 do
    let aug = (0,0)::((comp_weight.(c), comp_beauty.(c))::pl_array.(c)) in
    pl_array.(c) <- prune (-1) (List.sort compare aug) []
  done;

  let final_pl = fold 1 (ncomps-1)
    (fun c ac -> merge ac pl_array.(c)) pl_array.(0)
  in

  let max_beauty = List.fold_left (fun ac (w,b) -> max b ac) 0 final_pl in

  printf "%d\n" max_beauty


Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended up entangled and now have to be untangled again.The device is powered by two wires "plus" and "minus". The wires run along the floor from the wall (on the left) to the device (on the right). Both the wall and the device have two contacts in them on the same level, into which the wires are plugged in some order. The wires are considered entangled if there are one or more places where one wire runs above the other one. For example, the picture below has four such places (top view):  Mike knows the sequence in which the wires run above each other. Mike also noticed that on the left side, the "plus" wire is always plugged into the top contact (as seen on the picture). He would like to untangle the wires without unplugging them and without moving the device. Determine if it is possible to do that. A wire can be freely moved and stretched on the floor, but cannot be cut.To understand the problem better please read the notes to the test samples.

The single line of the input contains a sequence of characters "+" and "-" of length n (1 ≤ n ≤ 100000). The i-th (1 ≤ i ≤ n) position of the sequence contains the character "+", if on the i-th step from the wall the "plus" wire runs above the "minus" wire, and the character "-" otherwise.

Print either "Yes" (without the quotes) if the wires can be untangled or "No" (without the quotes) if the wires cannot be untangled.

NoteThe first testcase corresponds to the picture in the statement. To untangle the wires, one can first move the "plus" wire lower, thus eliminating the two crosses in the middle, and then draw it under the "minus" wire, eliminating also the remaining two crosses.In the second testcase the "plus" wire makes one full revolution around the "minus" wire. Thus the wires cannot be untangled:   In the third testcase the "plus" wire simply runs above the "minus" wire twice in sequence. The wires can be untangled by lifting "plus" and moving it higher:   In the fourth testcase the "minus" wire runs above the "plus" wire once. The wires cannot be untangled without moving the device itself:

let s = read_line () in
let l = ref [] in
let rec alt c = match !l with
    []   -> l := [c]
  | h::t -> l := (if h = c then t else c :: h :: t)
in
String.iter alt s ;
if !l = [] then
    Printf.printf "Yes\n"
else
    Printf.printf "No\n" ;;


You are given an array $$$a$$$ consisting of $$$n$$$ ($$$n \ge 3$$$) positive integers. It is known that in this array, all the numbers except one are the same (for example, in the array $$$[4, 11, 4, 4]$$$ all numbers except one are equal to $$$4$$$).Print the index of the element that does not equal others. The numbers in the array are numbered from one.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$). Then $$$t$$$ test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$3 \le n \le 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 100$$$). It is guaranteed that all the numbers except one in the $$$a$$$ array are the same.

For each test case, output a single integer — the index of the element that is not equal to others.

open Str;;

let rec check (a : int list)(n : int) =
  if List.length (List.find_all (fun x -> x == (List.nth a n)) a) == 1 then
    n
  else
    check a (n+1)
;;

let rec solve (t : int) =
  if t = 0 then
    ()
  else
    let n = read_int () in
    let arr = (Str.split (Str.regexp " ") (read_line ())) in
    let a = (List.map (fun x -> int_of_string x) arr) in
    let ind = check a 0 in
    print_endline (string_of_int (ind + 1));
    solve (t-1)
;;

let t = read_int() in
solve t;;

(* https://codeforces.com/contest/1512/problem/0 *)

let intruder arr =
    let rec commoner () =
        let h = Array.init 3 (fun i -> arr.(i)) in
        let count =
            Array.map
                (fun e -> Array.fold_left (fun acc e' -> if e = e' then acc+1 else acc) 0 h)
                h in
        if count.(0) > 1
        then h.(0)
        else h.(1) in
    let c = commoner () in
    let rec helper i =
        if arr.(i) <> c
        then (i+1)
        else helper (i+1) in
    helper 0

let solve_n nb_cases =
    let rec helper i =
        if i > 0
        then (
            let _ = read_int () and
            arr =
                read_line ()
                |> Str.split (Str.regexp " ")
                |> List.map int_of_string
                |> Array.of_list in
            intruder arr
            |> Printf.printf "%d\n";
            helper (i-1)
        ) in
    helper nb_cases

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


We saw the little game Marmot made for Mole's lunch. Now it's Marmot's dinner time and, as we all know, Marmot eats flowers. At every dinner he eats some red and white flowers. Therefore a dinner can be represented as a sequence of several flowers, some of them white and some of them red.But, for a dinner to be tasty, there is a rule: Marmot wants to eat white flowers only in groups of size k.Now Marmot wonders in how many ways he can eat between a and b flowers. As the number of ways could be very large, print it modulo 1000000007 (109 + 7).

Input contains several test cases. The first line contains two integers t and k (1 ≤ t, k ≤ 105), where t represents the number of test cases. The next t lines contain two integers ai and bi (1 ≤ ai ≤ bi ≤ 105), describing the i-th test.

Print t lines to the standard output. The i-th line should contain the number of ways in which Marmot can eat between ai and bi flowers at dinner modulo 1000000007 (109 + 7).

Note  For K = 2 and length 1 Marmot can eat (R).  For K = 2 and length 2 Marmot can eat (RR) and (WW).  For K = 2 and length 3 Marmot can eat (RRR), (RWW) and (WWR).  For K = 2 and length 4 Marmot can eat, for example, (WWWW) or (RWWR), but for example he can't eat (WWWR).

open Printf
open Scanf

let mm = 1000000007L

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

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

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

  let input = Array.init t (fun _ -> read_pair()) in

  let msize = maxf 0 (t-1) (fun i -> snd input.(i)) in

  let count = Array.make (msize+1) (-1L) in
  count.(0) <- 1L;

  let rec ccount b =
    if count.(b) >= 0L then count.(b) else
      let answer =
	if b < k then 1L else
	  ccount (b-k) ++ ccount (b-1)
      in
      count.(b) <- answer;
      answer
  in

  for b = 1 to msize do
    ignore (ccount b)
  done;

  let accum = Array.make (msize+1) 0L in
  accum.(0) <- count.(0);

  for i=1 to msize do
    accum.(i) <- accum.(i-1) ++ count.(i)
  done;

  for i=0 to t-1 do
    let (a,b) = input.(i) in
    printf "%Ld\n" (accum.(b) -- (accum.(a-1)))
  done

open Scanf;;
open String;;
open Printf;;
open Int64;;

(* This version implements
 * a(n) = a(n-1) + a(n-k)
 * where k is the number of continued W
 * - Reduce memory usage.
 *)

let (t,k) = bscanf Scanning.stdin "%d %d " (fun x y -> (x,y) )

let modn i = rem i (of_int 1000000007)

let ni i = of_int i
let sn i = to_string i

(*let nn = 100000 + 5*)
let nn_max = 100000 + 5

let nn = 100000 + 3

let r= Array.make nn_max (ni 0)

for i = 1 to k-1 do
  r.(i) <- (ni 1)
done

let () =
 r.(k) <- ni 2

for i = k+1 to nn do
  r.(i) <-  modn (add r.(i-1) r.(i-k))
done

for i = 2 to nn do
    r.(i) <- add r.(i) r.(i-1)
done

for i = 1 to t do
   let (s,e) = bscanf Scanning.stdin "%d %d " (fun x y -> (x,y) ) in
   let sum = ref (ni 0) in
   sum := sub r.(e) r.(s-1);
   printf "%s\n" (sn (modn !sum) )
done

open Int64;;

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

let modulo = of_int 1000000007;;

let dyn_array = Array.make 100005 (of_int (-1));;

let rec get_ways gap = function
  | index when index = Array.length dyn_array -> one
  | index when index > Array.length dyn_array -> zero
  | index when (compare dyn_array.(index)  (of_int (-1))) != 0 -> dyn_array.(index)
  | index ->
    let res = rem (add (get_ways gap (index+1)) (get_ways gap (index+gap))) modulo in
    dyn_array.(index) <- res;
    res;;

(*#trace get_ways;;*)

let nbTests = read_int () in
let gap = read_int () in
let _ = get_ways gap 0 in
for i = 1 to Array.length dyn_array - 1 do
  dyn_array.(i) <- rem (add dyn_array.(i)  dyn_array.(i - 1)) modulo
done;
for i = 1 to nbTests do
  let start = read_int () in
  let tree_end = Array.length dyn_array - start in
  let fin = read_int () in
  let tree_start = Array.length dyn_array - fin in
  let res = rem (add modulo  (sub dyn_array.(tree_end)  (if tree_start > 0 then dyn_array.(tree_start - 1) else zero))) modulo in
  Printf.printf "%s\n" (to_string res)
done;;

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

(* This version implements
 * a(n) = a(n-1) + a(n-k)
 * where k is the number of continued W
 * - Reduce memory usage.
 *)

let (t,k) = bscanf Scanning.stdin "%d %d " (fun x y -> (x,y) )

let modn i = i mod 1000000007

let ni i = i
let sn i = string_of_int i

(*let nn = 100000 + 5*)
let nn_max = 100000 + 5

let nn = 100000 + 3

let r= Array.make nn_max (ni (-1))

for i = 1 to k-1 do
  r.(i) <- (ni 1)
done

let () =
 r.(k) <- ni 2

let f n =
  if r.(n) = (ni (-1)) then
    begin
    let x = modn ( (modn r.(n-1)) + (modn r.(n-k)) ) in
    r.(n) <- x; x
    end
  else
    r.(n)

for i = k+1 to nn do
  r.(i) <- modn ((modn (f (i-1))) + (modn (f (i-k))))
done

(*
for i = 95515 to nn do
    printf "%s %s\n" (sn r.(i)) (sn w.(i))
done
*)

for i = 1 to t do
   let (s,e) = bscanf Scanning.stdin "%d %d " (fun x y -> (x,y) ) in
   let sum = ref (ni 0) in
   for j = s to e do
       sum := !sum + r.(j)
   done;
   printf "%s\n" (sn (modn !sum) )
done

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

let (t,k) = bscanf Scanning.stdin "%d %d " (fun x y -> (x,y) )

let modn i = mod_num i (num_of_int 1000000007)

let ni i = num_of_int i
let sn i = string_of_num i

(*let nn = 100000 + 5*)
let nn_max = 100000 + 5

let nn = 100000 + 1

let r= Array.make nn_max (ni 0)
let w= Array.make nn_max (ni 0)

let num_w = ref 1

let () =
 r.(1) <- ni 1

if k = 1 then
begin
  w.(1) <- ni 1;
end
else
begin
  w.(1) <- ni 0;
end

for i = 2 to nn do
   r.(i) <- r.(i-1) +/ w.(i-1);
   w.(i) <- w.(i-1);
   num_w := !num_w + 1;

   if !num_w = k then
   begin
   w.(i) <- w.(i) +/ (ni 1);
num_w := 0;
end
done

(*
for i = 0 to nn do
    printf "%s %s\n" (sn r.(i)) (sn w.(i))
done
*)

for i = 1 to t do
   let (s,e) = bscanf Scanning.stdin "%d %d " (fun x y -> (x,y) ) in
   let sum = ref (ni 0) in
   for j = s to e do
       sum := !sum +/ r.(j) +/ w.(j)
   done;
   printf "%s\n" (sn (modn !sum) )
done

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

(* This version implements
 * a(n) = a(n-1) + a(n-k)
 * where k is the number of continued W
 *)

let (t,k) = bscanf Scanning.stdin "%d %d " (fun x y -> (x,y) )

let modn i = mod_num i (num_of_int 1000000007)

let ni i = num_of_int i
let sn i = string_of_num i

(*let nn = 100000 + 5*)
let nn_max = 100000 + 5

let nn = 100000 + 3

let r= Array.make nn_max (ni (-1))

for i = 1 to k-1 do
  r.(i) <- (ni 1)
done

let () =
 r.(k) <- ni 2

let f n =
  if r.(n) = (ni (-1)) then
    begin
    let x = r.(n-1) +/ r.(n-k) in
    r.(n) <- x; x
    end
  else
    r.(n)

(*
for i = 95515 to nn do
    printf "%s %s\n" (sn r.(i)) (sn w.(i))
done
*)

for i = 1 to t do
   let (s,e) = bscanf Scanning.stdin "%d %d " (fun x y -> (x,y) ) in
   let sum = ref (ni 0) in
   for j = s to e do
       sum := !sum +/ (f j)
   done;
   printf "%s\n" (sn (modn !sum) )
done

open Scanf;;
open String;;
open Printf;;
open Int64;;

(* This version implements
 * a(n) = a(n-1) + a(n-k)
 * where k is the number of continued W
 * - Reduce memory usage.
 *)

let (t,k) = bscanf Scanning.stdin "%d %d " (fun x y -> (x,y) )

let modn i = rem i (of_int 1000000007)

let ni i = of_int i
let sn i = to_string i

(*let nn = 100000 + 5*)
let nn_max = 100000 + 5

let nn = 100000 + 3

let r= Array.make nn_max (ni (-1))

for i = 1 to k-1 do
  r.(i) <- (ni 1)
done

let () =
 r.(k) <- ni 2

let f n =
  if r.(n) = (ni (-1)) then
    begin
    let x = ( add (r.(n-1))  (r.(n-k)) ) in
    r.(n) <- x; x
    end
  else
    r.(n)

for i = k+1 to nn do
  r.(i) <-  (add ((f (i-1)))  ((f (i-k))) )
done

(*
for i = 95515 to nn do
    printf "%s %s\n" (sn r.(i)) (sn w.(i))
done
*)

for i = 1 to t do
   let (s,e) = bscanf Scanning.stdin "%d %d " (fun x y -> (x,y) ) in
   let sum = ref (ni 0) in
   for j = s to e do
       sum := add !sum r.(j)
   done;
   printf "%s\n" (sn (modn !sum) )
done

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

(* This version implements
 * a(n) = a(n-1) + a(n-k)
 * where k is the number of continued W
 * - Reduce memory usage.
 *)

let (t,k) = bscanf Scanning.stdin "%d %d " (fun x y -> (x,y) )

let modn i = i mod 1000000007

let ni i = i
let sn i = string_of_int i

(*let nn = 100000 + 5*)
let nn_max = 100000 + 5

let nn = 100000 + 3

let r= Array.make nn_max (ni (-1))

for i = 1 to k-1 do
  r.(i) <- (ni 1)
done

let () =
 r.(k) <- ni 2

let f n =
  if r.(n) = (ni (-1)) then
    begin
    let x = modn ( r.(n-1) + r.(n-k) ) in
    r.(n) <- x; x
    end
  else
    r.(n)

for i = k+1 to nn do
  r.(i) <- (f (i-1)) + (f (i-k))
done

(*
for i = 95515 to nn do
    printf "%s %s\n" (sn r.(i)) (sn w.(i))
done
*)

for i = 1 to t do
   let (s,e) = bscanf Scanning.stdin "%d %d " (fun x y -> (x,y) ) in
   let sum = ref (ni 0) in
   for j = s to e do
       sum := !sum + r.(j)
   done;
   printf "%s\n" (sn (modn !sum) )
done

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

let (--) debut fin =
  let rec range aux start en =
    if start > en then aux
    else range (en::aux) start (en-1)
  in range [] debut fin;;

let print_list f lst =
  let rec print_elements = function
    | [] -> ()
    | h::t -> f h; print_string ";"; print_elements t
  in
  print_string "[";
  print_elements lst;
  print_string "]\n";
  lst;;

let modulo = 1000000007;;

let dyn_array = Array.make 100000 (-1);;

let rec get_ways gap = function
  | index when index = Array.length dyn_array -> 1
  | index when index > Array.length dyn_array -> 0
  | index when dyn_array.(index) != -1 -> dyn_array.(index)
  | index ->
    let res = (get_ways gap (index+1) + get_ways gap (index+gap)) mod modulo in
    dyn_array.(index) <- res;
    res;;

(*#trace get_ways;;*)

type 'a node_data = {
  data:'a;
  start: int;
  fin: int
};;

type 'a node =
  | Leaf of 'a node_data
  | Cell of 'a node_data * 'a node * 'a node;;

let get_data = function
  | Leaf data
  | Cell (data,_,_)
    -> data;;

let computing_function = (+);;
let default_val = 0;;

let rec get_range tree debut fin = match tree with
  | Leaf data ->
    if data.start >= debut && data.fin <= fin then
      data.data
    else
      default_val
  | Cell (d, left, right) ->
    if fin < d.start || debut > d.fin then
      default_val
    else if d.fin > fin || d.start < debut then
      computing_function (get_range left debut fin) (get_range right debut fin)
    else
      d.data;;

let rec buildTree debut fin =
  if debut = fin then
    Leaf {
        data = dyn_array.(debut);
        start = debut;
        fin = fin
      }
  else
    let mid = (debut + fin)/2 in
    let right = buildTree (mid + 1) fin in
    let left = buildTree debut mid in
    let node_d = {
      data = (computing_function (get_data left).data (get_data right).data);
      start = debut;
      fin = fin
    } in
    Cell (node_d, left, right);;

let nbTests = read_int () in
let gap = read_int () in
let _ = get_ways gap 0 in
let tree = buildTree 0 (Array.length dyn_array - 1) in
for i = 1 to nbTests do
  let start = read_int () in
  let tree_end = Array.length dyn_array - start in
  let fin = read_int () in
  let tree_start = Array.length dyn_array - fin in
  let res = get_range tree tree_start tree_end in
  Printf.printf "%d\n" res
done;;

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

let (--) debut fin =
  let rec range aux start en =
    if start > en then aux
    else range (en::aux) start (en-1)
  in range [] debut fin;;

let print_list f lst =
  let rec print_elements = function
    | [] -> ()
    | h::t -> f h; print_string ";"; print_elements t
  in
  print_string "[";
  print_elements lst;
  print_string "]\n";
  lst;;

let modulo = 1000000007;;

let dyn_array = Array.make 100005 (-1);;

let rec get_ways gap = function
  | index when index = Array.length dyn_array -> 1
  | index when index > Array.length dyn_array -> 0
  | index when dyn_array.(index) != -1 -> dyn_array.(index)
  | index ->
    let res = (get_ways gap (index+1) + get_ways gap (index+gap)) mod modulo in
    dyn_array.(index) <- res;
    res;;

(*#trace get_ways;;*)

let nbTests = read_int () in
let gap = read_int () in
let _ = get_ways gap 0 in
for i = 1 to Array.length dyn_array - 1 do
  dyn_array.(i) <- (dyn_array.(i) + dyn_array.(i - 1)) mod modulo
done;
for i = 1 to nbTests do
  let start = read_int () in
  let tree_end = Array.length dyn_array - start in
  let fin = read_int () in
  let tree_start = Array.length dyn_array - fin in
  let res = (modulo + dyn_array.(tree_end) - if tree_start > 0 then dyn_array.(tree_start - 1) else 0) mod modulo in
  Printf.printf "%l\n" res
done;;

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

let (--) debut fin =
  let rec range aux start en =
    if start > en then aux
    else range (en::aux) start (en-1)
  in range [] debut fin;;

let print_list f lst =
  let rec print_elements = function
    | [] -> ()
    | h::t -> f h; print_string ";"; print_elements t
  in
  print_string "[";
  print_elements lst;
  print_string "]\n";
  lst;;

let modulo = 1000000007;;

let dyn_array = Array.make 100000 (-1);;

let rec get_ways gap = function
  | index when index = Array.length dyn_array -> 1
  | index when index > Array.length dyn_array -> 0
  | index when dyn_array.(index) != -1 -> dyn_array.(index)
  | index ->
    let res = (get_ways gap (index+1) + get_ways gap (index+gap)) mod modulo in
    dyn_array.(index) <- res;
    res;;

(*#trace get_ways;;*)

type 'a node_data = {
  data:'a;
  start: int;
  fin: int
};;

type 'a node =
  | Leaf of 'a node_data
  | Cell of 'a node_data * 'a node * 'a node;;

let get_data = function
  | Leaf data
  | Cell (data,_,_)
    -> data;;

let computing_function a b=
  (a + b) mod modulo;;
let default_val = 0;;

let rec get_range tree debut fin = match tree with
  | Leaf data ->
    if data.start >= debut && data.fin <= fin then
      data.data
    else
      default_val
  | Cell (d, left, right) ->
    if fin < d.start || debut > d.fin then
      default_val
    else if d.fin > fin || d.start < debut then
      computing_function (get_range left debut fin) (get_range right debut fin)
    else
      d.data;;

(*#trace get_range;;*)

let rec buildTree debut fin =
  if debut = fin then
    Leaf {
        data = dyn_array.(debut);
        start = debut;
        fin = fin
      }
  else
    let mid = (debut + fin)/2 in
    let right = buildTree (mid + 1) fin in
    let left = buildTree debut mid in
    let node_d = {
      data = (computing_function (get_data left).data (get_data right).data);
      start = debut;
      fin = fin
    } in
    Cell (node_d, left, right);;

let nbTests = read_int () in
let gap = read_int () in
let _ = get_ways gap 0 in
let tree = buildTree 0 (Array.length dyn_array - 1) in
for i = 1 to nbTests do
  let start = read_int () in
  let tree_end = Array.length dyn_array - start in
  let fin = read_int () in
  let tree_start = Array.length dyn_array - fin in
  let res = get_range tree tree_start tree_end in
  Printf.printf "%d\n" res
done;;


This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a "Discuss tasks" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle.After a long time thinking, Tolik's uncle hasn't any ideas on how to solve it. But, he doesn't want to tell Tolik about his inability to solve it, so he hasn't found anything better than asking you how to solve this task.In this task you are given a cell field $$$n \cdot m$$$, consisting of $$$n$$$ rows and $$$m$$$ columns, where point's coordinates $$$(x, y)$$$ mean it is situated in the $$$x$$$-th row and $$$y$$$-th column, considering numeration from one ($$$1 \leq x \leq n, 1 \leq y \leq m$$$). Initially, you stand in the cell $$$(1, 1)$$$. Every move you can jump from cell $$$(x, y)$$$, which you stand in, by any non-zero vector $$$(dx, dy)$$$, thus you will stand in the $$$(x+dx, y+dy)$$$ cell. Obviously, you can't leave the field, but also there is one more important condition — you're not allowed to use one vector twice. Your task is to visit each cell of the field exactly once (the initial cell is considered as already visited).Tolik's uncle is a very respectful person. Help him to solve this task!

The first and only line contains two positive integers $$$n, m$$$ ($$$1 \leq n \cdot m \leq 10^{6}$$$) — the number of rows and columns of the field respectively.

Print "-1" (without quotes) if it is impossible to visit every cell exactly once. Else print $$$n \cdot m$$$ pairs of integers, $$$i$$$-th from them should contain two integers $$$x_i, y_i$$$ ($$$1 \leq x_i \leq n, 1 \leq y_i \leq m$$$) — cells of the field in order of visiting, so that all of them are distinct and vectors of jumps between them are distinct too. Notice that the first cell should have $$$(1, 1)$$$ coordinates, according to the statement.

NoteThe vectors from the first example in the order of making jumps are $$$(0, 2), (0, -1), (1, 0), (0, 1), (0, -2)$$$.

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

let writeP (x, y) = Printf.printf "%d %d\n" (x+1) (y+1)

let run (n, m) =
  for x=0 to n/2-1 do
    for y=0 to m-1 do
      writeP (x, y); writeP (n-x-1, m-y-1)
    done;
  done;
  if n mod 2 = 1 then begin
    for y=0 to m/2-1 do
      writeP (n/2, y); writeP (n/2, m-y-1)
    done;
    if m mod 2 = 1 then writeP (n/2, m/2)
  end

let main () =
  let n = readInt () in
  let m = readInt () in
  run (n, m)

let () = main ()


Vasya's house is situated in a forest, and there is a mushroom glade near it. The glade consists of two rows, each of which can be divided into n consecutive cells. For each cell Vasya knows how fast the mushrooms grow in this cell (more formally, how many grams of mushrooms grow in this cell each minute). Vasya spends exactly one minute to move to some adjacent cell. Vasya cannot leave the glade. Two cells are considered adjacent if they share a common side. When Vasya enters some cell, he instantly collects all the mushrooms growing there.Vasya begins his journey in the left upper cell. Every minute Vasya must move to some adjacent cell, he cannot wait for the mushrooms to grow. He wants to visit all the cells exactly once and maximize the total weight of the collected mushrooms. Initially, all mushrooms have a weight of 0. Note that Vasya doesn't need to return to the starting cell.Help Vasya! Calculate the maximum total weight of mushrooms he can collect.

The first line contains the number n (1 ≤ n ≤ 3·105) — the length of the glade. The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the growth rate of mushrooms in the first row of the glade. The third line contains n numbers b1, b2, ..., bn (1 ≤ bi ≤ 106) is the growth rate of mushrooms in the second row of the glade.

Output one number — the maximum total weight of mushrooms that Vasya can collect by choosing the optimal route. Pay attention that Vasya must visit every cell of the glade exactly once.

NoteIn the first test case, the optimal route is as follows:    Thus, the collected weight of mushrooms will be 0·1 + 1·2 + 2·3 + 3·4 + 4·5 + 5·6 = 70.In the second test case, the optimal route is as follows:    Thus, the collected weight of mushrooms will be 0·1 + 1·10 + 2·100 + 3·1000 + 4·10000 + 5·100000 = 543210.

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0L in
  let b = Array.make n 0L in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%Ld " (fun s -> s)
    done;
    for i = 0 to n - 1 do
      b.(i) <- Scanf.bscanf sb "%Ld " (fun s -> s)
    done;
  in
  let sa = Array.make (n + 1) 0L in
  let sb = Array.make (n + 1) 0L in
  let pa = Array.make (n + 1) 0L in
  let pb = Array.make (n + 1) 0L in
  let qa = Array.make (n + 1) 0L in
  let qb = Array.make (n + 1) 0L in
  let _ =
    for i = 0 to n - 1 do
      sa.(i + 1) <- sa.(i) +| a.(i);
      sb.(i + 1) <- sb.(i) +| b.(i);
      pa.(i + 1) <- pa.(i) +| a.(i) *| Int64.of_int i;
      pb.(i + 1) <- pb.(i) +| b.(i) *| Int64.of_int i;
      qa.(i + 1) <- qa.(i) +| a.(i) *| Int64.of_int (n - 1 - i);
      qb.(i + 1) <- qb.(i) +| b.(i) *| Int64.of_int (n - 1 - i);
    done;
  in
  let res = ref 0L in
  let c = ref 0L in
    for i = 0 to n - 1 do
      if i mod 2 = 0 then (
	let d = pa.(n) -| pa.(i) +| (sa.(n) -| sa.(i)) *| Int64.of_int i in
	let e = qb.(n) -| qb.(i) +| (sb.(n) -| sb.(i)) *|
	    Int64.of_int (2 * i + (n - i))
	in
	let t = !c +| d +| e in
	  res := max !res t;
	  (*Printf.printf "asd %Ld %Ld\n" d e;*)
	  c := !c +| Int64.of_int (2 * i) *| a.(i) +|
	      Int64.of_int (2 * i + 1) *| b.(i);
      ) else (
	let d = pb.(n) -| pb.(i) +| (sb.(n) -| sb.(i)) *| Int64.of_int i in
	let e = qa.(n) -| qa.(i) +| (sa.(n) -| sa.(i)) *|
	    Int64.of_int (2 * i + (n - i))
	in
	let t = !c +| d +| e in
	  res := max !res t;
	  (*Printf.printf "asd %Ld %Ld\n" d e;*)
	  c := !c +| Int64.of_int (2 * i) *| b.(i) +|
	      Int64.of_int (2 * i + 1) *| a.(i);
      )
    done;
    Printf.printf "%Ld\n" !res


Consider an n × m grid. Initially all the cells of the grid are colored white. Lenny has painted some of the cells (at least one) black. We call a painted grid convex if one can walk from any black cell to any another black cell using a path of side-adjacent black cells changing his direction at most once during the path. In the figure below, the left grid is convex while the right one is not convex, because there exist two cells which need more than one time to change direction in their path.  You're given a painted grid in the input. Tell Lenny if the grid is convex or not.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 50) — the size of the grid. Each of the next n lines contains m characters "B" or "W". Character "B" denotes a black cell of the grid and "W" denotes a white cell of the grid. It's guaranteed that the grid has at least one black cell.

On the only line of the output print "YES" if the grid is convex, otherwise print "NO". Do not print quotes.

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

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

  let a = Array.make_matrix n m false in

  let blist = ref [] in

  let () =
    for i=0 to n-1 do
      let s = read_string() in
	for j=0 to m-1 do
	  a.(i).(j) <- s.[j]='B';
	  if a.(i).(j) then blist := (i,j)::(!blist)
	done
    done in

  let hpath i j jj =
    let good = ref true in
      for jjj = min j jj to max j jj do
	good := !good && a.(i).(jjj)
      done;
      !good
  in

  let vpath i j ii =
    let good = ref true in
      for iii = min i ii to max i ii do
	good := !good && a.(iii).(j)
      done;
      !good
  in

  let reachable (i,j) (ii,jj) =
      ((hpath i j jj) && (vpath i jj ii)) || ((vpath i j ii) && (hpath ii j jj))
  in

    if List.for_all (fun (i,j) -> List.for_all (fun (ii,jj) -> reachable (i,j) (ii,jj) ) !blist) !blist
    then Printf.printf "YES\n" else Printf.printf "NO\n"


Palo Alto is an unusual city because it is an endless coordinate line. It is also known for the office of Lyft Level 5.Lyft has become so popular so that it is now used by all $$$m$$$ taxi drivers in the city, who every day transport the rest of the city residents — $$$n$$$ riders.Each resident (including taxi drivers) of Palo-Alto lives in its unique location (there is no such pair of residents that their coordinates are the same).The Lyft system is very clever: when a rider calls a taxi, his call does not go to all taxi drivers, but only to the one that is the closest to that person. If there are multiple ones with the same distance, then to taxi driver with a smaller coordinate is selected.But one morning the taxi drivers wondered: how many riders are there that would call the given taxi driver if they were the first to order a taxi on that day? In other words, you need to find for each taxi driver $$$i$$$ the number $$$a_{i}$$$ — the number of riders that would call the $$$i$$$-th taxi driver when all drivers and riders are at their home?The taxi driver can neither transport himself nor other taxi drivers.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n,m \le 10^5$$$) — number of riders and taxi drivers. The second line contains $$$n + m$$$ integers $$$x_1, x_2, \ldots, x_{n+m}$$$ ($$$1 \le x_1 < x_2 < \ldots < x_{n+m} \le 10^9$$$), where $$$x_i$$$ is the coordinate where the $$$i$$$-th resident lives.  The third line contains $$$n + m$$$ integers $$$t_1, t_2, \ldots, t_{n+m}$$$ ($$$0 \le t_i \le 1$$$). If $$$t_i = 1$$$, then the $$$i$$$-th resident is a taxi driver, otherwise $$$t_i = 0$$$. It is guaranteed that the number of $$$i$$$ such that $$$t_i = 1$$$ is equal to $$$m$$$.

Print $$$m$$$ integers $$$a_1, a_2, \ldots, a_{m}$$$, where $$$a_i$$$ is the answer for the $$$i$$$-th taxi driver. The taxi driver has the number $$$i$$$ if among all the taxi drivers he lives in the $$$i$$$-th smallest coordinate (see examples for better understanding).

NoteIn the first example, we have only one taxi driver, which means an order from any of $$$n$$$ riders will go to him.In the second example, the first taxi driver lives at the point with the coordinate $$$2$$$, and the second one lives at the point with the coordinate $$$6$$$. Obviously, the nearest taxi driver to the rider who lives on the $$$3$$$ coordinate is the first one, and to the rider who lives on the coordinate $$$5$$$ is the second one. The rider who lives on the $$$4$$$ coordinate has the same distance to the first and the second taxi drivers, but since the first taxi driver has a smaller coordinate, the call from this rider will go to the first taxi driver.In the third example, we have one rider and the taxi driver nearest to him is the fourth one.

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 ( *< ) 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
	(* 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

let () =
	let n,m = get_2_i64 0 in
	let x = input_i64_array (n+m) in
	let t = input_i64_array (n+m) in
	let dr = ref [] in
	let re = ref [] in
	repi 0 (i32 (n+m)-$1) (fun i->
		let x,t = x.(i),t.(i) in
		if t=1L then dr := x::!dr
		else re := x::!re
	);
	let dr,re = of_list !dr,of_list !re in
	sort compare dr;
	sort compare re;
	(* iter (fun d ->
		let rleft,rright = lower_bound re d,binary_search (alen re) 0L (fun i->re.(i32 i)>d)
		in
		let vrleft = if rleft<0L || rleft>=n then Int64.max_int else re.(i32 rleft)
		in let vrright = if rright<0L || rright>=n then Int64.max_int else re.(i32 rright)
		in
		if labs (vrleft - d) < labs (vrright - d) then
	) dr *)
	let mx = Int64.max_int in
	let safe a i d = try a.(i32 i) with Invalid_argument _ -> d
	in
	let count = make (i32 m) 0L in
	(* print_array ist re;
	print_array ist dr; *)
	iter (fun r ->
		let d_l,d_r =
			(* binary_search (alen re-1L) 0L (fun i->safe dr i mx<r),
			binary_search 0L (alen re-1L) (fun i->safe dr i 0L>r) *)
			binary_search (alen dr-1L) 0L (fun i->dr.(i32 i)<r),
			binary_search 0L (alen dr-1L) (fun i->dr.(i32 i)>r)
		in
		let vdl,vdr = safe dr d_l mx,safe dr d_r (-1L) in
		(* printf "%Ld:%Ld -- %Ld:%Ld\n" d_l vdl d_r vdr; *)
		let i = if r-vdl<=0L then d_r else if vdr-r<=0L then d_l
		else if r - vdl <= vdr - r then d_l else d_r in
		count.(i32 i) <- count.(i32 i) + 1L;
	) re;
	iter (fun v->printf "%Ld " v) count


Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$) — the array that Phoenix currently has. This array may or may not be already beautiful.

For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.

NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example:   $$$2, 1, 2, 1, 2, 1$$$  $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also.

(* Codeforces 1348 B Phoenix and Beauty train *)

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

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

(* unique elements in sorted list *)
let rec diffr lun last sl = match sl with
  | [] -> lun
	| h :: t ->
		let nlun = if (h == last) then lun else h :: lun in
		diffr nlun h t;;

(* count number of different elements in integers list *)
let ldiff l =
    let sl = List.sort compare l in
    diffr [] (-1) sl;;

let repeat ls n =
    let rec f l = function
        | 0 -> l
        | n -> f (List.rev_append ls l) (n-1) in
    List.rev (f [] n)

let fill_to_k l k =
	(* let _ = Printf.printf "fill_to_k k,l = %d %s\n" k (list_to_s l) in *)
	let nfill = k - (List.length l) in
	if nfill <= 0 then l
	else
		let lf = repeat [List.hd l] nfill in
		(* let _ = Printf.printf "Fill: %s\n" (list_to_s lf) in *)
		List.append lf l;;

let rec beautya n k a =
	if n == k then (n , a)
	else
		let lun = ldiff a in
		(* let _ = printlisti lun in *)
		let lenun = List.length lun in
		if lenun > k then ((-1), [])
		else
      let lun = fill_to_k lun k in
			let ln = (k * n) in
		  let reta = repeat lun n in
		  (ln, reta);;

let do_one () =
  let n = gr () in
  let k = gr () in
	let a = List.rev (readlist n []) in
	let ln,reta = beautya n k a in
	begin
		print_int ln;
    print_string "\n";
		if ln > 0 then
			begin
  			printlisti reta;
        print_string "\n"
			end
	end;;

let rec do_all t = match t with
	| 0 -> ()
	| _ ->
		begin
			do_one ();
			do_all (t-1)
		end;;

let main() =
	let t = gr () in
	do_all t;;

main();;

(* Codeforces 1348 B Phoenix and Beauty train *)

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

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

(* unique elements in sorted list *)
let rec diffr lun last sl = match sl with
  | [] -> lun
	| h :: t ->
		let nlun = if (h == last) then lun else h :: lun in
		diffr nlun h t;;

(* count number of different elements in integers list *)
let ldiff l =
    let sl = List.sort compare l in
    diffr [] (-1) sl;;

let repeat ls n =
    let rec f l = function
        | 0 -> l
        | n -> f (List.rev_append ls l) (n-1) in
    List.rev (f [] n)

let rec beautya n k a =
	if n == k then (n , a)
	else
		let lun = ldiff a in
		(* let _ = printlisti lun in *)
		let lenun = List.length lun in
		if lenun > k then ((-1), [])
		else
			let ln = (lenun * n) in
		  let reta = repeat lun n in
		  (ln, reta);;

let do_one () =
  let n = gr () in
  let k = gr () in
	let a = readlist n [] in
	let ln,reta = beautya n k a in
	begin
		print_int ln;
    print_string "\n";
		if ln > 0 then
			begin
  			printlisti reta;
        print_string "\n"
			end
	end;;

let rec do_all t = match t with
	| 0 -> ()
	| _ ->
		begin
			do_one ();
			do_all (t-1)
		end;;

let main() =
	let t = gr () in
	do_all t;;

main();;

(* Codeforces 1348 B Phoenix and Beauty train *)

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

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

(* unique elements in sorted list *)
let rec diffr lun last sl = match sl with
  | [] -> lun
	| h :: t ->
		let nlun = if (h == last) then lun else h :: lun in
		diffr nlun h t;;

(* count number of different elements in integers list *)
let ldiff l =
    let sl = List.sort compare l in
    diffr [] (-1) sl;;

let repeat ls n =
    let rec f l = function
        | 0 -> l
        | n -> f (List.rev_append ls l) (n-1) in
    List.rev (f [] n)

let fill_to_k l k =
	(* let _ = Printf.printf "fill_to_k k,l = %d %s\n" k (list_to_s l) in *)
	let nfill = k - (List.length l) in
	if nfill <= 0 then l
	else
		let lf = repeat [List.hd l] nfill in
		(* let _ = Printf.printf "Fill: %s\n" (list_to_s lf) in *)
		List.append lf l;;

let rec beautya n k a =
	if n == k then (n , a)
	else
		let lun = ldiff a in
		(* let _ = printlisti lun in *)
		let lenun = List.length lun in
		if lenun > k then ((-1), [])
		else
      let lun = fill_to_k lun k in
			let ln = (k * n) in
		  let reta = repeat lun n in
		  (ln, reta);;

let do_one () =
  let n = gr () in
  let k = gr () in
	let a = readlist n [] in
	let ln,reta = beautya n k a in
	begin
		print_int ln;
    print_string "\n";
		if ln > 0 then
			begin
  			printlisti reta;
        print_string "\n"
			end
	end;;

let rec do_all t = match t with
	| 0 -> ()
	| _ ->
		begin
			do_one ();
			do_all (t-1)
		end;;

let main() =
	let t = gr () in
	do_all t;;

main();;


Some people leave the lights at their workplaces on when they leave that is a waste of resources. As a hausmeister of DHBW, Sagheer waits till all students and professors leave the university building, then goes and turns all the lights off.The building consists of n floors with stairs at the left and the right sides. Each floor has m rooms on the same line with a corridor that connects the left and right stairs passing by all the rooms. In other words, the building can be represented as a rectangle with n rows and m + 2 columns, where the first and the last columns represent the stairs, and the m columns in the middle represent rooms.Sagheer is standing at the ground floor at the left stairs. He wants to turn all the lights off in such a way that he will not go upstairs until all lights in the floor he is standing at are off. Of course, Sagheer must visit a room to turn the light there off. It takes one minute for Sagheer to go to the next floor using stairs or to move from the current room/stairs to a neighboring room/stairs on the same floor. It takes no time for him to switch the light off in the room he is currently standing in. Help Sagheer find the minimum total time to turn off all the lights.Note that Sagheer does not have to go back to his starting position, and he does not have to visit rooms where the light is already switched off.

The first line contains two integers n and m (1 ≤ n ≤ 15 and 1 ≤ m ≤ 100) — the number of floors and the number of rooms in each floor, respectively. The next n lines contains the building description. Each line contains a binary string of length m + 2 representing a floor (the left stairs, then m rooms, then the right stairs) where 0 indicates that the light is off and 1 indicates that the light is on. The floors are listed from top to bottom, so that the last line represents the ground floor. The first and last characters of each string represent the left and the right stairs, respectively, so they are always 0.

Print a single integer — the minimum total time needed to turn off all the lights.

NoteIn the first example, Sagheer will go to room 1 in the ground floor, then he will go to room 2 in the second floor using the left or right stairs.In the second example, he will go to the fourth room in the ground floor, use right stairs, go to the fourth room in the second floor, use right stairs again, then go to the second room in the last floor.In the third example, he will walk through the whole corridor alternating between the left and right stairs at each floor.

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 minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)
let maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)
let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)

let read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)
let read_string _ = bscanf Scanning.stdib " %s " (fun x -> x)
let () =
  let n = read_int () in
  let m = read_int () in
  let light = Array.init n read_string in
(* light.(f).[r] = is the light on floor f in room r *)
  let ison f r = light.(n-1-f).[r] = '1' in

  let floor_off f = forall 0 (m+1) (fun r -> not (ison f r)) in

  let top_floor = maxf 0 (n-1) (fun f -> if floor_off f then 0 else f) in

  let ftime f st en =
  (* time to clear floor f starting at st (=0/1 for left/right) ending at en *)
    if en <> st then m+1
    else if st=0 then 2 * (maxf 1 m (fun r -> if ison f r then r else 0))
    else if st=1 then 2 * (maxf 1 m (fun r -> if ison f r then (m+1-r) else 0))
    else failwith "no"
  in

  let dp = Array.make_matrix n 2 0 in

  for f=0 to n-2 do
    for en = 0 to 1 do
      dp.(f).(en) <-
	if f=0 then ftime f 0 en
	else minf 0 1 (fun st -> dp.(f-1).(st) + 1 + (ftime f st en))
(*      printf "dp.(%d).(%d) = %d\n" f en dp.(f).(en) *)
    done
  done;

(* handle the last floor *)

  let answer f =
    if f=0 then (ftime 0 0 0)/2
    else minf 0 1 (fun st -> dp.(f-1).(st) + ((ftime f st st)/2) + 1)
  in

  printf "%d\n" (answer top_floor)

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 minf i j f = fold (i+1) j (fun k a -> min (f k) a) (f i)
let maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)
let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)

let read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)
let read_string _ = bscanf Scanning.stdib " %s " (fun x -> x)
let () =
  let n = read_int () in
  let m = read_int () in
  let light = Array.init n read_string in
(* light.(f).[r] = is the light on floor f in room r *)
  let ison f r = light.(n-1-f).[r] = '1' in

  let floor_off f = forall 0 (m+1) (fun r -> not (ison f r)) in

  let top_floor = maxf 0 (n-1) (fun f -> if floor_off f then 0 else f) in

  let ftime f st en =
  (* time to clear floor f starting at st (=0/1 for left/right) ending at en *)
    if en <> st then m+1
    else if st=0 then 2 * (maxf 1 m (fun r -> if ison f r then r else 0))
    else if st=1 then 2 * (maxf 1 m (fun r -> if ison f r then (m+1-r) else 0))
    else failwith "no"
  in

  let best_cost = ref 1_000_000 in

  let rec backtrack f side cost =
    if f = top_floor then (
      let top_cost = (ftime f side side)/2 in
      best_cost := min !best_cost (cost + 1 + top_cost)
    ) else (
      backtrack (f+1) side (cost + 1 + ftime f side side);
      backtrack (f+1) (1-side) (cost + 1 + ftime f side (1-side));
    )
  in

  backtrack 0 0 (-1);

  printf "%d\n" !best_cost

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

let read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)
let read_string _ = bscanf Scanning.stdib " %s " (fun x -> x)
let () =
  let n = read_int () in
  let m = read_int () in
  let light = Array.init n read_string in
(* light.(f).[r] = is the light on floor f in room r *)
  let ison f r = light.(n-1-f).[r] = '1' in

  let ftime f st en =
  (* time to clear floor f starting at st (=0/1 for left/right) ending at en *)
    if en <> st then m+1
    else if st=0 then 2 * (maxf 1 m (fun r -> if ison f r then r else 0))
    else if st=1 then 2 * (maxf 1 m (fun r -> if ison f r then (m+1-r) else 0))
    else failwith "no"
  in

  let dp = Array.make_matrix n 2 0 in

  for f=0 to n-2 do
    for en = 0 to 1 do
      dp.(f).(en) <-
	if f=0 then ftime f 0 en
	else minf 0 1 (fun st -> dp.(f-1).(st) + 1 + (ftime f st en))
(*      printf "dp.(%d).(%d) = %d\n" f en dp.(f).(en) *)
    done
  done;

(* handle the last floor *)

  let answer f =
    if f=0 then (ftime 0 0 0)/2
    else minf 0 1 (fun st -> dp.(f-1).(st) + ((ftime f st st)/2) + 1)
  in

  printf "%d\n" (answer (n-1))

open Printf
open Scanf

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

let read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)
let read_string _ = bscanf Scanning.stdib " %s " (fun x -> x)
let () =
  let n = read_int () in
  let m = read_int () in
  let light = Array.init n read_string in
(* light.(f).[r] = is the light on floor f in room r *)
  let ison f r = light.(n-1-f).[r] = '1' in

  let inf = 1_000_000_000 in

  let ftime f st en =
  (* time to clear floor f starting at st (=0/1 for left/right) ending at en *)
    if en <> st then m+1
    else if st=0 then 2 * (maxf 1 m (fun r -> if ison f r then r else 0))
    else if st=1 then 2 * (maxf 1 m (fun r -> if ison f r then (m+1-r) else 0))
    else failwith "no"
  in

  let dp = Array.make_matrix n 2 0 in

  for f=0 to n-2 do
    for en = 0 to 1 do
      dp.(f).(en) <-
	if f=0 then ftime f 0 en
	else minf 0 1 (fun st -> dp.(f-1).(st) + 1 + (ftime f st en))
(*      printf "dp.(%d).(%d) = %d\n" f en dp.(f).(en) *)
    done
  done;

(* handle the last floor *)

  let answer f = minf 0 1 (fun st ->
    let prev = if f=0 then (if st=0 then 0 else inf) else dp.(f-1).(st) in
    prev + ((ftime f st st)/2) + (if f<>0 then 1 else 0)
  ) in

  printf "%d\n" (answer (n-1))


Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences.Let's assume that strings s and t have the same length n, then the function h(s, t) is defined as the number of positions in which the respective symbols of s and t are the same. Function h(s, t) can be used to define the function of Vasya distance ρ(s, t):  where  is obtained from string s, by applying left circular shift i times. For example, ρ("AGC", "CGT") =  h("AGC", "CGT") + h("AGC", "GTC") + h("AGC", "TCG") +  h("GCA", "CGT") + h("GCA", "GTC") + h("GCA", "TCG") +  h("CAG", "CGT") + h("CAG", "GTC") + h("CAG", "TCG") =  1 + 1 + 0 + 0 + 1 + 1 + 1 + 0 + 1 = 6Vasya found a string s of length n on the Internet. Now he wants to count how many strings t there are such that the Vasya distance from the string s attains maximum possible value. Formally speaking, t must satisfy the equation: .Vasya could not try all possible strings to find an answer, so he needs your help. As the answer may be very large, count the number of such strings modulo 109 + 7.

The first line of the input contains a single integer n (1 ≤ n ≤ 105). The second line of the input contains a single string of length n, consisting of characters "ACGT".

Print a single number — the answer modulo 109 + 7.

NotePlease note that if for two distinct strings t1 and t2 values ρ(s, t1) и ρ(s, t2) are maximum among all possible t, then both strings must be taken into account in the answer even if one of them can be obtained by a circular shift of another one.In the first sample, there is ρ("C", "C") = 1, for the remaining strings t of length 1 the value of ρ(s, t) is 0.In the second sample, ρ("AG", "AG") = ρ("AG", "GA") = ρ("AG", "AA") = ρ("AG", "GG") = 4.In the third sample, ρ("TTT", "TTT") = 27

open Printf
open Scanf

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

let long x = Int64.of_int x

let mm = 1_000_000_007L

let rec ( ^ ) e p =
  if p=0 then 1L else
    let a = e^(p/2) in
    if (p land 1)=0 then (a**a) %% mm else (e**((a**a) %% mm)) %%mm

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

  let hist = Array.make 4 0 in

  for i=0 to n-1 do
    let j = match s.[i] with
      | 'A' -> 0
      | 'G' -> 1
      | 'C' -> 2
      | 'T' -> 3
      | _ -> failwith "bad input"
    in
    hist.(j) <- hist.(j) + 1
  done;

  Array.sort compare hist;

  let ct = ref 1 in

  for i=0 to 2 do
    if hist.(3) = hist.(i) then ct := !ct+1
  done;

  let answer = (long !ct) ^ n in

  printf "%Ld\n" answer


The R2 company has n employees working for it. The work involves constant exchange of ideas, sharing the stories of success and upcoming challenging. For that, R2 uses a famous instant messaging program Spyke.R2 has m Spyke chats just to discuss all sorts of issues. In each chat, some group of employees exchanges messages daily. An employee can simultaneously talk in multiple chats. If some employee is in the k-th chat, he can write messages to this chat and receive notifications about messages from this chat. If an employee writes a message in the chat, all other participants of the chat receive a message notification.The R2 company is conducting an audit. Now the specialists study effective communication between the employees. For this purpose, they have a chat log and the description of chat structure. You, as one of audit specialists, are commissioned to write a program that will use this data to determine the total number of message notifications received by each employee.

The first line contains three space-separated integers n, m and k (2 ≤ n ≤ 2·104; 1 ≤ m ≤ 10; 1 ≤ k ≤ 2·105) — the number of the employees, the number of chats and the number of events in the log, correspondingly.  Next n lines contain matrix a of size n × m, consisting of numbers zero and one. The element of this matrix, recorded in the j-th column of the i-th line, (let's denote it as aij) equals 1, if the i-th employee is the participant of the j-th chat, otherwise the element equals 0. Assume that the employees are numbered from 1 to n and the chats are numbered from 1 to m. Next k lines contain the description of the log events. The i-th line contains two space-separated integers xi and yi (1 ≤ xi ≤ n; 1 ≤ yi ≤ m) which mean that the employee number xi sent one message to chat number yi. It is guaranteed that employee number xi is a participant of chat yi. It is guaranteed that each chat contains at least two employees.

Print in the single line n space-separated integers, where the i-th integer shows the number of message notifications the i-th employee receives.

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int() and m=read_int() and k=read_int();;
let mat=Array.make_matrix (n+1) (m+1) 0;;
for i=1 to n do
   for j=1 to m do
      mat.(i).(j)<-read_int()
   done
done;;
let tab=Array.make (m+1) 0;;
let mess=Array.make (n+1) 0;;
for i=1 to k do
   let x=read_int() and j=read_int() in
   begin
   mess.(x)<-mess.(x)-1;
   tab.(j)<-tab.(j)+1
   end
done;;

for i=1 to n do
   for j=1 to m do
      mess.(i)<-mess.(i)+mat.(i).(j)*tab.(j)
   done;
   Printf.printf "%d " mess.(i)
done;;


Nikita has a stack. A stack in this problem is a data structure that supports two operations. Operation push(x) puts an integer x on the top of the stack, and operation pop() deletes the top integer from the stack, i. e. the last added. If the stack is empty, then the operation pop() does nothing.Nikita made m operations with the stack but forgot them. Now Nikita wants to remember them. He remembers them one by one, on the i-th step he remembers an operation he made pi-th. In other words, he remembers the operations in order of some permutation p1, p2, ..., pm. After each step Nikita wants to know what is the integer on the top of the stack after performing the operations he have already remembered, in the corresponding order. Help him!

The first line contains the integer m (1 ≤ m ≤ 105) — the number of operations Nikita made. The next m lines contain the operations Nikita remembers. The i-th line starts with two integers pi and ti (1 ≤ pi ≤ m, ti = 0 or ti = 1) — the index of operation he remembers on the step i, and the type of the operation. ti equals 0, if the operation is pop(), and 1, is the operation is push(x). If the operation is push(x), the line also contains the integer xi (1 ≤ xi ≤ 106) — the integer added to the stack. It is guaranteed that each integer from 1 to m is present exactly once among integers pi.

Print m integers. The integer i should equal the number on the top of the stack after performing all the operations Nikita remembered on the steps from 1 to i. If the stack is empty after performing all these operations, print -1.

NoteIn the first example, after Nikita remembers the operation on the first step, the operation push(2) is the only operation, so the answer is 2. After he remembers the operation pop() which was done before push(2), answer stays the same.In the second example, the operations are push(2), push(3) and pop(). Nikita remembers them in the order they were performed.In the third example Nikita remembers the operations in the reversed order.

type op =
  | Pop
  | Push of int

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let ops = Array.make n (0, Pop) in
  let _ =
    for i = 0 to n - 1 do
      let p = Scanf.bscanf sb "%d " (fun s -> s) in
      let t = Scanf.bscanf sb "%d " (fun s -> s) in
	if t = 0
	then ops.(i) <- (p - 1, Pop)
	else (
	  let x = Scanf.bscanf sb "%d " (fun s -> s) in
	    ops.(i) <- (p - 1, Push x)
	)
    done;
  in
  let o =
    let d = ref 1 in
      while !d < n do
	d := !d * 2;
      done;
      !d
  in
  let sum = Array.make (2 * o) 0 in
  let max_suf = Array.make (2 * o) 0 in
  let rec update i x l r k =
    if l = r then (
      sum.(k) <- x;
      max_suf.(k) <- x;
    ) else (
      let m = (l + r) / 2 in
	if i <= m
	then update i x l m (2 * k + 1)
	else update i x (m + 1) r (2 * k + 2);
	  sum.(k) <- sum.(2 * k + 1) + sum.(2 * k + 2);
	  max_suf.(k) <- max (sum.(2 * k + 2) + max_suf.(2 * k + 1))
	    max_suf.(2 * k + 2);
    )
  in
  let a = Array.make n 0 in
    for i = 0 to n - 1 do
      (match ops.(i) with
	 | (pos, Push x) ->
	     a.(pos) <- x;
	     update pos 1 0 (o - 1) 0
	 | (pos, Pop) ->
	     update pos (-1) 0 (o - 1) 0
      );
      if max_suf.(0) <= 0 then (
	Printf.printf "-1\n"
      ) else (
	let idx = ref 0 in
	let s = ref 0 in
	  (*for i = 0 to 2 * o - 2 do
	    Printf.printf "asd %d %d %d\n" i sum.(i) max_suf.(i)
	  done;*)
	  while !idx < o - 1 do
	    (*Printf.printf "qwe %d\n" !idx;*)
	    if 2 * !idx + 2 < 2 * o - 1 && max_suf.(2 * !idx + 2) + !s > 0 then (
	      idx := 2 * !idx + 2;
	    ) else (
	      if 2 * !idx + 2 < 2 * o - 1
	      then s := !s + sum.(2 * !idx + 2);
	      idx := 2 * !idx + 1;
	    )
	  done;
	  (*Printf.printf "idx %d\n" (!idx - o + 1);*)
	  Printf.printf "%d\n" a.(!idx - o + 1)
      )
    done;
    (*for i = 0 to 2 * o - 2 do
      Printf.printf "asd %d %d %d\n" i sum.(i) max_suf.(i)
    done;*)


The employees of the R1 company often spend time together: they watch football, they go camping, they solve contests. So, it's no big deal that sometimes someone pays for someone else.Today is the day of giving out money rewards. The R1 company CEO will invite employees into his office one by one, rewarding each one for the hard work this month. The CEO knows who owes money to whom. And he also understands that if he invites person x to his office for a reward, and then immediately invite person y, who has lent some money to person x, then they can meet. Of course, in such a situation, the joy of person x from his brand new money reward will be much less. Therefore, the R1 CEO decided to invite the staff in such an order that the described situation will not happen for any pair of employees invited one after another.However, there are a lot of employees in the company, and the CEO doesn't have a lot of time. Therefore, the task has been assigned to you. Given the debt relationships between all the employees, determine in which order they should be invited to the office of the R1 company CEO, or determine that the described order does not exist.

The first line contains space-separated integers n and m  — the number of employees in R1 and the number of debt relations. Each of the following m lines contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi), these integers indicate that the person number ai owes money to a person a number bi. Assume that all the employees are numbered from 1 to n. It is guaranteed that each pair of people p, q is mentioned in the input data at most once. In particular, the input data will not contain pairs p, q and q, p simultaneously.

Print -1 if the described order does not exist. Otherwise, print the permutation of n distinct integers. The first number should denote the number of the person who goes to the CEO office first, the second number denote the person who goes second and so on. If there are multiple correct orders, you are allowed to print any of them.

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int() and m=read_int();;
let pred=Array.make (n+1) [0];;
for i=1 to n do
   pred.(i)<-[]
done;;
for i=1 to m do
   let x=read_int() and y=read_int() in
   pred.(x)<-y::pred.(x)
done;;
type etat=Vu|Non_vu|En_cours;;
let mark=Array.make (n+1) Non_vu;;
let res=ref [];;

let rec dfs u=function
|[]->mark.(u)<-Vu;res:=u::(!res)
|h::t->if mark.(h)=Non_vu then
          begin
          mark.(h)<-En_cours;
          dfs h pred.(h)
          end;
       dfs u t;;

let tri()=
for i=1 to n do
   if mark.(i)=Vu then () else
      begin
      mark.(i)<-En_cours;
      dfs i pred.(i)
      end;
done;;

tri();;

let rec print_list=function
|[]->print_newline()
|h::t->print_list t;Printf.printf "%d " h;;

print_list !res;;

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let es = Array.make n [] in
  let ht = Hashtbl.create m in
  let () =
    for i = 1 to m do
      let u = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
      let v = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
	es.(u) <- v :: es.(u);
	Hashtbl.add ht (v, u) ();
    done
  in
  let es = Array.map Array.of_list es in
  let used = Array.make n false in
  let res = ref [] in
  let stack = Array.make (2 * n) (fun _ -> ()) in
  let stack_pos = ref 0 in
  let rec execute () =
    if !stack_pos > 0 then (
      decr stack_pos;
      let f = stack.(!stack_pos) in
	f ();
	execute ()
    )
  in
  let rec dfs u prev =
    used.(u) <- true;
    let rec aux i =
      if i < Array.length es.(u) then (
	stack.(!stack_pos) <- (fun () -> aux (i + 1));
	incr stack_pos;
	let v = es.(u).(i) in
	  if not used.(v) then (
	    (*let f () =
	      (*pe.(v) <- edge;
	      tout.(u) <- !t;
	      incr t;*) ()
	    in
	      (*stack.(!stack_pos) <- f;
	      incr stack_pos;*)*)
	      stack.(!stack_pos) <- (fun () -> dfs v u);
	      incr stack_pos;
	  )
      ) else (
      )
    in
    let f () =
      res := u :: !res
    in
      stack.(!stack_pos) <- f;
      incr stack_pos;
      aux 0
  in
    for u = 0 to n - 1 do
      if not used.(u) then (
	stack_pos := 0;
	dfs u 0;
	execute ();
      )
    done;
    List.iter
      (fun u ->
	 Printf.printf "%d " (u + 1)
      ) (List.rev !res);
    Printf.printf "\n"

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let es = Array.make n [] in
  let ht = Hashtbl.create m in
  let () =
    for i = 1 to m do
      let u = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
      let v = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
	es.(v) <- u :: es.(u);
	Hashtbl.add ht (v, u) ();
    done
  in
  let es = Array.map Array.of_list es in
  let used = Array.make n false in
  let res = ref [] in
  let stack = Array.make (2 * n) (fun _ -> ()) in
  let stack_pos = ref 0 in
  let rec execute () =
    if !stack_pos > 0 then (
      decr stack_pos;
      let f = stack.(!stack_pos) in
	f ();
	execute ()
    )
  in
  let rec dfs u prev =
    used.(u) <- true;
    let rec aux i =
      if i < Array.length es.(u) then (
	stack.(!stack_pos) <- (fun () -> aux (i + 1));
	incr stack_pos;
	let v = es.(u).(i) in
	  if not used.(v) then (
	    (*let f () =
	      (*pe.(v) <- edge;
	      tout.(u) <- !t;
	      incr t;*) ()
	    in
	      (*stack.(!stack_pos) <- f;
	      incr stack_pos;*)*)
	      stack.(!stack_pos) <- (fun () -> dfs v u);
	      incr stack_pos;
	  )
      ) else (
      )
    in
    let f () =
      res := u :: !res
    in
      stack.(!stack_pos) <- f;
      incr stack_pos;
      aux 0
  in
    for u = 0 to n - 1 do
      if not used.(u) then (
	stack_pos := 0;
	dfs u 0;
	execute ();
      )
    done;
    List.iter
      (fun u ->
	 Printf.printf "%d " (u + 1)
      ) ((*List.rev*) !res);
    Printf.printf "\n"


Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the rating of i-th student as ai. After the contest ends, every student will end up with some positive integer position. GukiZ expects that his students will take places according to their ratings. He thinks that each student will take place equal to . In particular, if student A has rating strictly lower then student B, A will get the strictly better position than B, and if two students have equal ratings, they will share the same position. GukiZ would like you to reconstruct the results by following his expectations. Help him and determine the position after the end of the contest for each of his students if everything goes as expected.

The first line contains integer n (1 ≤ n ≤ 2000), number of GukiZ's students.  The second line contains n numbers a1, a2, ... an (1 ≤ ai ≤ 2000) where ai is the rating of i-th student (1 ≤ i ≤ n).

In a single line, print the position after the end of the contest for each of n students in the same order as they appear in the input.

NoteIn the first sample, students 2 and 3 are positioned first (there is no other student with higher rating), and student 1 is positioned third since there are two students with higher rating.In the second sample, first student is the only one on the contest.In the third sample, students 2 and 5 share the first position with highest rating, student 4 is next with third position, and students 1 and 3 are the last sharing fourth position.

open Printf
open Scanf

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

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

let () =
    (* let start_time = Sys.time() in *)

    let n = read_int () in
    let a = Array.init n (fun _ -> read_int()) in
    let b = Array.init n (fun i -> string_of_int (
                            1 + sum 0 n (fun x -> if a.(x) > a.(i) then 1 else 0)
                         )) in
    print_string (String.concat " " (Array.to_list b));

    (* let finish_time = Sys.time() in *)
    (* printf "Time of scanning %fs\n" (finish_time -. start_time); *)
    (* b;; *)

let () =
	let n = Scanf.scanf "%d" (fun i -> i) and l = ref [] and tab = Array.make 2001 0
	and tab' = Array.make 2001 0 in
		for i=1 to n do
			Scanf.scanf " %d" (fun j -> tab.(j) <- tab.(j) + 1; l := j::!l);
		done;
		for i=2000 downto 1 do
			tab'.(i-1) <- tab'.(i) + tab.(i);
		done;
	List.iter (fun i -> Printf.printf "%d " (1 + tab'.(i))) (List.rev !l)

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 main () =
    let start_time = Sys.time() in

    let n = read_int () in
    let a = Array.init n (fun _ -> read_int()) in
    let b = Array.init n (fun i -> string_of_int (
                            sum 0 n (fun x -> if a.(x) > a.(i) then 1 else 0)
                         )) in
    print_string (String.concat " " (Array.to_list b));

    let finish_time = Sys.time() in
    printf "Time of scanning %fs\n" (finish_time -. start_time);
    b;;

open Printf
open Scanf

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

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

let () =
    (* let start_time = Sys.time() in *)

    let n = read_int () in
    let a = Array.init n (fun _ -> read_int()) in
    let b = Array.init n (fun i -> string_of_int (
                            sum 0 n (fun x -> if a.(x) > a.(i) then 1 else 0)
                         )) in
    print_string (String.concat " " (Array.to_list b));

    (* let finish_time = Sys.time() in *)
    (* printf "Time of scanning %fs\n" (finish_time -. start_time); *)
    (* b;; *)