Bob is a pirate looking for the greatest treasure the world has ever seen. The treasure is located at the point $$$T$$$, which coordinates to be found out.Bob travelled around the world and collected clues of the treasure location at $$$n$$$ obelisks. These clues were in an ancient language, and he has only decrypted them at home. Since he does not know which clue belongs to which obelisk, finding the treasure might pose a challenge. Can you help him?As everyone knows, the world is a two-dimensional plane. The $$$i$$$-th obelisk is at integer coordinates $$$(x_i, y_i)$$$. The $$$j$$$-th clue consists of $$$2$$$ integers $$$(a_j, b_j)$$$ and belongs to the obelisk $$$p_j$$$, where $$$p$$$ is some (unknown) permutation on $$$n$$$ elements. It means that the treasure is located at $$$T=(x_{p_j} + a_j, y_{p_j} + b_j)$$$. This point $$$T$$$ is the same for all clues.In other words, each clue belongs to exactly one of the obelisks, and each obelisk has exactly one clue that belongs to it. A clue represents the vector from the obelisk to the treasure. The clues must be distributed among the obelisks in such a way that they all point to the same position of the treasure.Your task is to find the coordinates of the treasure. If there are multiple solutions, you may print any of them.Note that you don't need to find the permutation. Permutations are used only in order to explain the problem.

The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 1000$$$) — the number of obelisks, that is also equal to the number of clues. Each of the next $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$-10^6 \leq x_i, y_i \leq 10^6$$$) — the coordinates of the $$$i$$$-th obelisk. All coordinates are distinct, that is $$$x_i \neq x_j$$$ or $$$y_i \neq y_j$$$ will be satisfied for every $$$(i, j)$$$ such that $$$i \neq j$$$.  Each of the next $$$n$$$ lines contains two integers $$$a_i$$$, $$$b_i$$$ ($$$-2 \cdot 10^6 \leq a_i, b_i \leq 2 \cdot 10^6$$$) — the direction of the $$$i$$$-th clue. All coordinates are distinct, that is $$$a_i \neq a_j$$$ or $$$b_i \neq b_j$$$ will be satisfied for every $$$(i, j)$$$ such that $$$i \neq j$$$.  It is guaranteed that there exists a permutation $$$p$$$, such that for all $$$i,j$$$ it holds $$$\left(x_{p_i} + a_i, y_{p_i} + b_i\right) = \left(x_{p_j} + a_j, y_{p_j} + b_j\right)$$$.

Output a single line containing two integers $$$T_x, T_y$$$ — the coordinates of the treasure. If there are multiple answers, you may print any of them.

NoteAs $$$n = 2$$$, we can consider all permutations on two elements. If $$$p = [1, 2]$$$, then the obelisk $$$(2, 5)$$$ holds the clue $$$(7, -2)$$$, which means that the treasure is hidden at $$$(9, 3)$$$. The second obelisk $$$(-6, 4)$$$ would give the clue $$$(-1,-3)$$$ and the treasure at $$$(-7, 1)$$$. However, both obelisks must give the same location, hence this is clearly not the correct permutation.If the hidden permutation is $$$[2, 1]$$$, then the first clue belongs to the second obelisk and the second clue belongs to the first obelisk. Hence $$$(-6, 4) + (7, -2) = (2,5) + (-1,-3) = (1, 2)$$$, so $$$T = (1,2)$$$ is the location of the treasure.  In the second sample, the hidden permutation is $$$[2, 3, 4, 1]$$$.

open Printf open Scanf
module Lib = struct
  let i32,i64,ist = Int64.(to_int,of_int,to_string)
  let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (%$) = (mod)
  let labs = Int64.abs
  let (+),(-),( * ),(/),(mod),(%) = Int64.(add,sub,mul,div,rem,rem)
  let (+=) r v = r := !r + v
  let (-=) r v = r := !r - v
  let ( *= ) r v = r := !r * v
  let (/=) r v = r := !r / v
  let (%=) r v = r := !r % v
  let max_i64,min_i64 = Int64.(max_int,min_int)
  (* math *)
  let ceildiv p q = (p+q-1L) / q
  let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n)
  let lcm m n = m / gcd m n * n
  module Int64_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
  let pow n k =
    let rec f a n = function
    | 0L -> a | 1L -> n*a | k when k mod 2L = 0L -> f a (n*n) (k/2L) | k -> f (a*n) (n*n) (k/2L)
    in f 1L n k
  (* input *)
  let input_i64_array n = Array.init (i32 n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v)) let iia = input_i64_array
  let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v) let gi = get_i64
  let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v) let g2 = get_2_i64
  let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w) let g3 = get_3_i64
  let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x) let g4 = get_4_i64
  let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y) let g5 = get_5_i64
  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 slen s = String.length s
  let string_of_list ?(separator=" ") f ls = ls |> List.map f |> String.concat separator
  let string_of_array ?(separator=" ") f a = a |> Array.to_list |> string_of_list ~separator f
  let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) []
  let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
  let fail _ = failwith "fail"
  let dx,dy = [|1;0;-1;0|],[|0;1;0;-1|]
  let range l r = let ls = ref [] in for i=i32 l to i32 r do ls := i :: !ls done;!ls |> List.rev
  let cartesian_product u v = u |> List.map (fun p -> List.map (fun q -> p,q) v) |> List.flatten
  let shuffle a = Array.sort (fun _ _ -> (Random.int 3) -$ 1) a
  let binary_search ng ok f = let d = if ng < ok then 1L else -1L in
    let rec f0 ng ok =
      if labs (ok - ng) <= 1L then ok
      else let mid = ng + (ok - ng) / 2L in if f mid then f0 ng mid else f0 mid ok
    in f0 (ng-1L*d) (ok+1L*d)
  let lower_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >= v)
  let upper_bound a v = binary_search 0L (alen a - 1L) (fun i -> a.(i32 i) >  v)
  let equal_range a v = lower_bound a v, upper_bound a v (* #=snd-fst *)
  let rec fix f x = f (fix f) x
  let fix_memo ?(size=10000) f x =
    let tb = Hashtbl.create ~random:true size in
    let rec f0 x =
      try Hashtbl.find tb x with
      | Not_found -> (let v = f f0 x in Hashtbl.add tb x v; v)
    in f0 x
  (* imperative *)
  let rep f t ?(stride=1L) fbod = let i = ref f in while !i <= t do fbod !i; i := !i + stride done
  let repb f t ?(stride=1L) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i + stride done
  let repm f t ?(stride=1L) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i + stride done; !m
  let repi f t ?(stride=1) fbod = let i = ref f in while !i <= t do fbod !i; i := !i +$ stride done
  let repib f t ?(stride=1) fbod = let i,c = ref f,ref true in while !i <= t && !c do
    match fbod !i with | `Break -> c := false | `Ok -> i := !i +$ stride done
  let repim f t ?(stride=1) m0 fbod =
    let i,c,m = ref f,ref true,ref m0 in
    while !i<=t && !c do match fbod !m !i with
    | `Break -> c := false | `Break_m m' -> (c := false; m := m') | `Ok m' -> m := m'; i := !i +$ stride done; !m
  let rep_rev f t ?(stride=1L) fbod = rep t f ~stride @@ fun v -> fbod @@ f + t - v
  let repb_rev f t ?(stride=1L) fbod = repb t f ~stride @@ fun v -> fbod @@ f + t - v
  let repm_rev f t ?(stride=1L) m0 fbod = repm f t ~stride m0 @@ fun u v -> fbod u @@ f + t - v
  let repi_rev f t ?(stride=1) fbod = repi t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repib_rev f t ?(stride=1) fbod = repib t f ~stride @@ fun v -> fbod @@ f +$ t -$ v
  let repim_rev f t ?(stride=1) m0 fbod = repim f t ~stride m0 @@ fun u v -> fbod u @@ f +$ t -$ v
  (* output *)
  let print_list_mle f ls = string_of_list f ls |> print_endline
  let print_array_mle f a = string_of_array f a |> print_endline
  let print_list f ls = ls |> List.iter (fun v -> printf "%s " @@ f v); print_newline ()
  let print_array f a = a |> Array.iter (fun v -> printf "%s " @@ f v); print_newline ()
  (* debug *)
  let dump_2darr f a = a |> Array.iter (fun b -> print_array f b)
  let dump_i64_list ls = print_list ist ls
  let dump_i64_array a = print_array ist a
end open Lib open Array
module IMap = Map.Make (struct
  type t = int64 * int64
  let compare = compare
end)
let () =
  let n = gi 0 in
  let x,y = make (i32 n) 0L, make (i32 n) 0L in
  repi 1 (i32 n) (fun i ->
    let p,q = g2 0 in
    x.(i-$1) <- p; y.(i-$1) <- q;
  );
  let a,b = make (i32 n) 0L, make (i32 n) 0L in
  let m = ref IMap.empty in
  repi 1 (i32 n) (fun i ->
    let p,q = g2 0 in
    a.(i-$1) <- p; b.(i-$1) <- q;
    m := IMap.add (p,q) (i-$1) !m;
  );
  repi 1 (i32 n) (fun i ->
    let a,b = a.(i-$1),b.(i-$1) in
    let p,q = x.(0) + a, y.(0) + b in
    let used = make (i32 n) false in
    let f = ref true in
    repi 1 (i32 n) (fun i ->
      let x,y = x.(i-$1),y.(i-$1) in
      let a0,b0 = p-x, q-y in
      try
        let j = IMap.find (a0,b0) !m in
        if used.(j) then raise Not_found
        else (
          used.(j) <- true;
        )
      with _ -> (
        f := false;
      )
    );
    if !f then (
      printf "%Ld %Ld\n" p q; exit 0
    )
  )


Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains $$$26$$$ buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning. To check which buttons need replacement, Polycarp pressed some buttons in sequence, and a string $$$s$$$ appeared on the screen. When Polycarp presses a button with character $$$c$$$, one of the following events happened:  if the button was working correctly, a character $$$c$$$ appeared at the end of the string Polycarp was typing;  if the button was malfunctioning, two characters $$$c$$$ appeared at the end of the string. For example, suppose the buttons corresponding to characters a and c are working correctly, and the button corresponding to b is malfunctioning. If Polycarp presses the buttons in the order a, b, a, c, a, b, a, then the string he is typing changes as follows: a $$$\rightarrow$$$ abb $$$\rightarrow$$$ abba $$$\rightarrow$$$ abbac $$$\rightarrow$$$ abbaca $$$\rightarrow$$$ abbacabb $$$\rightarrow$$$ abbacabba.You are given a string $$$s$$$ which appeared on the screen after Polycarp pressed some buttons. Help Polycarp to determine which buttons are working correctly for sure (that is, this string could not appear on the screen if any of these buttons was malfunctioning).You may assume that the buttons don't start malfunctioning when Polycarp types the string: each button either works correctly throughout the whole process, or malfunctions throughout the whole process.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then the test cases follow. Each test case is represented by one line containing a string $$$s$$$ consisting of no less than $$$1$$$ and no more than $$$500$$$ lowercase Latin letters.

For each test case, print one line containing a string $$$res$$$. The string $$$res$$$ should contain all characters which correspond to buttons that work correctly in alphabetical order, without any separators or repetitions. If all buttons may malfunction, $$$res$$$ should be empty.

module S = Set.Make(struct type t = char let compare = compare end)

let _ =
  let n = int_of_string (input_line stdin) in
  for i = 1 to n do
    let s = input_line stdin in
    let n = String.length s in
    if n = 1 then
      Format.printf "%c@." s.[0]
    else
      let i = ref 0 in
      let l = ref S.empty in
      while !i <= (n - 2) do
        if s.[!i] = s.[!i+1] then
          i := !i +2
        else begin
          l := S.add s.[!i] !l;
          i := !i + 1
        end;
      done;
      if !i < n then
        l := S.add s.[!i] !l;
      let rec pp fmt = function
        | [] -> Format.printf "@."
        | x::l -> Format.printf "%c%a" x pp l
      in
      Format.printf "%a" pp (List.sort compare (S.elements !l));
  done

module S = Set.Make(struct type t = char let compare = compare end)

let to_set string =
  let s = ref S.empty in
  String.iter (fun c -> s := S.add c !s) string;
  !s

let _ =
  let n = int_of_string (input_line stdin) in
  for i = 1 to n do
    let s = input_line stdin in
    let n = String.length s in
    if n = 1 then
      Format.printf "%c@." s.[0]
    else
      let i = ref 0 in
      let l = ref [] in
      while !i <= (n - 2) do
        if s.[!i] = s.[!i+1] then
          i := !i +2
        else begin
          l := s.[!i]::!l;
          i := !i + 1
        end;
      done;
      if !i < n then
        l := s.[!i]::!l;
      let rec pp fmt = function
        | [] -> Format.printf "@."
        | x::l -> Format.printf "%c%a" x pp l
      in
      Format.printf "%a" pp !l;
  done


Two integers x and y are compatible, if the result of their bitwise "AND" equals zero, that is, a & b = 0. For example, numbers 90 (10110102) and 36 (1001002) are compatible, as 10110102 & 1001002 = 02, and numbers 3 (112) and 6 (1102) are not compatible, as 112 & 1102 = 102.You are given an array of integers a1, a2, ..., an. Your task is to find the following for each array element: is this element compatible with some other element from the given array? If the answer to this question is positive, then you also should find any suitable element.

The first line contains an integer n (1 ≤ n ≤ 106) — the number of elements in the given array. The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 4·106) — the elements of the given array. The numbers in the array can coincide.

Print n integers ansi. If ai isn't compatible with any other element of the given array a1, a2, ..., an, then ansi should be equal to -1. Otherwise ansi is any such number, that ai & ansi = 0, and also ansi occurs in the array a1, a2, ..., an.

let _ =
    let rdint =
        let l = ref 0 in
        let i = ref 0 in
        let s = String.create 65536 in
        let refill () =
            let n = input stdin s 0 65536 in
            i := 0;
            l := n in
        refill ();

        fun () ->
            let rec loop2 j k t f =
                let fin j t f =
                    let _ = i := j in
                    t * f in

                if j = k then (
                    let _ = refill () in
                    if !l > 0 then loop2 !i !l t f else fin j t f
                ) else if s.[j] >= '0' && s.[j] <= '9' then
                    loop2 (j + 1) k (t * 10 + Char.code s.[j] - 48) f
                else fin j t f in

            let rec loop1 j k =
                if j = k then (
                    let _ = refill () in
                    if !l > 0 then loop1 !i !l else 0
                ) else if s.[j] = '-' then loop2 (j + 1) k 0 (-1)
                else if s.[j] >= '0' && s.[j] <= '9' then loop2 (j + 1) k (Char.code s.[j] - 48) 1
                else loop1 (j + 1) k in
            loop1 !i !l
    in
    let main () =
        let n = rdint () in
        let bit = Array.create 4194303 (-1) in
        let arr = Array.init n (fun _ -> let k = rdint () in bit.(k) <- k; k) in
        Array.iteri (fun s v ->
            if v >= 0 then
                for i = 0 to 21 do
                    if (1 lsl i) land s == 0 then
                        let q = s lor (1 lsl i) in
                        if q < 4194303 then bit.(q) <- v
                done) bit;
        Array.iteri (fun i v ->
            let t = (lnot v) land 0x3FFFFF in
            Printf.printf "%s%d" (if i > 0 then " " else "") bit.(t)) arr;
        print_newline ()
    in
    main ()


As meticulous Gerald sets the table, Alexander finished another post on Codeforces and begins to respond to New Year greetings from friends. Alexander has n friends, and each of them sends to Alexander exactly one e-card. Let us number his friends by numbers from 1 to n in the order in which they send the cards. Let's introduce the same numbering for the cards, that is, according to the numbering the i-th friend sent to Alexander a card number i.Alexander also sends cards to friends, but he doesn't look for the new cards on the Net. He simply uses the cards previously sent to him (sometimes, however, he does need to add some crucial details). Initially Alexander doesn't have any cards. Alexander always follows the two rules:  He will never send to a firend a card that this friend has sent to him.  Among the other cards available to him at the moment, Alexander always chooses one that Alexander himself likes most. Alexander plans to send to each friend exactly one card. Of course, Alexander can send the same card multiple times.Alexander and each his friend has the list of preferences, which is a permutation of integers from 1 to n. The first number in the list is the number of the favorite card, the second number shows the second favorite, and so on, the last number shows the least favorite card.Your task is to find a schedule of sending cards for Alexander. Determine at which moments of time Alexander must send cards to his friends, to please each of them as much as possible. In other words, so that as a result of applying two Alexander's rules, each friend receives the card that is preferred for him as much as possible.Note that Alexander doesn't choose freely what card to send, but he always strictly follows the two rules.

The first line contains an integer n (2 ≤ n ≤ 300) — the number of Alexander's friends, equal to the number of cards. Next n lines contain his friends' preference lists. Each list consists of n different integers from 1 to n. The last line contains Alexander's preference list in the same format.

Print n space-separated numbers: the i-th number should be the number of the friend, whose card Alexander receives right before he should send a card to the i-th friend. If there are several solutions, print any of them.

NoteIn the sample, the algorithm of actions Alexander and his friends perform is as follows:   Alexander receives card 1 from the first friend.  Alexander sends the card he has received (at the moment he only has one card, and therefore it is the most preferable for him) to friends with the numbers 2 and 3.  Alexander receives card 2 from the second friend, now he has two cards — 1 and 2.  Alexander sends a card to the first friend. Despite the fact that Alexander likes card 1 more, he sends card 2 as he cannot send a friend the card sent by that very friend.  Alexander receives card 3 from the third friend.  Alexander receives card 4 from the fourth friend.  Among the cards Alexander has number 3 is his favorite and he sends it to the fourth friend. Note that Alexander can send cards to multiple friends at a time (in this case the second and the third one). Alexander can send card 3 to the fourth friend after he receives the third card or after he receives the fourth card (both variants are correct).

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make_matrix n n 0 in
  let b = Array.make n 0 in
  let _ =
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	a.(i).(j) <- Scanf.bscanf sb "%d " (fun s -> s) - 1
      done
    done;
    for i = 0 to n - 1 do
      b.(i) <- Scanf.bscanf sb "%d " (fun s -> s) - 1
    done;
  in
  let c = Array.make_matrix n n (-1) in
    for i = 0 to n - 1 do
      let c1 = ref (-1) in
      let c2 = ref (-1) in
	for j = 0 to n - 1 do
	  if b.(j) <= i then (
	    if !c1 < 0
	    then c1 := b.(j)
	    else if !c2 < 0
	    then c2 := b.(j)
	  )
	done;
	for j = 0 to n - 1 do
	  if j <> !c1
	  then c.(j).(!c1) <- i
	  else if !c2 >= 0
	  then c.(j).(!c2) <- i
	done
    done;
    let res = Array.make n (-1) in
      (*for i = 0 to n - 1 do
	for j = 0 to n - 1 do
	  Printf.printf "%d " (c.(i).(j) + 1)
	done;
	Printf.printf "\n"
      done;*)
      for i = 0 to n - 1 do
	for j = 0 to n - 1 do
	  if res.(i) < 0 && c.(i).(a.(i).(j)) >= 0
	  then res.(i) <- c.(i).(a.(i).(j))
	done
      done;
      for i = 0 to n - 1 do
	Printf.printf "%d " (res.(i) + 1)
      done;
      Printf.printf "\n"


A sequence of square brackets is regular if by inserting symbols "+" and "1" into it, you can get a regular mathematical expression from it. For example, sequences "[[]][]", "[]" and "[[][[]]]" — are regular, at the same time "][", "[[]" and "[[]]][" — are irregular. Draw the given sequence using a minimalistic pseudographics in the strip of the lowest possible height — use symbols '+', '-' and '|'. For example, the sequence "[[][]][]" should be represented as: +-        -++- -+    |+- -++- -+||   |||   ||   |||   ||+- -++- -+||   |+-        -++- -+Each bracket should be represented with the hepl of one or more symbols '|' (the vertical part) and symbols '+' and '-' as on the example which is given above.Brackets should be drawn without spaces one by one, only dividing pairs of consecutive pairwise brackets with a single-space bar (so that the two brackets do not visually merge into one symbol). The image should have the minimum possible height. The enclosed bracket is always smaller than the surrounding bracket, but each bracket separately strives to maximize the height of the image. So the pair of final brackets in the example above occupies the entire height of the image.Study carefully the examples below, they adequately explain the condition of the problem. Pay attention that in this problem the answer (the image) is unique.

The first line contains an even integer n (2 ≤ n ≤ 100) — the length of the sequence of brackets. The second line contains the sequence of brackets — these are n symbols "[" and "]". It is guaranteed that the given sequence of brackets is regular.

Print the drawn bracket sequence in the format which is given in the condition. Don't print extra (unnecessary) spaces.

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

let read_int _ = Scanf.scanf " %d " (fun n -> n)
let read_word _ = Scanf.scanf " %s " (fun n -> n)

let plus mx ht =
  String.init (2*mx+1)
    (fun i ->
       let d = abs (mx-i) in
       if d<ht then
         '|'
       else if d=ht then '+'
       else ' ')

let minus mx ht =
  String.init (2*mx+1)
    (fun i ->
       let d = abs (mx-i) in
       if d=ht then '-'
       else ' ')

let plusminus mx ht =
  String.init (2*mx+1)
    (fun i ->
       let d = abs (mx-i) in
       if d<ht then
         '|'
       else if d=ht then '+'
       else if d=ht+1 then '-'
       else ' ')

let blank mx = String.make (2*mx+1) ' '

let convert s n i mx d =
  let g j = (String.get s j) = '[' in
  let d = if (g i) then d else (d+1) in
  let base =
    if (i>0 && g (i-1) && g i) || (i<n-1 && not(g (i+1)) && not(g i)) then
      plusminus mx d
    else
      plus mx d in
  if g i && not (g (i+1)) then
    [minus mx d; blank mx; minus mx d; base]
  else
    [base]

let () =
  let n = read_int () in
  let s = read_word () in
  let rec iter i cur acc =
    if i<n then
      let cur = (if (String.get s i)='[' then cur+1 else cur-1) in
      iter (i+1) cur (max cur acc)
    else
      acc in
  let dep = iter 0 0 0 in
  let rec iter i d acc =
    if i<n then
      let c = String.get s i in
      iter (i+1) (d + (if c='[' then -1 else 1)) (List.append (convert s n i dep d) acc)
    else
      acc in
  let ls = iter 0 dep [] in
  let ls = List.rev ls in
  let n = String.length (List.hd ls) in
  let print_row i =
    let rec iter l =
      match l with
      |[] -> ()
      |s::ss -> (print_char (String.get s i); iter ss) in
    iter ls in
  let rec iter i =
    if i=n then ()
    else (print_row i; print_newline (); iter (i+1)) in
  iter 0


Twilight Sparkle was playing Ludo with her friends Rainbow Dash, Apple Jack and Flutter Shy. But she kept losing. Having returned to the castle, Twilight Sparkle became interested in the dice that were used in the game.The dice has m faces: the first face of the dice contains a dot, the second one contains two dots, and so on, the m-th face contains m dots. Twilight Sparkle is sure that when the dice is tossed, each face appears with probability . Also she knows that each toss is independent from others. Help her to calculate the expected maximum number of dots she could get after tossing the dice n times.

A single line contains two integers m and n (1 ≤ m, n ≤ 105).

Output a single real number corresponding to the expected maximum. The answer will be considered correct if its relative or absolute error doesn't exceed 10  - 4.

NoteConsider the third test example. If you've made two tosses:  You can get 1 in the first toss, and 2 in the second. Maximum equals to 2.  You can get 1 in the first toss, and 1 in the second. Maximum equals to 1.  You can get 2 in the first toss, and 1 in the second. Maximum equals to 2.  You can get 2 in the first toss, and 2 in the second. Maximum equals to 2. The probability of each outcome is 0.25, that is expectation equals to: You can read about expectation using the following link: http://en.wikipedia.org/wiki/Expected_value

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

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

module Array = ArrayLabels ;;
module List  = ListLabels ;;

open Num ;;

let foi = float_of_int ;;

let rec pow x n =
  if n = 0 then 1.
  else if n mod 2 = 0 then
    let p2 = pow x (n / 2) in
    p2 *. p2
  else
    x *. pow x (n - 1)
;;

let () =
  sf "%d %d "(fun m n ->
    let s = ref (foi m) in
    for i = m - 1 downto 1 do
      s := !s -. pow (foi i /. foi m) n;
    done;
    pf "%f\n" !s)
;;


You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.

The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge. It is possible that the graph has loops and multiple edges between pair of vertices.

Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.

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

module PSet = struct
  type 'k set =
    | Empty
    | Node of 'k set * 'k * 'k set * int

  type 'k t =
    {
      cmp : 'k -> 'k -> int;
      set : 'k set;
    }

  let height = function
    | Node (_, _, _, h) -> h
    | Empty -> 0

  let make l k r = Node (l, k, r, max (height l) (height r) + 1)

  let bal l k r =
    let hl = height l in
    let hr = height r in
    if hl > hr + 2 then
      match l with
      | Node (ll, lk, lr, _) ->
          if height ll >= height lr then make ll lk (make lr k r)
          else
            (match lr with
            | Node (lrl, lrk, lrr, _) ->
                make (make ll lk lrl) lrk (make lrr k r)
            | Empty -> assert false)
      | Empty -> assert false
    else if hr > hl + 2 then
      match r with
      | Node (rl, rk, rr, _) ->
          if height rr >= height rl then make (make l k rl) rk rr
          else
            (match rl with
            | Node (rll, rlk, rlr, _) ->
                make (make l k rll) rlk (make rlr rk rr)
            | Empty -> assert false)
      | Empty -> assert false
    else Node (l, k, r, max hl hr + 1)

  let rec min_elt = function
    | Node (Empty, k, _, _) -> k
    | Node (l, _, _, _) -> min_elt l
    | Empty -> raise Not_found

  let rec remove_min_elt = function
    | Node (Empty, _, r, _) -> r
    | Node (l, k, r, _) -> bal (remove_min_elt l) k r
    | Empty -> invalid_arg "PSet.remove_min_elt"

  let merge t1 t2 =
    match t1, t2 with
    | Empty, _ -> t2
    | _, Empty -> t1
    | _ ->
        let k = min_elt t2 in
        bal t1 k (remove_min_elt t2)

  let create cmp = { cmp = cmp; set = Empty }
  let empty = { cmp = compare; set = Empty }

  let is_empty x =
    x.set = Empty

  let rec add_one cmp x = function
    | Node (l, k, r, h) ->
        let c = cmp x k in
        if c = 0 then Node (l, x, r, h)
        else if c < 0 then
          let nl = add_one cmp x l in
          bal nl k r
        else
          let nr = add_one cmp x r in
          bal l k nr
    | Empty -> Node (Empty, x, Empty, 1)

  let add x { cmp = cmp; set = set } =
    { cmp = cmp; set = add_one cmp x set }

  let rec join cmp l v r =
    match (l, r) with
      (Empty, _) -> add_one cmp v r
    | (_, Empty) -> add_one cmp v l
    | (Node(ll, lv, lr, lh), Node(rl, rv, rr, rh)) ->
        if lh > rh + 2 then bal ll lv (join cmp lr v r) else
        if rh > lh + 2 then bal (join cmp l v rl) rv rr else
        make l v r

  let split x { cmp = cmp; set = set } =
    let rec loop x = function
        Empty ->
          (Empty, false, Empty)
      | Node (l, v, r, _) ->
          let c = cmp x v in
          if c = 0 then (l, true, r)
          else if c < 0 then
            let (ll, pres, rl) = loop x l in (ll, pres, join cmp rl v r)
          else
            let (lr, pres, rr) = loop x r in (join cmp l v lr, pres, rr)
    in
    let setl, pres, setr = loop x set in
    { cmp = cmp; set = setl }, pres, { cmp = cmp; set = setr }

  let remove x { cmp = cmp; set = set } =
    let rec loop = function
      | Node (l, k, r, _) ->
          let c = cmp x k in
          if c = 0 then merge l r else
          if c < 0 then bal (loop l) k r else bal l k (loop r)
      | Empty -> Empty in
    { cmp = cmp; set = loop set }

  let mem x { cmp = cmp; set = set } =
    let rec loop = function
      | Node (l, k, r, _) ->
          let c = cmp x k in
          c = 0 || loop (if c < 0 then l else r)
      | Empty -> false in
    loop set

  let exists = mem

  let iter f { set = set } =
    let rec loop = function
      | Empty -> ()
      | Node (l, k, r, _) -> loop l; f k; loop r in
    loop set

  let fold f { cmp = cmp; set = set } acc =
    let rec loop acc = function
      | Empty -> acc
      | Node (l, k, r, _) ->
            loop (f k (loop acc l)) r in
    loop acc set

  let elements { set = set } =
    let rec loop acc = function
        Empty -> acc
      | Node(l, k, r, _) -> loop (k :: loop acc r) l in
    loop [] set
end;;

module type GRAPH_LABELS =
  sig
    type label
  end;;

(* Typ modułu implementującego grafy o wierzchołkach numerowanych od 0 do n-1. *)
module type GRAPH =
  sig
    (* Etykiety krawędzi. *)
    type label

    (* Typ grafów o wierzchołkach typu 'a. *)
    type graph

    (* Pusty graf. *)
    val init : int -> graph

    (* Rozmiar grafu *)
    val size : graph -> int

    (* Dodanie krawędzi skierowanej łączącej dwa wierzchołki. *)
    val insert_directed_edge : graph -> int -> int -> label -> unit

    (* Dodanie krawędzi nieskierowanej (dwukierunkowej) łączącej dwa wierzchołki. *)
    val insert_edge : graph -> int -> int -> label -> unit

    (* Lista incydencji danego wierzchołka. *)
    val neighbours :  graph -> int -> (int*label) list
  end;;

module Graph = functor (L : GRAPH_LABELS) ->
(struct
  (* Etykiety krawędzi. *)
  type label = L.label

  (* Typ grafów - tablica list sąsiedztwa. *)
  type graph = {n : int; e : (int*label) list array}

  (* Pusty graf. *)
  let init s = {n = s; e = Array.make s []}

  (* Rozmiar grafu. *)
  let size g = g.n

  (* Dodanie krawędzi skierowanej łączącej dwa wierzchołki. *)
  let insert_directed_edge g x y l =
    assert ((x<>y)  && (x >= 0) && (x < size g) && (y >= 0) && (y < size g));
    g.e.(x) <- (y,l)::g.e.(x)

  (* Dodanie krawędzi łączącej dwa (istniejące) wierzchołki. *)
  let insert_edge g x y l =
    insert_directed_edge g x y l;
    insert_directed_edge g y x l

  (* Lista incydencji danego wierzchołka. *)
  let neighbours g x =
    g.e.(x)
end : GRAPH with type label = L.label);;

module IntLabel =
  struct
    type label = int
  end;;

module G = Graph(IntLabel);;

open G;;
open PSet;;
let n = scan_int() and m = scan_int();;
let g = G.init n;;

let zbior = ref empty;;

for i = 1 to m do
  let a = scan_int() - 1 and b = scan_int() - 1 and c = scan_int() in
  G.insert_edge g a b c;
done;;

let dijkstra g = (*wierzcholki numerujemy od 0*)
  zbior := add (Int64.zero, 0) !zbior;
  let dis = Array.make n Int64.max_int and pred = Array.make n (-1) in
  while is_empty !zbior = false do
    let (odl, u) = min_elt (!zbior).set in
    zbior := {cmp = (!zbior).cmp; set = remove_min_elt (!zbior).set};
    List.iter (fun (v, w) ->
      let waga = Int64.add odl (Int64.of_int(w)) in
      if waga < dis.(v) then begin
        dis.(v) <- waga;
        pred.(v) <- u;
        zbior := add (waga, v) !zbior;
      end;
    ) (neighbours g u);
  done;
  pred;
;;

let wyn = dijkstra g;;

if wyn.(n - 1) = -1 then begin
  print_string("-1");
  exit 0;
end;;

let odp = ref [];;
let rec petla x =
  odp := (x + 1) :: !odp;
  if x <> 0 then petla (wyn.(x));;
petla (n - 1);

List.iter (fun x -> print_int (x); psp()) !odp;;


Peter Parker wants to play a game with Dr. Octopus. The game is about cycles. Cycle is a sequence of vertices, such that first one is connected with the second, second is connected with third and so on, while the last one is connected with the first one again. Cycle may consist of a single isolated vertex.Initially there are k cycles, i-th of them consisting of exactly vi vertices. Players play alternatively. Peter goes first. On each turn a player must choose a cycle with at least 2 vertices (for example, x vertices) among all available cycles and replace it by two cycles with p and x - p vertices where 1 ≤ p < x is chosen by the player. The player who cannot make a move loses the game (and his life!).Peter wants to test some configurations of initial cycle sets before he actually plays with Dr. Octopus. Initially he has an empty set. In the i-th test he adds a cycle with ai vertices to the set (this is actually a multiset because it can contain two or more identical cycles). After each test, Peter wants to know that if the players begin the game with the current set of cycles, who wins? Peter is pretty good at math, but now he asks you to help.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of tests Peter is about to make. The second line contains n space separated integers a1, a2, ..., an (1 ≤ ai ≤ 109), i-th of them stands for the number of vertices in the cycle added before the i-th test.

Print the result of all tests in order they are performed. Print 1 if the player who moves first wins or 2 otherwise.

NoteIn the first sample test:In Peter's first test, there's only one cycle with 1 vertex. First player cannot make a move and loses.In his second test, there's one cycle with 1 vertex and one with 2. No one can make a move on the cycle with 1 vertex. First player can replace the second cycle with two cycles of 1 vertex and second player can't make any move and loses.In his third test, cycles have 1, 2 and 3 vertices. Like last test, no one can make a move on the first cycle. First player can replace the third cycle with one cycle with size 1 and one with size 2. Now cycles have 1, 1, 2, 2 vertices. Second player's only move is to replace a cycle of size 2 with 2 cycles of size 1. And cycles are 1, 1, 1, 1, 2. First player replaces the last cycle with 2 cycles with size 1 and wins.In the second sample test:Having cycles of size 1 is like not having them (because no one can make a move on them). In Peter's third test: There a cycle of size 5 (others don't matter). First player has two options: replace it with cycles of sizes 1 and 4 or 2 and 3.  If he replaces it with cycles of sizes 1 and 4: Only second cycle matters. Second player will replace it with 2 cycles of sizes 2. First player's only option to replace one of them with two cycles of size 1. Second player does the same thing with the other cycle. First player can't make any move and loses.  If he replaces it with cycles of sizes 2 and 3: Second player will replace the cycle of size 3 with two of sizes 1 and 2. Now only cycles with more than one vertex are two cycles of size 2. As shown in previous case, with 2 cycles of size 2 second player wins. So, either way first player loses.

open Printf
open Scanf

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

  let rec loop ac i = if i<n then
      let ac = (a.(i)-1) lxor ac in
      if ac land 1 = 0 then printf "2\n" else printf "1\n";
      loop ac (i+1)
  in

  loop 0 0


New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of n - 1 positive integers a1, a2, ..., an - 1. For every integer i where 1 ≤ i ≤ n - 1 the condition 1 ≤ ai ≤ n - i holds. Next, he made n - 1 portals, numbered by integers from 1 to n - 1. The i-th (1 ≤ i ≤ n - 1) portal connects cell i and cell (i + ai), and one can travel from cell i to cell (i + ai) using the i-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (i + ai) to cell i using the i-th portal. It is easy to see that because of condition 1 ≤ ai ≤ n - i one can't leave the Line World using portals.Currently, I am standing at cell 1, and I want to go to cell t. However, I don't know whether it is possible to go there. Please determine whether I can go to cell t by only using the construted transportation system.

The first line contains two space-separated integers n (3 ≤ n ≤ 3 × 104) and t (2 ≤ t ≤ n) — the number of cells, and the index of the cell which I want to go to. The second line contains n - 1 space-separated integers a1, a2, ..., an - 1 (1 ≤ ai ≤ n - i). It is guaranteed, that using the given transportation system, one cannot leave the Line World.

If I can go to cell t using the transportation system, print "YES". Otherwise, print "NO".

NoteIn the first sample, the visited cells are: 1, 2, 4; so we can successfully visit the cell 4.In the second sample, the possible cells to visit are: 1, 2, 4, 6, 7, 8; so we can't visit the cell 5, which we want to visit.

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

let input () =
    let total = (read ()) - 1 in
    let destination = (read ()) - 1 in
    let portals = Array.init total (fun n -> read ()) in
    (total, destination, portals)

let solve (total, destination, portals) =
    let rec loop i =
        if i < total
        then
            let portal_in = portals.(i) in
            let portal_out = portal_in + i in
            if portal_out < destination
            then
                loop (portal_out)
            else
                if portal_out = destination
                then
                    "YES"
                else
                    "NO"
        else
            failwith "Corrupted input"
    in loop 0

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

let () = Scanf.scanf "%d %d\n" (fun n t ->
  let p = Array.init (n - 1) (fun _ ->
    Scanf.scanf "%d%_c" (fun x -> x))
  in
  let rec f i =
    if i > t then false
    else if i = t then true
    else f (i + p.(i - 1))
  in
  print_endline (if f 1 then "YES" else "NO")
)

let words line = Str.split (Str.regexp " ") line;;

let transport curr arr = curr + arr.(curr - 1);;

let rec step arr start goal =
  if start = goal then
    "YES"
  else if goal < start then
    "NO"
  else
    step arr (transport start arr) goal
;;

let () =
  let nk = words (read_line ()) in
  let goal = int_of_string (List.nth nk 1) in
  let line = words (read_line ()) in
  let arr = Array.of_list (List.map int_of_string line)
  in
  Printf.printf "%s\n"
                (step arr 1 goal)
;;

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let t = read_int () in
  let a = Array.init n (fun i -> if i=0 then 0 else read_int()) in

  let rec scan c =
    if c = t then true else if c = n then false else scan (c + a.(c))
  in

  if scan 1 then printf "YES\n" else printf "NO\n"

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

let solve (n, m) =
    let rec loop i =
        if i < n
        then
            let portal_in = Scanf.scanf "%d " (fun p -> p) in
            let portal_out = portal_in + i in
            if portal_out < m
            then
                loop (i + 1)
            else
                if portal_out = m
                then
                    "YES"
                else
                    "NO"
        else
            failwith "Corrupted input"
    in loop 1

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


Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an arbitrary sequence of these operations with arbitrary constants from 0 to 1023. When the program is run, all operations are applied (in the given order) to the argument and in the end the result integer is returned.Petya wrote a program in this language, but it turned out to be too long. Write a program in CALPAS that does the same thing as the Petya's program, and consists of no more than 5 lines. Your program should return the same integer as Petya's program for all arguments from 0 to 1023.

The first line contains an integer n (1 ≤ n ≤ 5·105) — the number of lines. Next n lines contain commands. A command consists of a character that represents the operation ("&", "|" or "^" for AND, OR or XOR respectively), and the constant xi 0 ≤ xi ≤ 1023.

Output an integer k (0 ≤ k ≤ 5) — the length of your program. Next k lines must contain commands in the same format as in the input.

NoteYou can read about bitwise operations in https://en.wikipedia.org/wiki/Bitwise_operation.Second sample:Let x be an input of the Petya's program. It's output is ((x&1)&3)&5 = x&(1&3&5) = x&1. So these two programs always give the same outputs.

open Printf
open Scanf

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

let () =
  let n = read_int () in
  let prog = Array.init n (fun _ ->
    let op = (read_string ()).[0] in
    let k = read_int () in
    (op,k)
  ) in

  let execute k =
    let rec loop i ac = if i=n then ac else (
      let ac = match prog.(i) with
	| ('^', c) -> ac lxor c
	| ('&', c) -> ac land c
	| ('|', c) -> ac lor c
	| _ -> failwith "bad program"
      in
      loop (i+1) ac
    )
    in
    loop 0 k
  in

  let does_to_bit b =
    let b0 = ((execute (0 lsl b)) lsr b) land 1 in
    let b1 = ((execute (1 lsl b)) lsr b) land 1 in
    (b0,b1)
  in

  let xor_part = ref 0 in
  let or_part = ref 0 in
  let and_part = ref 1023 in

  for b=0 to 9 do
    let x = 1 lsl b in
    match does_to_bit b with
      | (0,0) -> and_part := !and_part land (lnot x)
      | (0,1) -> ()
      | (1,0) -> xor_part := !xor_part lor x
      | (1,1) -> or_part := !or_part lor x
      | _ -> failwith "bad bits"
  done;

  printf "3\n";
  printf "^ %d\n" !xor_part;
  printf "| %d\n" !or_part;
  printf "& %d\n" !and_part


One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.Vitaly sees a building of n floors and 2·m windows on each floor. On each floor there are m flats numbered from 1 to m, and two consecutive windows correspond to each flat. If we number the windows from 1 to 2·m from left to right, then the j-th flat of the i-th floor has windows 2·j - 1 and 2·j in the corresponding row of windows (as usual, floors are enumerated from the bottom). Vitaly thinks that people in the flat aren't sleeping at that moment if at least one of the windows corresponding to this flat has lights on.Given the information about the windows of the given house, your task is to calculate the number of flats where, according to Vitaly, people aren't sleeping.

The first line of the input contains two integers n and m (1 ≤ n, m ≤ 100) — the number of floors in the house and the number of flats on each floor respectively. Next n lines describe the floors from top to bottom and contain 2·m characters each. If the i-th window of the given floor has lights on, then the i-th character of this line is '1', otherwise it is '0'.

Print a single integer — the number of flats that have lights on in at least one window, that is, the flats where, according to Vitaly, people aren't sleeping.

NoteIn the first test case the house has two floors, two flats on each floor. That is, in total there are 4 flats. The light isn't on only on the second floor in the left flat. That is, in both rooms of the flat the light is off.In the second test case the house has one floor and the first floor has three flats. The light is on in the leftmost flat (in both windows) and in the middle flat (in one window). In the right flat the light is off.

let [n; m]= List.map (int_of_string) (Str.split (Str.regexp " ") (read_line ())) and ans = ref 0;;
for i= 1 to n do
	let s = List.map (int_of_string) (Str.split (Str.regexp " ") (read_line ())) in
		for j= 1 to m do
			if (List.nth s (2 * j - 1) = 1) || (List.nth s (2 * j - 2) = 1) then
				ans:= !ans + 1;
		done
done;;
print_int !ans

let read_int() = Scanf.scanf "%d " (fun x->x) ;;
let rec f = function 0 -> 0 | c -> ( read_int() lor read_int() ) + f (c-1) in print_int @@ f ( read_int() * read_int() )

input_line stdin

let eval a b =
    if a + b == 0 then 0 else 1 ;;

    let rec solve acc =
        let i = Scanf.scanf "%d %d " eval in
            try solve (acc + i) with _ -> acc + i ;;

let ans = solve 0 ;;

Printf.printf "%d\n" ans ;;

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 n = read_int () in
  let m = read_int () in

  let awake a b = if a+b > 0 then 1 else 0 in
  let answer = sum 1 n (fun i ->
    sum 1 m (fun j ->
      let a = read_int() in
      let b = read_int() in
      awake a b
    )
  ) in

  printf "%d\n" answer


Polycarpus has n friends in Tarasov city. Polycarpus knows phone numbers of all his friends: they are strings s1, s2, ..., sn. All these strings consist only of digits and have the same length. Once Polycarpus needed to figure out Tarasov city phone code. He assumed that the phone code of the city is the longest common prefix of all phone numbers of his friends. In other words, it is the longest string c which is a prefix (the beginning) of each si for all i (1 ≤ i ≤ n). Help Polycarpus determine the length of the city phone code.

The first line of the input contains an integer n (2 ≤ n ≤ 3·104) — the number of Polycarpus's friends. The following n lines contain strings s1, s2, ..., sn — the phone numbers of Polycarpus's friends. It is guaranteed that all strings consist only of digits and have the same length from 1 to 20, inclusive. It is also guaranteed that all strings are different.

Print the number of digits in the city phone code.

NoteA prefix of string t is a string that is obtained by deleting zero or more digits from the end of string t. For example, string "00209" has 6 prefixes: "" (an empty prefix), "0", "00", "002", "0020", "00209".In the first sample the city phone code is string "00".In the second sample the city phone code is an empty string.In the third sample the city phone code is string "770123456789".

open Array;;
open String;;
let (|>) x f = f x
let identity = fun x -> x

let flip f y x = f x y

let readStrLn _ =
  try Some (Scanf.scanf "%s\n" identity)
  with _ -> None
let readIntLn _ = Scanf.scanf "%d\n" identity

let foldCont f a cont =
  let rec fold' a = match cont () with
      None -> a
    | Some x -> fold' (f a x)
  in fold' a

let _ = readIntLn ()
let temp = Scanf.scanf "%s\n" identity
let len = length temp;;
let f a b =
  let rec f' i = match b.[i] with
    c when c = temp.[i] ->  f' (i+1)
    | _ -> temp.[i] <- ' '; i
  in f' 0;;
(*let main () = *)
if len = 1 then (print_int 0)
else ( len |> flip (foldCont f) readStrLn |> print_int; ());;

let solve codes =
  let rec loop length =
    let num = String.get (List.hd codes) length in
    if List.for_all (fun str -> (String.get str length) = num) codes
    then loop (length+1)
    else length
  in
  loop 0

let rec input_strings n =
  if n <= 0 then []
  else (Scanf.scanf " %s" (fun x -> x)) :: (input_strings (n-1))

let _ =
  let codes = Scanf.scanf " %d" input_strings in
  Printf.printf "%d\n" (solve codes)

open Array;;
open String;;
let (|>) x f = f x
let identity = fun x -> x

let flip f y x = f x y

let readStrLn _ =
  try Some (Scanf.scanf "%s\n" identity)
  with _ -> None
let readIntLn _ = Scanf.scanf "%d\n" identity

let foldCont f a cont =
  let rec fold' a = match cont () with
      None -> a
    | Some x -> fold' (f a x)
  in fold' a

let _ = readIntLn ()
let temp = Scanf.scanf "%s\n" identity
let len = length temp ;;
let f a b =
  let rec f' i = match b.[i] with
    c when c = temp.[i] -> f' (i+1)
    | _ -> i
  in f' 0;;
(*let main () = *)
if len = 1 then (print_int 0)
else ( len |> flip (foldCont f) readStrLn |> print_int; ());;


When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfaction. But some dishes do not go well together and some dishes go very well together. Kefa set to himself k rules of eating food of the following type — if he eats dish x exactly before dish y (there should be no other dishes between x and y), then his satisfaction level raises by c. Of course, our parrot wants to get some maximal possible satisfaction from going to the restaurant. Help him in this hard task!

The first line of the input contains three space-separated numbers, n, m and k (1 ≤ m ≤ n ≤ 18, 0 ≤ k ≤ n * (n - 1)) — the number of dishes on the menu, the number of portions Kefa needs to eat to get full and the number of eating rules. The second line contains n space-separated numbers ai, (0 ≤ ai ≤ 109) — the satisfaction he gets from the i-th dish. Next k lines contain the rules. The i-th rule is described by the three numbers xi, yi and ci (1 ≤ xi, yi ≤ n, 0 ≤ ci ≤ 109). That means that if you eat dish xi right before dish yi, then the Kefa's satisfaction increases by ci. It is guaranteed that there are no such pairs of indexes i and j (1 ≤ i < j ≤ k), that xi = xj and yi = yj.

In the single line of the output print the maximum satisfaction that Kefa can get from going to the restaurant.

NoteIn the first sample it is best to first eat the second dish, then the first one. Then we get one unit of satisfaction for each dish and plus one more for the rule.In the second test the fitting sequences of choice are 4 2 1 or 2 1 4. In both cases we get satisfaction 7 for dishes and also, if we fulfill rule 1, we get an additional satisfaction 5.

let popcount n =
    let rec aux n acc =
        if n == 0
        then acc
        else aux (n lsr 1) (acc + (n land 1))
    in aux n 0

let (+) = Int64.add

let () = Scanf.scanf "%d %d %d\n" (fun n m k ->
    (* dp in current state and last eaten dish *)
    let dp = Array.make_matrix (1 lsl n) n (-1L) in
    (* read list of satisfactions *)
    let a = Array.init n (fun i -> Scanf.scanf "%Ld%_c" (fun x ->
        dp.(1 lsl i).(i) <- x;
        x))
    (* rules are mappings of (prev,next) -> c *)
    and rules = Array.make_matrix n n 0L
    (* the solution! *)
    and best = ref 0L
    in
    (* populate rules *)
    for i = 1 to k do
        Scanf.scanf "%d %d %Ld\n" (fun x y c ->
            rules.(x - 1).(y - 1) <- c)
    done;

    (* loop over all possible states *)
    for state = 1 to (1 lsl n) - 1 do
        (* loop over all possible last-taken dishes *)
        for last = 0 to n - 1 do
            (* are we done? *)
            if dp.(state).(last) != -1L then
                if popcount state == m
                then best := max !best dp.(state).(last)
                else
                    (* all next dishes *)
                    for next = 0 to n - 1 do
                        (* we haven't already eaten this *)
                        if state land (1 lsl next) == 0 then
                            dp.(state lor (1 lsl next)).(next) <- max dp.(state lor (1 lsl next)).(next)
                                                                     (dp.(state).(last) + a.(next) + rules.(last).(next))
                    done
        done
    done;

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

let popcount =
    let k1 = 0x55555555 in
    let k2 = 0x33333333 in
    let k3 = 0x0f0f0f0f in
    (fun x ->
      let x = x - (x lsr 1) land k1 in
      let x = ((x lsr 2) land k2) + (x land k2) in
      let x = (x + (x lsr 4)) land k3 in
      let x = x + x lsr 8 in
      (x + x lsr 16) land 0x3f
    )

let max (a : float) (b : float) : float = if a >= b then a else b

let () = Scanf.scanf "%d %d %d\n" (fun n m k ->
    (* dp in current state and last eaten dish *)
    let dp = Array.make_matrix (1 lsl n) n (-1.) in
    (* read list of satisfactions *)
    let a = Array.init n (fun i -> Scanf.scanf "%f%_c" (fun x ->
        dp.(1 lsl i).(i) <- x;
        x))
    (* rules are mappings of (prev,next) -> c *)
    and rules = Array.make_matrix n n 0.
    and best = ref 0.
    (* the solution! *)
    in
    (* populate rules *)
    for i = 1 to k do
        Scanf.scanf "%d %d %f\n" (fun x y c ->
            rules.(x - 1).(y - 1) <- c)
    done;

    (* loop over all possible states *)
    for state = 1 to (1 lsl n) - 1 do
        (* loop over all possible last-taken dishes *)
        for last = 0 to n - 1 do
            (* are we done? *)
            if dp.(state).(last) != -1. then
                if popcount state = m
                then best := max !best dp.(state).(last)
                else
                    (* all next dishes *)
                    for next = 0 to n - 1 do
                        (* we haven't already eaten this *)
                        if state land (1 lsl next) = 0 then
                            dp.(state lor (1 lsl next)).(next) <- max dp.(state lor (1 lsl next)).(next)
                                                                     (dp.(state).(last) +. a.(next) +. rules.(last).(next))
                    done
        done
    done;

    Printf.printf "%.0f\n" !best
)

let popcount n =
    let rec aux n acc =
        if n == 0
        then acc
        else aux (n lsr 1) (acc + (n land 1))
    in aux n 0

let () = Scanf.scanf "%d %d %d\n" (fun n m k ->
    (* dp in current state and last eaten dish *)
    let dp = Array.make_matrix (1 lsl n) n (-1) in
    (* read list of satisfactions *)
    let a = Array.init n (fun i -> Scanf.scanf "%d%_c" (fun x ->
        dp.(1 lsl i).(i) <- x;
        x))
    (* rules are mappings of (prev,next) -> c *)
    and rules = Array.make_matrix n n 0
    (* the solution! *)
    and best = ref 0
    in
    (* populate rules *)
    for i = 1 to k do
        Scanf.scanf "%d %d %d\n" (fun x y c ->
            rules.(x - 1).(y - 1) <- c)
    done;

    (* loop over all possible states *)
    for state = 1 to (1 lsl n) - 1 do
        (* loop over all possible last-taken dishes *)
        for last = 0 to n - 1 do
            (* are we done? *)
            if dp.(state).(last) != -1 then
                if popcount state == m
                then best := max !best dp.(state).(last)
                else
                    (* all next dishes *)
                    for next = 0 to n - 1 do
                        (* we haven't already eaten this *)
                        if state land (1 lsl next) == 0 then
                            dp.(state lor (1 lsl next)).(next) <-
                                max dp.(state lor (1 lsl next)).(next)
                                    (dp.(state).(last) + a.(next) + rules.(last).(next))
                    done
        done
    done;

    print_int !best;
    print_newline ()
)


So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation. Right now the situation in Berland is dismal — their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surrounded cities. At any moment all points of the flatland ring can begin to move quickly in the direction of the city — that's the strategy the flatlanders usually follow when they besiege cities.The berlanders are sure that they can repel the enemy's attack if they learn the exact time the attack starts. For that they need to construct a radar that would register any movement at the distance of at most r from it. Thus, we can install a radar at such point, that at least one point of the enemy ring will be in its detecting range (that is, at a distance of at most r). Then the radar can immediately inform about the enemy's attack. Due to the newest technologies, we can place a radar at any point without any problems. But the problem is that the berlanders have the time to make only one radar. Besides, the larger the detection radius (r) is, the more the radar costs.That's why Vasya's task (that is, your task) is to find the minimum possible detection radius for the radar. In other words, your task is to find the minimum radius r (r ≥ 0) such, that a radar with radius r can be installed at some point and it can register the start of the movements of both flatland rings from that point. In this problem you can consider the cities as material points, the attacking enemy rings - as circles with centers in the cities, the radar's detection range — as a disk (including the border) with the center at the point where the radar is placed.

The input files consist of two lines. Each line represents the city and the flatland ring that surrounds it as three space-separated integers xi, yi, ri (|xi|, |yi| ≤ 104; 1 ≤ ri ≤ 104) — the city's coordinates and the distance from the city to the flatlanders, correspondingly. It is guaranteed that the cities are located at different points.

Print a single real number — the minimum detection radius of the described radar. The answer is considered correct if the absolute or relative error does not exceed 10 - 6.

NoteThe figure below shows the answer to the first sample. In this sample the best decision is to put the radar at point with coordinates (2, 0).   The figure below shows the answer for the second sample. In this sample the best decision is to put the radar at point with coordinates (0, 0).

let _ =
    let main () =
        let tri a b c = a, b, c in
        let x1, y1, r1 = Scanf.scanf " %d %d %d" tri in
        let x2, y2, r2 = Scanf.scanf " %d %d %d" tri in
        let d2 =
            let sq x = x * x in
            let dd = sqrt (float (sq (x2 - x1) + sq (y2 - y1))) in
            let r = (dd -. float (r1 + r2)) /. 2. in
            if r > 0. then r else max ((float (abs (r1 - r2)) -. dd) /. 2.) 0.
        in
        Printf.printf "%.15f\n" d2
    in
    main ()

let _ =
    let main () =
        let tri a b c = a, b, c in
        let x1, y1, r1 = Scanf.scanf " %d %d %d" tri in
        let x2, y2, r2 = Scanf.scanf " %d %d %d" tri in
        let d2 =
            let sq x = x * x in
            let dd = sqrt (float (sq (x2 - x1) + sq (y2 - y1))) in
            let r = (dd -. float (r1 + r2)) /. 2. in
            if r > 0. then r else (float (abs (r1 - r2)) -. dd) /. 2.
        in
        Printf.printf "%.15f\n" d2
    in
    main ()

let _ =
    let main () =
        let tri a b c = a, b, c in
        let x1, y1, r1 = Scanf.scanf " %d %d %d" tri in
        let x2, y2, r2 = Scanf.scanf " %d %d %d" tri in
        let d2 =
            let sq x = x * x in
            (sqrt (float (sq (x2 - x1) + sq (y2 - y1))) -. float (r1 + r2)) /. 2.
        in
        Printf.printf "%.15f\n" d2
    in
    main ()


Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd.

The only line contains odd integer n (1 ≤ n ≤ 49).

Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main diagonals should be odd.

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let mmod x =
    let r = x mod n in
      if r >= 0
      then r
      else r + n
  in
  let a = Array.make_matrix n n 0 in
  let x = ref (n / 2) in
  let y = ref 0 in
  let _ =
    for i = 1 to n * n do
      if a.(!y).(!x) > 0 then (
	x := mmod (!x - 1);
	y := mmod (!y + 2);
      );
      a.(!y).(!x) <- i;
      x := mmod (!x + 1);
      y := mmod (!y - 1);
    done;
  in
    for i = 0 to n - 1 do
      for j = 0 to n - 1 do
	Printf.printf "%d " a.(i).(j)
      done;
      Printf.printf "\n"
    done


Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers $$$n$$$ pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy.The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the $$$i$$$-th from the left sushi as $$$t_i$$$, where $$$t_i = 1$$$ means it is with tuna, and $$$t_i = 2$$$ means it is with eel.Arkady does not like tuna, Anna does not like eel. Arkady wants to choose such a continuous subsegment of sushi that it has equal number of sushi of each type and each half of the subsegment has only sushi of one type. For example, subsegment $$$[2, 2, 2, 1, 1, 1]$$$ is valid, but subsegment $$$[1, 2, 1, 2, 1, 2]$$$ is not, because both halves contain both types of sushi.Find the length of the longest continuous subsegment of sushi Arkady can buy.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100\,000$$$) — the number of pieces of sushi. The second line contains $$$n$$$ integers $$$t_1$$$, $$$t_2$$$, ..., $$$t_n$$$ ($$$t_i = 1$$$, denoting a sushi with tuna or $$$t_i = 2$$$, denoting a sushi with eel), representing the types of sushi from left to right. It is guaranteed that there is at least one piece of sushi of each type. Note that it means that there is at least one valid continuous segment.

Print a single integer — the maximum length of a valid continuous segment.

NoteIn the first example Arkady can choose the subsegment $$$[2, 2, 1, 1]$$$ or the subsegment $$$[1, 1, 2, 2]$$$ with length $$$4$$$.In the second example there is no way but to choose one of the subsegments $$$[2, 1]$$$ or $$$[1, 2]$$$ with length $$$2$$$.In the third example Arkady's best choice is the subsegment $$$[1, 1, 1, 2, 2, 2]$$$.

open Printf
open Scanf

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

let rec one_type_seg cur = function
  | x::(y::_ as rest) when x = y -> one_type_seg (cur+1) rest
  | _::rest -> (cur+1) :: one_type_seg 0 rest
  | [] -> []

let rec max_seg cur = function
  | a::(b::_ as rest) -> max_seg (max cur (2*min a b)) rest
  | _ -> cur

let () =
  let n = read_int () in
  let a = Array.(init n read_int |> to_list) in
  printf "%d\n" (one_type_seg 0 a |> max_seg 0)


Kate has a set $$$S$$$ of $$$n$$$ integers $$$\{1, \dots, n\} $$$. She thinks that imperfection of a subset $$$M \subseteq S$$$ is equal to the maximum of $$$gcd(a, b)$$$ over all pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are in $$$M$$$ and $$$a \neq b$$$. Kate is a very neat girl and for each $$$k \in \{2, \dots, n\}$$$ she wants to find a subset that has the smallest imperfection among all subsets in $$$S$$$ of size $$$k$$$. There can be more than one subset with the smallest imperfection and the same size, but you don't need to worry about it. Kate wants to find all the subsets herself, but she needs your help to find the smallest possible imperfection for each size $$$k$$$, will name it $$$I_k$$$. Please, help Kate to find $$$I_2$$$, $$$I_3$$$, ..., $$$I_n$$$.

The first and only line in the input consists of only one integer $$$n$$$ ($$$2\le n \le 5 \cdot 10^5$$$)  — the size of the given set $$$S$$$.

Output contains only one line that includes $$$n - 1$$$ integers: $$$I_2$$$, $$$I_3$$$, ..., $$$I_n$$$.

NoteFirst sample: answer is 1, because $$$gcd(1, 2) = 1$$$.Second sample: there are subsets of $$$S$$$ with sizes $$$2, 3$$$ with imperfection equal to 1. For example, $$$\{2,3\}$$$ and $$$\{1, 2, 3\}$$$.

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

let rec read_int_seq n =
  match n with
    0 -> []
  | _ -> (get_int ()) :: (read_int_seq (n-1))
;;

let rec print_list xs =
  match xs with
    [] -> print_endline ""
  | x :: [] -> (Printf.printf "%d\n" x)
  | x :: xs' -> (let _ = Printf.printf "%d " x in print_list xs')
;;

let rec range a b =
  if a > b then [] else
    a :: (range (a+1) b)
;;

let read_case () =
  let n = get_int () in n
;;

let rec min_div_from n k =
  if k*k > n then n else
    if n mod k = 0 then k else
      min_div_from n (k+1)
;;

let min_div n =
  min_div_from n 2
;;

let solve n =
  List.map (fun x -> x / (min_div x)) (range 2 n)
  |> (List.sort (-))
  |> print_list
;;

let n = read_case () in
    solve n
;;


After observing the results of Spy Syndrome, Yash realised the errors of his ways. He now believes that a super spy such as Siddhant can't use a cipher as basic and ancient as Caesar cipher. After many weeks of observation of Siddhant’s sentences, Yash determined a new cipher technique.For a given sentence, the cipher is processed as:   Convert all letters of the sentence to lowercase.  Reverse each of the words of the sentence individually.  Remove all the spaces in the sentence. For example, when this cipher is applied to the sentenceKira is childish and he hates losingthe resulting string isariksihsidlihcdnaehsetahgnisolNow Yash is given some ciphered string and a list of words. Help him to find out any original sentence composed using only words from the list. Note, that any of the given words could be used in the sentence multiple times.

The first line of the input contains a single integer n (1 ≤ n ≤ 10 000) — the length of the ciphered text. The second line consists of n lowercase English letters — the ciphered text t. The third line contains a single integer m (1 ≤ m ≤ 100 000) — the number of words which will be considered while deciphering the text. Each of the next m lines contains a non-empty word wi (|wi| ≤ 1 000) consisting of uppercase and lowercase English letters only. It's guaranteed that the total length of all words doesn't exceed 1 000 000.

Print one line — the original sentence. It is guaranteed that at least one solution exists. If there are multiple solutions, you may output any of those.

30
ariksihsidlihcdnaehsetahgnisol
10
Kira
hates
is
he
losing
death
childish
L
and
Note

12
iherehtolleh
5
HI
Ho
there
HeLLo
hello

Kira is childish and he hates losing
HI there HeLLo

NoteIn sample case 2 there may be multiple accepted outputs, "HI there HeLLo" and "HI there hello" you may output any of them.

exception End of int

type trie = E of bool | N of bool * trie array

let add w trie =
   let n = String.length w in
   let rec aux i = function
      | E(b) -> if i = n then E(true) else
                (let tab = Array.make 26 (E false) in
                   tab.(int_of_char w.[i] - 97) <- aux (i+1) (E false);
                   N(b,tab))
      | N(b,tab) -> if i = n then N(true,tab) else
                   (tab.(int_of_char w.[i] - 97) <- aux (i+1)
                                            (tab.(int_of_char w.[i] - 97));
                   N(b,tab))
   in ignore (aux 0 trie)

let main () =
   (let trie = N(false,Array.make 26 (E false)) in
   let hasht = Hashtbl.create 0 in
   let m,w = Scanf.scanf "%d %s" (fun i j -> i,j) in
   let n = Scanf.scanf " %d" (fun i -> i) in
      for i=1 to n do
         Scanf.scanf " %s" (fun s ->
            let s_low = String.lowercase s in
            let m = String.length s_low in
            let rev = String.init m (fun i -> s_low.[m-i-1]) in
               add rev trie;
               Hashtbl.add hasht rev s
                            );
      done;
   let tab = Array.make m (-1) in
   let rec aux i last = function
      |E false      -> ()
      |E true       -> if i = m
                       then raise (End(last))
                       else if tab.(i) = -1
                            then (tab.(i) <- last; aux i i trie)
      |N(false,tab) -> if i < m
                       then aux (i+1) last (tab.(int_of_char w.[i] - 97))
      |N(true,tab') -> (if i = m
                       then raise (End(last));
                       if i < m && tab.(i) = -1
                       then (tab.(i) <- last; aux i i trie);
                       if i < m
                       then aux (i+1) last (tab'.(int_of_char w.[i] - 97)))
   in
   let rec reconst beg en =
      let s = Hashtbl.find hasht (String.sub w beg (en-beg+1)) in
         if beg = 0
            then [s] else s::(reconst (tab.(beg)) (beg - 1))
   in
   try
      aux 0 0 trie; ""
   with End last -> String.concat " " (List.rev (reconst last (m-1))));;

print_string (main ())


Alice and Bob are playing chess on a huge chessboard with dimensions $$$n \times n$$$. Alice has a single piece left — a queen, located at $$$(a_x, a_y)$$$, while Bob has only the king standing at $$$(b_x, b_y)$$$. Alice thinks that as her queen is dominating the chessboard, victory is hers. But Bob has made a devious plan to seize the victory for himself — he needs to march his king to $$$(c_x, c_y)$$$ in order to claim the victory for himself. As Alice is distracted by her sense of superiority, she no longer moves any pieces around, and it is only Bob who makes any turns.Bob will win if he can move his king from $$$(b_x, b_y)$$$ to $$$(c_x, c_y)$$$ without ever getting in check. Remember that a king can move to any of the $$$8$$$ adjacent squares. A king is in check if it is on the same rank (i.e. row), file (i.e. column), or diagonal as the enemy queen. Find whether Bob can win or not.

The first line contains a single integer $$$n$$$ ($$$3 \leq n \leq 1000$$$) — the dimensions of the chessboard. The second line contains two integers $$$a_x$$$ and $$$a_y$$$ ($$$1 \leq a_x, a_y \leq n$$$) — the coordinates of Alice's queen. The third line contains two integers $$$b_x$$$ and $$$b_y$$$ ($$$1 \leq b_x, b_y \leq n$$$) — the coordinates of Bob's king. The fourth line contains two integers $$$c_x$$$ and $$$c_y$$$ ($$$1 \leq c_x, c_y \leq n$$$) — the coordinates of the location that Bob wants to get to. It is guaranteed that Bob's king is currently not in check and the target location is not in check either. Furthermore, the king is not located on the same square as the queen (i.e. $$$a_x \neq b_x$$$ or $$$a_y \neq b_y$$$), and the target does coincide neither with the queen's position (i.e. $$$c_x \neq a_x$$$ or $$$c_y \neq a_y$$$) nor with the king's position (i.e. $$$c_x \neq b_x$$$ or $$$c_y \neq b_y$$$).

Print "YES" (without quotes) if Bob can get from $$$(b_x, b_y)$$$ to $$$(c_x, c_y)$$$ without ever getting in check, otherwise print "NO". You can print each letter in any case (upper or lower).

NoteIn the diagrams below, the squares controlled by the black queen are marked red, and the target square is marked blue.In the first case, the king can move, for instance, via the squares $$$(2, 3)$$$ and $$$(3, 2)$$$. Note that the direct route through $$$(2, 2)$$$ goes through check.  In the second case, the queen watches the fourth rank, and the king has no means of crossing it.  In the third case, the queen watches the third file.

open Printf open Scanf
module MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let abs v = abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) let min_int,max_int = min_int,max_int end
module MyInt64 = struct
	let (%$) = (mod) let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v)) let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v) let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done let repb from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod (~~| !i) with | `Break -> f := false | _ -> i := !i +$ 1 done; !f let repm from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod !m (~~| !i) with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; !m let repmb from_ to_ m_init fbod = let i,f,m = ref ~|from_,ref true,ref m_init in while !i <= ~|to_ && !f do match fbod (~~| !i) !m with | `Break -> f := false | `Break_m m' -> (f := false; m := m') | `Ok m' -> (i := !i +$ 1; m := m') done; (!m,!f) let string_of_list ?(separator=" ") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls "" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
	let (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v
	let ceildiv m n = (m+n-1L) / n
	let abs v = Int64.abs v let (land),(lor),(lxor),lnot,(lsl),(lsr),(asr) = let open Int64 in (logand),(logor),(logxor),lognot,(fun u v -> shift_left u (~|v)),(fun u v -> shift_right u (~|v)),(fun u v -> shift_right_logical u (~|v)) let min_int,max_int = Int64.min_int,Int64.max_int let get_string _ = scanf " %s" (fun v -> v)
	let i32,i64 = Int64.to_int,Int64.of_int let alen a = i64 @@ Array.length a
	let dump_array a = a |> Array.to_list |> string_of_list Int64.to_string |> print_endline let i32_get_int _ = Scanf.scanf " %d" (fun v -> v) let i32_get_2_ints _ = Scanf.scanf " %d %d" (fun u v -> u,v) let i32_get_3_ints _ = Scanf.scanf " %d %d %d" (fun u v w -> u,v,w) let i32_get_4_ints _ = Scanf.scanf " %d %d %d %d" (fun u v w x -> u,v,w,x) let i32_get_5_ints _ = Scanf.scanf " %d %d %d %d %d" (fun u v w x y -> u,v,w,x,y) let repi from_ to_ fbod = let i,f = ref from_,ref true in while !i <= to_ && !f do match fbod !i with | `Break -> f := false | _ -> i := !i +$ 1 done
end open MyInt64

let () =
	let n = get_i64 0 in
	let ax,ay = get_2_i64 0 in
	let bx,by = get_2_i64 0 in
	let cx,cy = get_2_i64 0 in
	(
		if
		(bx < ax && cx < ax || bx > ax && cx > ax)
		&&
		(by < ay && cy < ay || by > ay && cy > ay)
	then (
		let dx,dy = labs (bx - ax), labs (by - ay) in
		if dx = dy then "NO" else "YES"
	) else "NO"
	)
	|> print_endline


You are given a binary matrix $$$A$$$ of size $$$n \times n$$$. Let's denote an $$$x$$$-compression of the given matrix as a matrix $$$B$$$ of size $$$\frac{n}{x} \times \frac{n}{x}$$$ such that for every $$$i \in [1, n], j \in [1, n]$$$ the condition $$$A[i][j] = B[\lceil \frac{i}{x} \rceil][\lceil \frac{j}{x} \rceil]$$$ is met.Obviously, $$$x$$$-compression is possible only if $$$x$$$ divides $$$n$$$, but this condition is not enough. For example, the following matrix of size $$$2 \times 2$$$ does not have any $$$2$$$-compression: $$$01$$$   $$$10$$$ For the given matrix $$$A$$$, find maximum $$$x$$$ such that an $$$x$$$-compression of this matrix is possible.Note that the input is given in compressed form. But even though it is compressed, you'd better use fast input.

The first line contains one number $$$n$$$ ($$$4 \le n \le 5200$$$) — the number of rows and columns in the matrix $$$A$$$. It is guaranteed that $$$n$$$ is divisible by $$$4$$$. Then the representation of matrix follows. Each of $$$n$$$ next lines contains $$$\frac{n}{4}$$$ one-digit hexadecimal numbers (that is, these numbers can be represented either as digits from $$$0$$$ to $$$9$$$ or as uppercase Latin letters from $$$A$$$ to $$$F$$$). Binary representation of each of these numbers denotes next $$$4$$$ elements of the matrix in the corresponding row. For example, if the number $$$B$$$ is given, then the corresponding elements are 1011, and if the number is $$$5$$$, then the corresponding elements are 0101. Elements are not separated by whitespaces.

Print one number: maximum $$$x$$$ such that an $$$x$$$-compression of the given matrix is possible.

let int_of_hex c = match c with
| '0' .. '9' -> int_of_char c - int_of_char '0'
| 'A' .. 'F' -> int_of_char c - int_of_char 'A' + 10
| _ -> failwith ""
let rv f p q = f q p
let divisors n = (* O(sqrt n) *)
  let rec f0 i a =
    if i*i > n then a
    else if i*i = n && n mod i = 0 then i::a
    else if n mod i = 0 then f0 (i+1) (i::(n/i)::a)
    else f0 (i+1) a in f0 1 []
;;
Scanf.(Array.(scanf " %d" @@ fun n ->
  let mat = make_matrix n n 0 in
  init n (fun i -> scanf " %s" @@ fun s ->
    String.iteri (fun j c ->
      let ih = int_of_hex c in
      mat.(i).(4*j)   <- ih land 8 / 8;
      mat.(i).(4*j+1) <- ih land 4 / 4;
      mat.(i).(4*j+2) <- ih land 2 / 2;
      mat.(i).(4*j+3) <- ih land 1;
    ) s
  ) |> ignore;
  (* iter (fun a ->
    iter (fun v ->
      Printf.printf "%d " v
    ) a; print_newline ()
  ) mat; *)
  let cml = make_matrix (n+1) (n+1) 0 in
  iteri (fun i a ->
    iteri (fun j _ ->
      cml.(i+1).(j+1) <- cml.(i+1).(j) + mat.(i).(j)
    ) a
  ) mat;
  iteri (fun j a ->
    iteri (fun i _ ->
      cml.(i+1).(j+1) <- cml.(i+1).(j+1) + cml.(i).(j+1)
    ) a
  ) mat;
  (* iter (fun a ->
    iter (fun v ->
      Printf.printf "%2d " v
    ) a; print_newline ()
  ) cml; *)
  let get d y x =
    let y,x = y+1,x+1 in
    cml.(y+d-1).(x+d-1) - cml.(y+d-1).(x-1) - cml.(y-1).(x+d-1) + cml.(y-1).(x-1)
  in
  divisors n
  |> List.sort (rv compare)
  |> List.iter (fun d ->
    if d=1 then (
      print_int 1; exit 0;
    );
    let f = ref true in
    init (n/d) (fun y ->
      init (n/d) (fun x ->
        let w = get d (y*d) (x*d) in
        if w=d*d || w=0 then ()
        else f := false
      ) |> ignore
    ) |> ignore;
    if !f then (
      print_int d; exit 0
    )
  )
));;

let int_of_hex c = match c with
| '0' .. '9' -> int_of_char c - int_of_char '0'
| 'A' .. 'F' -> int_of_char c - int_of_char 'A' + 10
| _ -> failwith ""
let rec fix f x = f (fix f) x
let gcd = fix (fun f m n ->
  if n=0 then m else f n (m mod n))
;;
Scanf.(Array.(scanf " %d" @@ fun n ->
  let mat = make_matrix n n 0 in
  init n (fun i -> scanf " %s" @@ fun s ->
    String.iteri (fun j c ->
      let ih = int_of_hex c in
      mat.(i).(4*j)   <- ih land 8 / 8;
      mat.(i).(4*j+1) <- ih land 4 / 4;
      mat.(i).(4*j+2) <- ih land 2 / 2;
      mat.(i).(4*j+3) <- ih land 1;
    ) s
  ) |> ignore;
  let visited = make_matrix n n false in
  let g = ref n in
  let fy y x pt = fix (fun f y ->
    if y>=n || visited.(y).(x) || mat.(y).(x) <> pt then y-1 else f (y+1)) y in
  for i=0 to n-1 do
    for j=0 to n-1 do
      if visited.(i).(j) then ()
      else (
        let pat = mat.(i).(j) in
        let bottom = fy i j pat in
        let finalize x =
          for ii=i to bottom do
            for jj=j to x-1 do
              visited.(ii).(jj) <- true
            done
          done;
        in
        let p,q = fix (fun f (p,q) x ->
          if x>=n then (
            finalize x; (p,q)
          ) else
          let b1 = fy i x pat in
          if b1 <> bottom then (
            finalize x; (p,q)
          ) else f (p,q+1) (x+1)
        ) (bottom+1,1) (j+1) in
        g := gcd !g @@ gcd p q;
        (* Printf.printf "%2d %2d :: %2d %2d\n" i j p q;
        iter (fun b ->
          iter (fun f -> Printf.printf @@ if f then "t " else "_ ") b; print_newline ()
        ) visited *)
      )
    done;
  done;
  print_int @@ !g
))

let int_of_hex c = match c with
| '0' .. '9' -> int_of_char c - int_of_char '0'
| 'A' .. 'F' -> int_of_char c - int_of_char 'A' + 10
| _ -> failwith ""
let divisors n = (* O(sqrt n) *)
  let rec f0 i a =
    if i*i > n then a
    else if i*i = n && n mod i = 0 then i::a
    else if n mod i = 0 then f0 (i+1) (i::(n/i)::a)
    else f0 (i+1) a in f0 1 []
let binary_search ng ok f = let d = if ng < ok then 1 else -1 in
  let rec f0 ng ok =
    if abs (ok - ng) <= 1 then ok
    else let mid = ng + (ok - ng) / 2 in if f mid then f0 ng mid else f0 mid ok
  in f0 (ng-d) (ok+d)
;;
Scanf.(Array.(scanf " %d" @@ fun n ->
  let mat = make_matrix n n 0 in
  init n (fun i -> scanf " %s" @@ fun s ->
    String.iteri (fun j c ->
      let ih = int_of_hex c in
      mat.(i).(4*j)   <- ih land 8 / 8;
      mat.(i).(4*j+1) <- ih land 4 / 4;
      mat.(i).(4*j+2) <- ih land 2 / 2;
      mat.(i).(4*j+3) <- ih land 1;
    ) s
  ) |> ignore;
  (* iter (fun a ->
    iter (fun v ->
      Printf.printf "%d " v
    ) a; print_newline ()
  ) mat; *)
  let cml = make_matrix (n+1) (n+1) 0 in
  iteri (fun i a ->
    iteri (fun j _ ->
      cml.(i+1).(j+1) <- cml.(i+1).(j) + mat.(i).(j)
    ) a
  ) mat;
  iteri (fun j a ->
    iteri (fun i _ ->
      cml.(i+1).(j+1) <- cml.(i+1).(j+1) + cml.(i).(j+1)
    ) a
  ) mat;
  (* iter (fun a ->
    iter (fun v ->
      Printf.printf "%2d " v
    ) a; print_newline ()
  ) cml; *)
  let get d y x =
    cml.(y+d).(x+d) - cml.(y+d).(x) - cml.(y).(x+d) + cml.(y).(x)
  in
  let divs = divisors n |> List.sort compare |> of_list in
  (* iter (Printf.printf "%2d; ") divs; print_newline (); *)
  print_int @@ divs.(
    binary_search (length divs-1) 0 (fun i ->
      let d = divs.(i) in
      let f = ref true in
      (* Printf.printf "%d:\n" d; *)
      init (n/d) (fun y ->
        init (n/d) (fun x ->
          let w = get d (y*d) (x*d) in
          (* Printf.printf "  %2d,%2d :: %2d\n" (y*d) (x*d) w; *)
          if w=d*d || w=0 then ()
          else f := false
        ) |> ignore
      ) |> ignore; !f
    ))
));;

let int_of_hex c = match c with
| '0' .. '9' -> int_of_char c - int_of_char '0'
| 'A' .. 'F' -> int_of_char c - int_of_char 'A' + 10
| _ -> failwith ""
let divisors n = (* O(sqrt n) *)
  let rec f0 i a =
    if i*i > n then a
    else if i*i = n && n mod i = 0 then i::a
    else if n mod i = 0 then f0 (i+1) (i::(n/i)::a)
    else f0 (i+1) a in f0 1 []
let binary_search ng ok f = let d = if ng < ok then 1 else -1 in
  let rec f0 ng ok =
    if abs (ok - ng) <= 1 then ok
    else let mid = ng + (ok - ng) / 2 in if f mid then f0 ng mid else f0 mid ok
  in f0 (ng-d) (ok+d)
;;
Scanf.(Array.(scanf " %d" @@ fun n ->
  let mat = make_matrix n n 0 in
  init n (fun i -> scanf " %s" @@ fun s ->
    String.iteri (fun j c ->
      let ih = int_of_hex c in
      mat.(i).(4*j)   <- ih land 8 / 8;
      mat.(i).(4*j+1) <- ih land 4 / 4;
      mat.(i).(4*j+2) <- ih land 2 / 2;
      mat.(i).(4*j+3) <- ih land 1;
    ) s
  ) |> ignore;
  (* iter (fun a ->
    iter (fun v ->
      Printf.printf "%d " v
    ) a; print_newline ()
  ) mat; *)
  let cml = make_matrix (n+1) (n+1) 0 in
  iteri (fun i a ->
    iteri (fun j _ ->
      cml.(i+1).(j+1) <- cml.(i+1).(j) + mat.(i).(j)
    ) a
  ) mat;
  iteri (fun j a ->
    iteri (fun i _ ->
      cml.(i+1).(j+1) <- cml.(i+1).(j+1) + cml.(i).(j+1)
    ) a
  ) mat;
  (* iter (fun a ->
    iter (fun v ->
      Printf.printf "%2d " v
    ) a; print_newline ()
  ) cml; *)
  let get d y x =
    cml.(y+d).(x+d) - cml.(y+d).(x) - cml.(y).(x+d) + cml.(y).(x)
  in
  let divs = divisors n |> List.sort compare |> of_list in
  print_int @@ divs.(
    binary_search (length divs-1) 0 (fun i ->
      let d = divs.(i) in
      let f = ref true in
      init (n/d) (fun y ->
        init (n/d) (fun x ->
          let w = get d y x in
          if w=d*d || w=0 then ()
          else f := false
        ) |> ignore
      ) |> ignore; !f
    ))
))

let int_of_hex c = match c with
| '0' .. '9' -> int_of_char c - int_of_char '0'
| 'A' .. 'F' -> int_of_char c - int_of_char 'A' + 10
| _ -> failwith ""
let rec fix f x = f (fix f) x
let gcd = fix (fun f m n ->
  if n=0 then m else f n (m mod n))
;;
Scanf.(Array.(scanf " %d" @@ fun n ->
  let mat = make_matrix n n 0 in
  init n (fun i -> scanf " %s" @@ fun s ->
    String.iteri (fun j c ->
      let ih = int_of_hex c in
      mat.(i).(4*j)   <- ih land 8 / 8;
      mat.(i).(4*j+1) <- ih land 4 / 4;
      mat.(i).(4*j+2) <- ih land 2 / 2;
      mat.(i).(4*j+3) <- ih land 1;
    ) s
  ) |> ignore;
  let visited = make_matrix n n false in
  let g = ref n in
  let rec visit y x c =
    if y >= n || x >= n || visited.(y).(x) || mat.(y).(x) <> c then 0,0
    else (
      visited.(y).(x) <- true;
      let p,q = visit (y+1) x c in
      let r,s = visit y (x+1) c in
      p+r+1,q+s+1
    )
  in
  for i=0 to n-1 do
    for j=0 to n-1 do
      if visited.(i).(j) then ()
      else (
        let p,q = visit i j mat.(i).(j) in
        g := gcd !g @@ gcd p q;
      )
    done;
  done;
  print_int @@ !g
))


You are given a positive decimal number x.Your task is to convert it to the "simple exponential notation".Let x = a·10b, where 1 ≤ a < 10, then in general case the "simple exponential notation" looks like "aEb". If b equals to zero, the part "Eb" should be skipped. If a is an integer, it should be written without decimal point. Also there should not be extra zeroes in a and b.

The only line contains the positive decimal number x. The length of the line will not exceed 106. Note that you are given too large number, so you can't use standard built-in data types "float", "double" and other.

Print the only line — the "simple exponential notation" of the given number x.

let _ =
  let sb = Scanf.Scanning.stdib in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let (s, e) =
    try
      let i = String.index s '.' in
      let n = String.length s in
	(String.sub s 0 i ^ String.sub s (i + 1) (n - i - 1), -(n - i - 1))
    with
      |	Not_found -> (s, 0)
  in
  let s =
    let n = String.length s in
    let pos = ref 0 in
      while !pos < n && s.[!pos] = '0' do
	incr pos
      done;
      String.sub s !pos (n - !pos)
  in
  let (s, e) =
    let n = String.length s in
    let e = ref e in
    let pos = ref n in
      while !pos > 0 && s.[!pos - 1] = '0' do
	decr pos;
	incr e;
      done;
      (String.sub s 0 !pos, !e)
  in
  let n = String.length s in
  let e = e + n - 1 in
    if n > 1
    then Printf.printf "%c.%s" s.[0] (String.sub s 1 (n - 1))
    else Printf.printf "%s" s;
    if e <> 0
    then Printf.printf "E%d" e;
    Printf.printf "\n"


A rooted tree is a non-directed connected graph without any cycles with a distinguished vertex, which is called the tree root. Consider the vertices of a rooted tree, that consists of n vertices, numbered from 1 to n. In this problem the tree root is the vertex number 1.Let's represent the length of the shortest by the number of edges path in the tree between vertices v and u as d(v, u).A parent of vertex v in the rooted tree with the root in vertex r (v ≠ r) is vertex pv, such that d(r, pv) + 1 = d(r, v) and d(pv, v) = 1. For example, on the picture the parent of vertex v = 5 is vertex p5 = 2.One day Polycarpus came across a rooted tree, consisting of n vertices. The tree wasn't exactly ordinary: it had strings written on its edges. Polycarpus positioned the tree on the plane so as to make all edges lead from top to bottom if you go from the vertex parent to the vertex (see the picture). For any edge that lead from vertex pv to vertex v (1 < v ≤ n), he knows string sv that is written on it. All strings are written on the edges from top to bottom. For example, on the picture s7="ba". The characters in the strings are numbered starting from 0.    An example of Polycarpus's tree (corresponds to the example from the statement) Polycarpus defines the position in this tree as a specific letter on a specific string. The position is written as a pair of integers (v, x) that means that the position is the x-th letter of the string sv (1 < v ≤ n, 0 ≤ x < |sv|), where |sv| is the length of string sv. For example, the highlighted letters are positions (2, 1) and (3, 1).Let's consider the pair of positions (v, x) and (u, y) in Polycarpus' tree, such that the way from the first position to the second goes down on each step. We will consider that the pair of such positions defines string z. String z consists of all letters on the way from (v, x) to (u, y), written in the order of this path. For example, in the picture the highlighted positions define string "bacaba".Polycarpus has a string t, he wants to know the number of pairs of positions that define string t. Note that the way from the first position to the second in the pair must go down everywhere. Help him with this challenging tree-string problem!

The first line contains integer n (2 ≤ n ≤ 105) — the number of vertices of Polycarpus's tree. Next n - 1 lines contain the tree edges. The i-th of them contains number pi + 1 and string si + 1 (1 ≤ pi + 1 ≤ n; pi + 1 ≠ (i + 1)). String si + 1 is non-empty and consists of lowercase English letters. The last line contains string t. String t consists of lowercase English letters, its length is at least 2. It is guaranteed that the input contains at most 3·105 English letters.

Print a single integer — the required number. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

7
1 ab
5 bacaba
1 abacaba
2 aca
5 ba
2 ba
aba

7
1 ab
5 bacaba
1 abacaba
2 aca
5 ba
2 ba
bacaba

NoteIn the first test case string "aba" is determined by the pairs of positions: (2, 0) and (5, 0); (5, 2) and (6, 1); (5, 2) and (3, 1); (4, 0) and (4, 2); (4, 4) and (4, 6); (3, 3) and (3, 5).Note that the string is not defined by the pair of positions (7, 1) and (5, 0), as the way between them doesn't always go down.

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

(* kmp algorithm. *)
(* memo.(i) will store the length of the longest prefix of s
   that matches the tail of s1...si *)
let kmptable s n =
  let memo = Array.make n 0 in
    for i=1 to (n-1) do
      let rec loop j =
	if s.[i] = s.[j] then j+1 else if j=0 then 0 else loop memo.(j-1)
      in memo.(i) <- loop memo.(i-1)
    done;
    memo

(*
(* returns table.
   table.(i) will store the length of the longest prefix of ms
   that matches the tail of ts0...tsi *)
let tailtable ts n ms m =
  let memo = kmptable ms m in
  let table = Array.make n 0 in
    table.(0) <- if ts.[0] = ms.[0] then 1 else 0;
    for i=1 to (n-1) do
      let rec loop j =
	if ts.[i] = ms.[j] then j+1 else if j=0 then 0 else loop memo.(j-1)
      in
	table.(i) <- loop (if table.(i-1) < m then table.(i-1) else memo.(m-1))
    done;
    table
*)

let solve child n pattern =
  let m = String.length pattern in
  let memo = kmptable pattern m in

  let run_kmp s j =
    let n = String.length s in
    let rec outer_loop i count j = if i=n then (j, count) else
      let rec loop j =
	if s.[i] = pattern.[j] then j+1 else if j=0 then 0 else loop memo.(j-1)
      in
      let j = loop j in
      let count = if j=m then count+1 else count in
      let j = if j=m then memo.(j-1) else j in
	outer_loop (i+1) count j
    in
      outer_loop 0 0 j
  in

  let rec dfs v j ac =
(*    Printf.printf "at node %d (j=%d, ac=%d)\n" v j ac; *)
    List.fold_left (
      fun ac (w,s) ->
(*	Printf.printf "   edge: (%d, %d) = \"%s\"\n" v w s; *)
	let (j', count) = run_kmp s j in
	  dfs w j' (ac + count)
    ) ac child.(v)
  in
    dfs 0 0 0

let () =
  let n = read_int() in
  let child = Array.make n [] in
    for i=1 to n-1 do
      let p = read_int() -1 in
      let s = read_string() in
	child.(p) <- (i,s)::child.(p);
    done;

    let pattern = read_string() in

      Printf.printf "%d\n" (solve child n pattern)

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

(* kmp algorithm. *)
(* memo.(i) will store the length of the longest prefix of s
   that matches the tail of s1...si *)
let kmptable s n =
  let memo = Array.make n 0 in
    for i=1 to (n-1) do
      let rec loop j =
	if s.[i] = s.[j] then j+1 else if j=0 then 0 else loop memo.(j-1)
      in memo.(i) <- loop memo.(i-1)
    done;
    memo

(*
(* returns table.
   table.(i) will store the length of the longest prefix of ms
   that matches the tail of ts0...tsi *)
let tailtable ts n ms m =
  let memo = kmptable ms m in
  let table = Array.make n 0 in
    table.(0) <- if ts.[0] = ms.[0] then 1 else 0;
    for i=1 to (n-1) do
      let rec loop j =
	if ts.[i] = ms.[j] then j+1 else if j=0 then 0 else loop memo.(j-1)
      in
	table.(i) <- loop (if table.(i-1) < m then table.(i-1) else memo.(m-1))
    done;
    table
*)

let l2n c = (int_of_char c) - (int_of_char 'a')
let n2l n = char_of_int ((int_of_char 'a') + n)

let solve child n pattern =
  let m = String.length pattern in
  let memo = kmptable pattern m in
  let jupdate_array = Array.make_matrix m 26 (-1) in

  let rec jupdate c x j =
    if jupdate_array.(j).(x) >= 0 then jupdate_array.(j).(x) else
      let j' = if c = pattern.[j] then j+1 else if j=0 then 0 else jupdate c x memo.(j-1) in
	jupdate_array.(j).(x) <- j';
	j'
  in

  let run_kmp s j =
    let n = String.length s in
    let rec loop i count j = if i=n then (j, count) else
      let j = jupdate s.[i] (l2n s.[i]) j in
      let count = if j=m then count+1 else count in
      let j = if j=m then memo.(j-1) else j in
	loop (i+1) count j
    in
      loop 0 0 j
  in

  let rec dfs v j ac =
(*    Printf.printf "at node %d (j=%d, ac=%d)\n" v j ac; *)
    List.fold_left (
      fun ac (w,s) ->
(*	Printf.printf "   edge: (%d, %d) = \"%s\"\n" v w s; *)
	let (j', count) = run_kmp s j in
	  dfs w j' (ac + count)
    ) ac child.(v)
  in
    dfs 0 0 0

let () =
  let n = read_int() in
  let child = Array.make n [] in
    for i=1 to n-1 do
      let p = read_int() -1 in
      let s = read_string() in
	child.(p) <- (i,s)::child.(p);
    done;

    let pattern = read_string() in

      Printf.printf "%d\n" (solve child n pattern)


Mihai has an $$$8 \times 8$$$ chessboard whose rows are numbered from $$$1$$$ to $$$8$$$ from top to bottom and whose columns are numbered from $$$1$$$ to $$$8$$$ from left to right.Mihai has placed exactly one bishop on the chessboard. The bishop is not placed on the edges of the board. (In other words, the row and column of the bishop are between $$$2$$$ and $$$7$$$, inclusive.)The bishop attacks in all directions diagonally, and there is no limit to the distance which the bishop can attack. Note that the cell on which the bishop is placed is also considered attacked.     An example of a bishop on a chessboard. The squares it attacks are marked in red. Mihai has marked all squares the bishop attacks, but forgot where the bishop was! Help Mihai find the position of the bishop.

The first line of the input contains a single integer $$$t$$$ ($$$1 \leq t \leq 36$$$) — the number of test cases. The description of test cases follows. There is an empty line before each test case. Each test case consists of $$$8$$$ lines, each containing $$$8$$$ characters. Each of these characters is either '#' or '.', denoting a square under attack and a square not under attack, respectively.

For each test case, output two integers $$$r$$$ and $$$c$$$ ($$$2 \leq r, c \leq 7$$$) — the row and column of the bishop.  The input is generated in such a way that there is always exactly one possible location of the bishop that is not on the edge of the board.

NoteThe first test case is pictured in the statement. Since the bishop lies in the intersection row $$$4$$$ and column $$$3$$$, the correct output is 4 3.

(*
https://codeforces.com/contest/1681/submission/163367661
See also: https://codeforces.com/contest/1681/submission/163367661
*)

open Printf
open Scanf

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

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

(* Main Code file *)

let () =
    let t = read_int() in
    let n = 8 in
    for t1=1 to t do
        (* printf "TC %d\n" t1; *)
        let rows = Array.init n (fun index -> read_string()) in
        try
            for i=0 to n - 1 do
                let s: string = (Array.get rows i) in
                (* printf "%d ^%s$\n" i s; *)
                for j=1 to n-2 do
                    (* printf "%c " s.[0]; *)
                    (* printf "> %d %d %c %c %c\n" i j
                        s.[j - 1] s.[j] s.[j + 1];*)
                    if s.[j - 1] == '#' && s.[j] == '.' && s.[j + 1] == '#' then
                        let () = (printf "%d %d\n" (i + 2) (j + 1)) in
                        raise Exit
                    else ()
                done;
            done;
        with Exit -> ()
    done;