Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a × b.After n - 1 steps there is only one number left. Can you make this number equal to 24?

The first line contains a single integer n (1 ≤ n ≤ 105).

If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes). If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces. If there are multiple valid answers, you may print any of them.

open Printf
open Scanf

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

  let rec solve n ac =
    if n=4 then (
      let ac = "3 * 4 = 12" :: ac in
      let ac = "2 * 12 = 24" :: ac in
      let ac = "1 * 24 = 24" :: ac in
      ac
    ) else if n=5 then (
      let ac = "4 + 5 = 9" :: ac in
      let ac = "3 + 9 = 12" :: ac in
      let ac = "2 * 12 = 24" :: ac in
      let ac = "1 * 24 = 24" :: ac in
      ac
    ) else (
      let ac = ((sprintf "%d - %d = %d") n (n-1) 1) :: ac in
      let ac = ((sprintf "%d * %d = %d") 1 (n-2) (n-2)) :: ac in
      solve (n-2) ac
    )
  in

  if n<4 then printf "NO\n"
  else (
    printf "YES\n";
    List.iter (fun e -> printf "%s\n" e) (List.rev (solve n []))
  )

open Printf
open Scanf

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

  let rec solve n ac =
    if n=4 then (
      let ac = "3 * 4 = 12" :: ac in
      let ac = "2 * 12 = 24" :: ac in
      let ac = "1 * 24 = 24" :: ac in
      ac
    ) else if n=5 then (
      let ac = "4 + 5 = 9" :: ac in
      let ac = "3 + 9 = 12" :: ac in
      let ac = "2 * 12 = 24" :: ac in
      let ac = "1 * 24 = 24" :: ac in
      ac
    ) else (
      let ac = ((sprintf "%d - %d = %d") n (n-1) 1) :: ac in
      let ac = ((sprintf "%d * %d = %d") 1 (n-2) (n-2)) :: ac in
      solve (n-2) ac
    )
  in

  if n<4 then printf "NO\n"
  else List.iter (fun e -> printf "%s\n" e) (List.rev (solve n []))


At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks.Fortunately, Picks remembers something about his set S:  its elements were distinct integers from 1 to limit;  the value of  was equal to sum; here lowbit(x) equals 2k where k is the position of the first one in the binary representation of x. For example, lowbit(100102) = 102, lowbit(100012) = 12, lowbit(100002) = 100002 (binary representation). Can you help Picks and find any set S, that satisfies all the above conditions?

The first line contains two integers: sum, limit (1 ≤ sum, limit ≤ 105).

In the first line print an integer n (1 ≤ n ≤ 105), denoting the size of S. Then print the elements of set S in any order. If there are multiple answers, print any of them. If it's impossible to find a suitable set, print -1.

NoteIn sample test 1: lowbit(4) = 4, lowbit(5) = 1, 4 + 1 = 5.In sample test 2: lowbit(1) = 1, lowbit(2) = 2, lowbit(3) = 1, 1 + 2 + 1 = 4.

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

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

let tab=Array.make 30 [];;
let nb=Array.make 30 0;;

let rec remplir n i=
   if (n mod 2)=0 then (nb.(i)<-0;remplir (n/2) (i+1))
   else (nb.(i)<-1;if n<>1 then remplir (n/2) (i+1));;

remplir sum 1;;

for i=1 to limit do
   let a=lowbit i 1 in tab.(a)<-i::tab.(a)
done;;

let sol=Array.make 30 0;;

let rec add x=
   if sol.(x)=0 then sol.(x)<-1 else (sol.(x)<-0;add (x+1));;

let b=ref true;;

let tete=function
|[]->0
|h::t->h;;

let queue=function
|[]->[]
|h::t->t;;

let y=ref 0;;

let liste=ref [];;

let rec prem i=
   if i=0 then (0,0)
   else if tab.(i)<>[] then (y:=tete tab.(i);tab.(i)<-queue tab.(i); (!y,i))
   else prem (i-1);;

for i=29 downto 1 do
   while (nb.(i)=1)&&(sol.(i)=0)&&(!b) do
      let (x,z)=prem i in
      if x=0 then b:=false else
      begin
      liste:=x::(!liste);
      add z
      end
   done
done;;

let rec taille=function
|[]->0
|h::t->1+taille t;;

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

if !b=false then print_int (-1) else
   begin
   let x=taille !liste in
   Printf.printf "%d\n" x;
   print_list !liste
   end;;


Arkady has a playlist that initially consists of $$$n$$$ songs, numerated from $$$1$$$ to $$$n$$$ in the order they appear in the playlist. Arkady starts listening to the songs in the playlist one by one, starting from song $$$1$$$. The playlist is cycled, i. e. after listening to the last song, Arkady will continue listening from the beginning.Each song has a genre $$$a_i$$$, which is a positive integer. Let Arkady finish listening to a song with genre $$$y$$$, and the genre of the next-to-last listened song be $$$x$$$. If $$$\operatorname{gcd}(x, y) = 1$$$, he deletes the last listened song (with genre $$$y$$$) from the playlist. After that he continues listening normally, skipping the deleted songs, and forgetting about songs he listened to before. In other words, after he deletes a song, he can't delete the next song immediately.Here $$$\operatorname{gcd}(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.For example, if the initial songs' genres were $$$[5, 9, 2, 10, 15]$$$, then the playlist is converted as follows: [5, 9, 2, 10, 15] $$$\to$$$ [5, 9, 2, 10, 15] $$$\to$$$ [5, 2, 10, 15] (because $$$\operatorname{gcd}(5, 9) = 1$$$) $$$\to$$$ [5, 2, 10, 15] $$$\to$$$ [5, 2, 10, 15] $$$\to$$$ [5, 2, 10, 15] $$$\to$$$ [5, 2, 10, 15] $$$\to$$$ [5, 2, 10, 15] $$$\to$$$ [5, 10, 15] (because $$$\operatorname{gcd}(5, 2) = 1$$$) $$$\to$$$ [5, 10, 15] $$$\to$$$ [5, 10, 15] $$$\to$$$ ... The bold numbers represent the two last played songs. Note that after a song is deleted, Arkady forgets that he listened to that and the previous songs.Given the initial playlist, please determine which songs are eventually deleted and the order these songs are deleted.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10\,000$$$). Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the number of songs. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the genres of the songs. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a single line. First, print a single integer $$$k$$$ — the number of deleted songs. After that print $$$k$$$ distinct integers: deleted songs in the order of their deletion.

NoteExplanation of the first test case is given in the statement.In the second test case, the playlist is converted as follows: [1, 2, 4, 2, 4, 2] $$$\to$$$ [1, 2, 4, 2, 4, 2] $$$\to$$$ [1, 4, 2, 4, 2] (because $$$\operatorname{gcd}(1, 2) = 1$$$) $$$\to$$$ [1, 4, 2, 4, 2] $$$\to$$$ [1, 4, 2, 4, 2] $$$\to$$$ [1, 4, 2, 4, 2] $$$\to$$$ [1, 4, 2, 4, 2] $$$\to$$$ [1, 4, 2, 4, 2] $$$\to$$$ [4, 2, 4, 2] (because $$$\operatorname{gcd}(2, 1) = 1$$$) $$$\to$$$ [4, 2, 4, 2] $$$\to$$$ ...In the third test case, the playlist is converted as follows: [1, 2] $$$\to$$$ [1, 2] $$$\to$$$ [1] (because $$$\operatorname{gcd}(1, 2) = 1$$$) $$$\to$$$ [1] $$$\to$$$ [1] (Arkady listened to the same song twice in a row) $$$\to$$$ [] (because $$$\operatorname{gcd}(1, 1) = 1$$$).The fourth test case is same as the third after deletion of the second song.In the fifth test case, the same song is listened to over and over again, but since $$$\operatorname{gcd}(2, 2) \ne 1$$$, it is not deleted.

let rec gcd a b = if a=0 then b else gcd (b mod a) a

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

open Iset
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 pred x s =
  let (l,_,_) = split x s in
  max_elt (if is_empty l then s else l)

let succ x s =
  let (_,_,r) = split x s in
  min_elt (if is_empty r then s else r)

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

let solve n a =
  let gcd_test i j = gcd a.(i) a.(j) = 1 in

  let delete i j present active =
    (* i is active and present. j and its successor, have GCD = 1.
       Remove j, and return (present', active') *)
    if not (gcd_test i j) then failwith "inconsistent 3";
    let present = remove j present in
    let active = remove j active in
    if is_empty active then (present, active) else
      let k = succ i present in
      (present, if gcd_test i k then active else remove i active)
  in

  let rec loop i present active ac =
    (* i = current place, i must be active
       present = the set of idices that still exist
       active = the indices where that and the successor index in present
                have gcd = 1. *)
    let j = succ i present in
    let (present, active) = delete i j present active in
    let ac = j::ac in
    if is_empty active then ac else
      loop (succ i active) present active ac
  in

  let active = fold 0 (n-1) (fun i ac ->
    let j = (i+1) mod n in
    if gcd a.(i) a.(j) = 1 then add i ac else ac
  ) empty in

  let present = fold 0 (n-1) (fun i ac -> add i ac) empty in

  if is_empty active then [] else
    let i = succ (n-1) active in
    List.rev (loop i present active [])

let () =
  let cases = read_int () in
  for case = 1 to cases do
    let n = read_int () in
    let a = Array.init n read_int in
    let answer = solve n a in
    printf "%d " (List.length answer);
    List.iter (fun i -> printf "%d " (i+1)) answer;
    print_newline()
  done


A connected undirected graph is called a vertex cactus, if each vertex of this graph belongs to at most one simple cycle.A simple cycle in a undirected graph is a sequence of distinct vertices v1, v2, ..., vt (t > 2), such that for any i (1 ≤ i < t) exists an edge between vertices vi and vi + 1, and also exists an edge between vertices v1 and vt.A simple path in a undirected graph is a sequence of not necessarily distinct vertices v1, v2, ..., vt (t > 0), such that for any i (1 ≤ i < t) exists an edge between vertices vi and vi + 1 and furthermore each edge occurs no more than once. We'll say that a simple path v1, v2, ..., vt starts at vertex v1 and ends at vertex vt.You've got a graph consisting of n vertices and m edges, that is a vertex cactus. Also, you've got a list of k pairs of interesting vertices xi, yi, for which you want to know the following information — the number of distinct simple paths that start at vertex xi and end at vertex yi. We will consider two simple paths distinct if the sets of edges of the paths are distinct.For each pair of interesting vertices count the number of distinct simple paths between them. As this number can be rather large, you should calculate it modulo 1000000007 (109 + 7).

The first line contains two space-separated integers n, m (2 ≤ n ≤ 105; 1 ≤ m ≤ 105) — the number of vertices and edges in the graph, correspondingly. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n) — the indexes of the vertices connected by the i-th edge. The next line contains a single integer k (1 ≤ k ≤ 105) — the number of pairs of interesting vertices. Next k lines contain the list of pairs of interesting vertices: the i-th line contains two space-separated numbers xi, yi (1 ≤ xi, yi ≤ n; xi ≠ yi) — the indexes of interesting vertices in the i-th pair. It is guaranteed that the given graph is a vertex cactus. It is guaranteed that the graph contains no loops or multiple edges. Consider the graph vertices are numbered from 1 to n.

Print k lines: in the i-th line print a single integer — the number of distinct simple ways, starting at xi and ending at yi, modulo 1000000007 (109 + 7).

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

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

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

let wypelnij p2 n =
  for i=1 to max 20 (n-1) do
    p2.(i) <- (p2.(i-1) * 2) mod (1000*1000*1000+7)
  done;;

let rec dfs from x tab g vis cykle =
(*  Printf.printf "dfs %d %d\n" from x;*)
  vis.(x) <- true;
  let cykl = ref 0 in
  let rec loop l =
    match l with
    | [] -> ()
    | h::t -> (*Printf.printf "lista %d, \n" h;*)
      if h <> from && vis.(h) && !cykl = 0 then begin (*Printf.printf "zacykla %d \n" h ; *)cykl := h end
      else       if h <> from && not vis.(h)
                 then let z = dfs x h tab g vis cykle in
                      if z <> 0 && !cykl = 0 then cykl := z else ()
                 else () ;
      loop t; in
  loop g.(x);
  if !cykl <> 0 then begin tab.(x) <- !cykl ;(* Printf.printf "na cyklu %d %d\n" x !cykl;*)cykle.(x) <- true end;
(*  Printf.printf "wyjdz z %d\n" x;
*)  if !cykl = x || !cykl = 0 then 0
  else !cykl;;

let rec dfs2 from x tab g dyn ojc gleb vis cykle =
(*  Printf.printf "dfs2 %d %d\n" x tab.(x);
*)  ojc.(0).(x) <- from;
  gleb.(x) <- gleb.(from) + 1;
  if dyn.( tab.(x) ) = 0 then dyn.( tab.(x) ) <- dyn.( tab.(from) );
  if cykle.( tab.(x) )  && not vis.( tab.(x) ) then begin
    vis.( tab.(x) ) <- true;
    dyn.( tab.(x) ) <- dyn.( tab.(x) ) + 1 end;
  List.iter ( fun y -> if y <> 1 && ojc.(0).(y) = 0 then dfs2 x y tab g dyn ojc gleb vis cykle ) g.(x);;

let przodek p2 ojc x l =
(*  Printf.printf "przodek %d %d\n" x l;
*)  let a = ref x
  and k = ref l in
  for i = 19 downto 0 do
    if p2.(i) <= !k then begin
(*      Printf.printf "przesun %d %d\n" i !a;
 *)     a := ojc.(i).(!a);
      k := !k - p2.(i)
    end
  done; !a;;

let rec lca p2 ojc gleb x y =
(*  Printf.printf "lca %d %d\n" x y;*)
  if gleb.(x) < gleb.(y) then lca p2 ojc gleb y x
  else
  let a = ref ( przodek p2 ojc x (gleb.(x)-gleb.(y)) )
  and b = ref y in
  for i = 19 downto 0 do
    if ojc.(i).(!a) <> ojc.(i).(!b) then begin
      a := ojc.(i).(!a);
      b := ojc.(i).(!b)
    end
  done;
(*  Printf.printf "lca %d %d %d\n" !a !b ojc.(0).(!b);*)
  if !a <> !b then ojc.(0).(!b)
  else !a;;

let _ =
  let (n, m) = read2() in
  let p2 = Array.make ( max 21 n ) 1 in
  wypelnij p2 n;
  let g = Array.make (n+1) [] in
  for i=1 to m do
    let (a,b) = read2 () in
    g.(a) <- b::g.(a);
    g.(b) <- a::g.(b);
  done;
  let tab = Array.init (n+1) ( fun x -> x )
  and vis = Array.make (n+1) false
  and cykl = Array.make (n+1) false in
  dfs 0 1 tab g vis cykl;
  Array.iteri ( fun i _ -> vis.(i) <- false ) vis; (* czyszczenie vis *)
  let dyn = Array.make (n+1) 0
  and ojc = Array.make_matrix 20 (n+1) 0
  and gleb = Array.make (n+1) 0 in
  dfs2 0 1 tab g dyn ojc gleb vis cykl;
  for i=1 to 19 do
    for j=1 to n do
(*      Printf.printf "%d %d -- %d %d\n" i j ojc.(i-1).(j) ojc.(i-1).( ojc.(i-1).(j));
*)      ojc.(i).(j) <- ojc.(i-1).( ojc.(i-1).(j) )
  done; done;
  let q = read1() in
  for i=1 to q do
    let (a,b) = read2() in
    let c = tab.( lca p2 ojc gleb tab.(a) tab.(b) ) in
(*    Printf.printf "tab %d %d dyn %d %d\n" tab.(a) tab.(b) dyn.( tab.(a) ) dyn.( tab.(b) ); *)
    let wyn = dyn.( tab.(a) ) + dyn.( tab.(b) ) - 2*dyn.( tab.(c) )
    and ww =
    (if cykl.( tab.(c) )  then 1 else 0) in
(*    Printf.printf "%d %d " wyn ww; *)
    Printf.printf "%d\n" p2.(wyn + ww)
  done;;

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

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

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

let wypelnij p2 n =
  for i=1 to max 20 (n-1) do
    p2.(i) <- (p2.(i-1) * 2) mod (1000*1000*1000+7)
  done;;

let rec dfs from x tab g vis cykle =
(*  Printf.printf "dfs %d %d\n" from x;*)
  vis.(x) <- true;
  let cykl = ref 0 in
  let rec loop l =
    match l with
    | [] -> ()
    | h::t -> (*Printf.printf "lista %d, \n" h;*)
      if h <> from && vis.(h) && !cykl = 0 then begin(* Printf.printf "zacykla %d \n" h ;*) cykl := h end
      else       if h <> from && not vis.(h)
                 then let z = dfs x h tab g vis cykle in
                      if z <> 0 && !cykl = 0 then cykl := z else ()
                 else () ;
      loop t; in
  loop g.(x);
  if !cykl <> 0 then begin tab.(x) <- !cykl ; (*Printf.printf "na cyklu %d %d\n" x !cykl;*)cykle.(x) <- true end;
(*  Printf.printf "wyjdz z %d\n" x;
*)  if !cykl = x || !cykl = 0 then 0
  else !cykl;;

let rec dfs2 from x tab g dyn ojc gleb vis =
(*  Printf.printf "dfs2 %d %d\n" x tab.(x);
*)  ojc.(0).(x) <- from;
  gleb.(x) <- gleb.(from) + 1;
  if dyn.( tab.(x) ) = 0 then dyn.( tab.(x) ) <- dyn.( tab.(from) );
  if tab.(x) <> x && not vis.( tab.(x) ) then begin
    vis.( tab.(x) ) <- true;
    dyn.( tab.(x) ) <- dyn.( tab.(x) ) + 1 end;
  List.iter ( fun y -> if y <> 1 && ojc.(0).(y) = 0 then dfs2 x y tab g dyn ojc gleb vis ) g.(x);;

let przodek p2 ojc x l =
(*  Printf.printf "przodek %d %d\n" x l;
*)  let a = ref x
  and k = ref l in
  for i = 19 downto 0 do
    if p2.(i) <= !k then begin
(*      Printf.printf "przesun %d %d\n" i !a;
 *)     a := ojc.(i).(!a);
      k := !k - p2.(i)
    end
  done; !a;;

let rec lca p2 ojc gleb x y =
(*  Printf.printf "lca %d %d\n" x y;
*)  if gleb.(x) < gleb.(y) then lca p2 ojc gleb y x
  else
  let a = ref ( przodek p2 ojc x (gleb.(x)-gleb.(y)) )
  and b = ref y in
  for i = 19 downto 0 do
    if ojc.(i).(!a) <> ojc.(i).(!b) then begin
      a := ojc.(i).(!a);
      b := ojc.(i).(!b)
    end
  done;
(*  Printf.printf "lca %d %d %d\n" !a !b ojc.(0).(!b);
*)  if !a <> !b then ojc.(0).(!b)
  else !a;;

let _ =
  let (n, m) = read2() in
  let p2 = Array.make ( max 21 n ) 1 in
  wypelnij p2 n;
  let g = Array.make (n+1) [] in
  for i=1 to m do
    let (a,b) = read2 () in
    g.(a) <- b::g.(a);
    g.(b) <- a::g.(b);
  done;
  let tab = Array.init (n+1) ( fun x -> x )
  and vis = Array.make (n+1) false
  and cykl = Array.make (n+1) false in
  dfs 0 1 tab g vis cykl;
  Array.iteri ( fun i _ -> vis.(i) <- false ) vis; (* czyszczenie vis *)
  let dyn = Array.make (n+1) 0
  and ojc = Array.make_matrix 20 (n+1) 0
  and gleb = Array.make (n+1) 0 in
  dfs2 0 1 tab g dyn ojc gleb vis;
  for i=1 to 19 do
    for j=1 to n do
(*      Printf.printf "%d %d -- %d %d\n" i j ojc.(i-1).(j) ojc.(i-1).( ojc.(i-1).(j));
*)      ojc.(i).(j) <- ojc.(i-1).( ojc.(i-1).(j) )
  done; done;
  let q = read1() in
  for i=1 to q do
    let (a,b) = read2() in
    let c = tab.( lca p2 ojc gleb tab.(a) tab.(b) )in
    let wyn = dyn.( tab.(a) ) + dyn.( tab.(b) ) - 2*dyn.( tab.( tab.(c) ) )
    and ww =
    (if cykl.(c)  then 1 else 0) in
    Printf.printf "%d\n" p2.(wyn + ww)
  done;;


We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor.There are n citizens in Kekoland, each person has ci coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to the poorest person (poorest person right after taking richest's 1 coin). In case the choice is not unique, he will select one among them at random. Sadly, Robin Hood is old and want to retire in k days. He decided to spend these last days with helping poor people. After taking his money are taken by Robin Hood richest person may become poorest person as well, and it might even happen that Robin Hood will give his money back. For example if all people have same number of coins, then next day they will have same number of coins too. Your task is to find the difference between richest and poorest persons wealth after k days. Note that the choosing at random among richest and poorest doesn't affect the answer.

The first line of the input contains two integers n and k (1 ≤ n ≤ 500 000, 0 ≤ k ≤ 109) — the number of citizens in Kekoland and the number of days left till Robin Hood's retirement. The second line contains n integers, the i-th of them is ci (1 ≤ ci ≤ 109) — initial wealth of the i-th person.

Print a single line containing the difference between richest and poorest peoples wealth.

NoteLets look at how wealth changes through day in the first sample.  [1, 1, 4, 2]  [2, 1, 3, 2] or [1, 2, 3, 2] So the answer is 3 - 1 = 2In second sample wealth will remain the same for each person.

open Printf
open Scanf

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

let long x = Int64.of_int x
let float = Int64.to_float
let abs = Int64.abs

let rec gcd a b = if a=0L then b else gcd (b %% a) a

let normalize (a,b) =
  if a=0L then (0L,1L) else
    let g = gcd (abs a) (abs b) in
    if b<0L then (0L--a//g, 0L--b//g) else (a//g, b//g)
let ( -/ ) (a,b) (c,d) = normalize (a**d -- b**c, b**d)
let ( </ ) a b = let (c,_) = b -/ a in c > 0L

let rat_floor (a,b) = a//b
let rat_ceil (a,b) = (a++b--1L)//b

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

let () =
  let n = read_int () in
  let moves = long (read_int()) in
  let c = Array.init n (fun i -> long (read_int())) in

  Array.sort (fun a b -> compare b a) c;
  for i=0 to n-1 do
    c.(i) <- c.(i) -- c.(n-1)
  done;

  if c.(0) = c.(n-1) then printf "0\n"
  else if moves = 0L then printf "%Ld\n" c.(0)
  else
    let make_height_vol_list n c flip =
      let get i = if flip then c.(n-i-1) else c.(i) in
      let rec scan i v ac = if i=n then ac
	else
	  let d = abs ((get (i-1)) -- (get i)) in
	  if d = 0L then scan (i+1) v ac
	  else
	    let v = v ++ d ** (long i) in
	    let ac = (v, get i) :: ac in
	    scan (i+1) v ac
      in

      Array.of_list (List.rev (scan 1 0L [(0L, get 0)]))
    in

    let givefunct = make_height_vol_list n c false in
    let ng =  Array.length givefunct in

    let takefunct = make_height_vol_list n c true in
    let nt = Array.length takefunct in

    let eval funct n x =
      let rec bsearch lo hi =
	(* x is in the interval [funct.(lo), funct.(hi)] *)
	if lo+1 = hi then (lo, hi)
	else
	  let m = (lo+hi)/2 in
	  if x <= fst funct.(m) then bsearch lo m else bsearch m hi
      in
      if x > fst funct.(n-1) then failwith "bad eval"
      else
	let (lo,hi) = bsearch 0 (n-1) in
	let (x1,y1) = funct.(lo) in
	let (x2,y2) = funct.(hi) in
	let a = x -- x1 in
	let b = x2 -- x in
	normalize (y1 ** b ++ y2 ** a, a ++ b)
    in

    let saturated =
      moves > fst givefunct.(ng-1)
      || moves > fst takefunct.(nt-1)
      || (eval givefunct ng moves) </ (eval takefunct nt moves)
    in

    if not saturated then (
      let y1 = eval givefunct ng moves in
      let y2 = eval takefunct nt moves in
      let height_hi = rat_ceil y1 in
      let height_lo = rat_floor y2 in
      printf "%Ld\n" (height_hi -- height_lo)
    ) else (
    (* now we find the crossover point *)
      let rec bsearch lo hi =
      (* givefunct(lo) > takefunct(lo) && givefunct(hi) <= takefunct(hi) *)
	if lo ++ 1L = hi then hi
	else
	  let m = (lo ++ hi) // 2L in
	  let y1 = eval givefunct ng m in
	  let y2 = eval takefunct nt m in
	  if y2 </ y1 then bsearch m hi else bsearch lo m
      in
      let hi = min (fst givefunct.(ng-1)) (fst takefunct.(nt-1)) in
      let vol = bsearch 0L hi  in
      let y1 = eval givefunct ng vol in
      let y2 = eval takefunct nt vol in
      let (y1,y2) = if y1 = y2 then (y1,y2) else
	  let y1 = eval givefunct ng (vol--1L) in
	  let y2 = eval takefunct nt (vol--1L) in
	  (y1,y2)
      in
      let height_hi = rat_ceil y1 in
      let height_lo = rat_floor y2 in
      printf "%Ld\n" (height_hi -- height_lo)
    )


Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck!

The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000.

Format the given text, aligning it center. Frame the whole text with characters «*» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better.

welcome to the
Codeforces
Beta
Round 5

and
good luck

let read _ =
  let rec go acc =
    try
      go (read_line ()::acc)
    with End_of_file ->
      List.rev acc
  in go []

let () =
  let xs = read 0 in
  let m = List.fold_left (fun m a -> max m (String.length a)) 0 xs in
  let banner = String.make (m+2) '*' in
  print_endline banner;
  List.fold_left (fun c a ->
    let pad = m - String.length a in
    if pad mod 2 = 0 then (
      Printf.printf "*%*s%s%*s*\n" (pad/2) "" a (pad/2) "";
      c
    ) else if c then (
      Printf.printf "*%*s%s%*s*\n" (pad/2+1) "" a (pad/2) "";
      false
    ) else (
      Printf.printf "*%*s%s%*s*\n" (pad/2) "" a (pad/2+1) "";
      true
    )
  ) false xs;
  print_endline banner


Caisa is going to have a party and he needs to buy the ingredients for a big chocolate cake. For that he is going to the biggest supermarket in town.Unfortunately, he has just s dollars for sugar. But that's not a reason to be sad, because there are n types of sugar in the supermarket, maybe he able to buy one. But that's not all. The supermarket has very unusual exchange politics: instead of cents the sellers give sweets to a buyer as a change. Of course, the number of given sweets always doesn't exceed 99, because each seller maximizes the number of dollars in the change (100 cents can be replaced with a dollar).Caisa wants to buy only one type of sugar, also he wants to maximize the number of sweets in the change. What is the maximum number of sweets he can get? Note, that Caisa doesn't want to minimize the cost of the sugar, he only wants to get maximum number of sweets as change.

The first line contains two space-separated integers n, s (1 ≤ n, s ≤ 100). The i-th of the next n lines contains two integers xi, yi (1 ≤ xi ≤ 100; 0 ≤ yi < 100), where xi represents the number of dollars and yi the number of cents needed in order to buy the i-th type of sugar.

Print a single integer representing the maximum number of sweets he can buy, or -1 if he can't buy any type of sugar.

NoteIn the first test sample Caisa can buy the fourth type of sugar, in such a case he will take 50 sweets as a change.

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

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

module Array = struct
  include ArrayLabels
  let fold_lefti ~f ~init arr =
    let acc = ref init in
    for i = 0 to Array.length arr - 1 do
      acc := f i !acc arr.(i)
    done;
    !acc
  ;;
end
module String = StringLabels ;;
module List  = struct
  include ListLabels ;;
  let rec repeat n a = if n = 0 then [] else a :: repeat (n - 1) a ;;
  let rec drop n a =
    if n = 0 then a
    else match a with
    | [] -> failwith "cannot take"
    | x :: xs -> drop (n - 1) xs ;;

  let init ~f n =
    let res = ref [] in
    for i = 0 to n - 1 do
      res := f i :: !res
    done;
    List.rev !res
  ;;
end ;;
module H = Hashtbl ;;

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

let solve n s ss =
  let max = Array.fold_left ~init:(-1) ss ~f:(fun acc (d, c) ->
    let cng = (if c = 0 then 0 else (100 - c)) in
    if s * 100 >= d * 100 + c && acc < cng then cng else acc) in
  pf "%d\n" max
;;

let () =
  sf "%d %d " (fun n s ->
    let ss = Array.init n ~f:(fun i -> sf "%d %d " (fun x y -> x, y)) in
    solve n s ss)
;;

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

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

module Array = struct
  include ArrayLabels
  let fold_lefti ~f ~init arr =
    let acc = ref init in
    for i = 0 to Array.length arr - 1 do
      acc := f i !acc arr.(i)
    done;
    !acc
  ;;
end
module String = StringLabels ;;
module List  = struct
  include ListLabels ;;
  let rec repeat n a = if n = 0 then [] else a :: repeat (n - 1) a ;;
  let rec drop n a =
    if n = 0 then a
    else match a with
    | [] -> failwith "cannot take"
    | x :: xs -> drop (n - 1) xs ;;

  let init ~f n =
    let res = ref [] in
    for i = 0 to n - 1 do
      res := f i :: !res
    done;
    List.rev !res
  ;;
end ;;
module H = Hashtbl ;;

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

let solve n s ss =
  let max = Array.fold_left ~init:(-1) ss ~f:(fun acc (d, c) ->
    if s * 100 > d * 100 + c && acc < (if c = 0 then 0 else (100 - c)) then 100 - c else acc) in
  pf "%d\n" max
;;

let () =
  sf "%d %d " (fun n s ->
    let ss = Array.init n ~f:(fun i -> sf "%d %d " (fun x y -> x, y)) in
    solve n s ss)
;;


First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other. For example, you should know linguistics very well. You learn a structure of Reberland language as foreign language. In this language words are constructed according to the following rules. First you need to choose the "root" of the word — some string which has more than 4 letters. Then several strings with the length 2 or 3 symbols are appended to this word. The only restriction —  it is not allowed to append the same string twice in a row. All these strings are considered to be suffixes of the word (this time we use word "suffix" to describe a morpheme but not the few last characters of the string as you may used to). Here is one exercise that you have found in your task list. You are given the word s. Find all distinct strings with the length 2 or 3, which can be suffixes of this word according to the word constructing rules in Reberland language. Two strings are considered distinct if they have different length or there is a position in which corresponding characters do not match. Let's look at the example: the word abacabaca is given. This word can be obtained in the following ways: , where the root of the word is overlined, and suffixes are marked by "corners". Thus, the set of possible suffixes for this word is {aca, ba, ca}.

The only line contains a string s (5 ≤ |s| ≤ 104) consisting of lowercase English letters.

On the first line print integer k — a number of distinct possible suffixes. On the next k lines print suffixes.  Print suffixes in lexicographical (alphabetical) order.

NoteThe first test was analysed in the problem statement. In the second example the length of the string equals 5. The length of the root equals 5, so no string can be used as a suffix.

open Printf
open Scanf

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)

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

  let valid2 = Array.make (n+1) false in
  let valid3 = Array.make (n+1) false in
  (* valid3.(k) means a block starting at k of length 3 is valid *)

  valid2.(n-2) <- true;
  valid3.(n-3) <- true;

  for k = n-4 downto 5 do
    let sk2x = String.sub s k 2 in
    let sk2y = String.sub s (k+2) 2 in
    let sk3x = String.sub s k 3 in
    let sk3y = if k+6 <= n then String.sub s (k+3) 3 else sk3x in
    let ans = sk2x <> sk2y && valid2.(k+2) in
    let ans = ans || valid3.(k+2) in
    valid2.(k) <- ans;
    let ans = sk3x <> sk3y && valid3.(k+3) in
    let ans = ans || valid2.(k+3) in
    valid3.(k) <- ans
  done;

  let stringlist = fold 5 (n-2) (
    fun i ac ->
      fold (i+2) (min n (i+3)) (
	fun j ac ->
	  let sx = String.sub s i (j-i) in
	  if j-i = 2 then (
	    if valid2.(i) then sx::ac else ac
	  ) else (
	    if valid3.(i) then sx::ac else ac
	  )
      ) ac
  ) [] in

  let stringlist = List.sort_uniq compare stringlist in

  printf "%d\n" (List.length stringlist);
  List.iter (printf "%s\n") stringlist

open Printf
open Scanf

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)

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

  let stringlist = fold 5 (n-2) (
    fun i ac ->
      fold (i+2) (min n (i+3)) (
	fun j ac ->
	  if j = n || j <= n-2 then (String.sub s i (j-i))::ac else ac
      ) ac
  ) [] in

  let stringlist = List.sort_uniq compare stringlist in

  printf "%d\n" (List.length stringlist);
  List.iter (printf "%s\n") stringlist

open Printf
open Scanf

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)

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

  let valid2 = Array.make (n+1) false in
  let valid3 = Array.make (n+1) false in
  (* valid3.(k) means a block starting at k of length 3 is valid *)

  valid2.(n-2) <- true;
  valid3.(n-3) <- true;

  for k = n-4 downto 5 do
    let sk2x = String.sub s k 2 in
    let sk2y = String.sub s (k+2) 2 in
    let sk3x = String.sub s k 3 in
    let sk3y = if k+5 <= n then String.sub s (k+3) 2 else "" in
    let ans = sk2x <> sk2y && valid2.(k+2) in
    let ans = ans || valid3.(k+2) in
    valid2.(k) <- ans;
    let ans = sk3x <> sk3y && valid3.(k+3) in
    let ans = ans || valid2.(k+3) in
    valid3.(k) <- ans
  done;

  let stringlist = fold 5 (n-2) (
    fun i ac ->
      fold (i+2) (min n (i+3)) (
	fun j ac ->
	  let sx = String.sub s i (j-i) in
	  if j-i = 2 then (
	    if valid2.(i) then sx::ac else ac
	  ) else (
	    if valid3.(i) then sx::ac else ac
	  )
      ) ac
  ) [] in

  let stringlist = List.sort_uniq compare stringlist in

  printf "%d\n" (List.length stringlist);
  List.iter (printf "%s\n") stringlist

open Printf
open Scanf

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)

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

  let valid2 = Array.make (n+1) false in
  let valid3 = Array.make (n+1) false in
  (* valid3.(k) means a block starting at k of length 3 is valid *)

  valid2.(n-2) <- true;
  valid3.(n-3) <- true;

  for k = n-4 downto 5 do
    let sk2x = String.sub s k 2 in
    let sk2y = String.sub s (k+2) 2 in
    let sk3x = String.sub s k 3 in
    let sk3y = if k+5 <= n then String.sub s (k+3) 2 else sk3x in
    let ans = sk2x <> sk2y && valid2.(k+2) in
    let ans = ans || valid3.(k+2) in
    valid2.(k) <- ans;
    let ans = sk3x <> sk3y && valid3.(k+3) in
    let ans = ans || valid2.(k+3) in
    valid3.(k) <- ans
  done;

  let stringlist = fold 5 (n-2) (
    fun i ac ->
      fold (i+2) (min n (i+3)) (
	fun j ac ->
	  let sx = String.sub s i (j-i) in
	  if j-i = 2 then (
	    if valid2.(i) then sx::ac else ac
	  ) else (
	    if valid3.(i) then sx::ac else ac
	  )
      ) ac
  ) [] in

  let stringlist = List.sort_uniq compare stringlist in

  printf "%d\n" (List.length stringlist);
  List.iter (printf "%s\n") stringlist


A boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sheet with n rows and m columns. Bob shaded some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives in Flatland. Now Bob has to send his picture by post, but because of the world economic crisis and high oil prices, he wants to send his creation, but to spend as little money as possible. For each sent square of paper (no matter whether it is shaded or not) Bob has to pay 3.14 burles. Please, help Bob cut out of his masterpiece a rectangle of the minimum cost, that will contain all the shaded squares. The rectangle's sides should be parallel to the sheet's sides.

The first line of the input data contains numbers n and m (1 ≤ n, m ≤ 50), n — amount of lines, and m — amount of columns on Bob's sheet. The following n lines contain m characters each. Character «.» stands for a non-shaded square on the sheet, and «*» — for a shaded square. It is guaranteed that Bob has shaded at least one square.

Output the required rectangle of the minimum cost. Study the output data in the sample tests to understand the output format better.

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

let () =
  let n = read_int 0 in
  let m = read_int 0 in
  let a = Array.init n read_str in
  let u = ref n and b = ref 0 and l = ref m and r = ref 0 in
  for i = 0 to n-1 do
    for j = 0 to m-1 do
      if a.(i).[j]='*' then (
        u := min !u i;
        b := max !b i;
        l := min !l j;
        r := max !r j
      )
    done
  done;
  for i = !u to !b do
    for j = !l to !r do
      print_char a.(i).[j]
    done;
    print_char '\n'
  done


Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has $$$a$$$ coins, Barbara has $$$b$$$ coins and Cerene has $$$c$$$ coins. Recently Polycarp has returned from the trip around the world and brought $$$n$$$ coins.He wants to distribute all these $$$n$$$ coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives $$$A$$$ coins to Alice, $$$B$$$ coins to Barbara and $$$C$$$ coins to Cerene ($$$A+B+C=n$$$), then $$$a + A = b + B = c + C$$$.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all $$$n$$$ coins between sisters in a way described above.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. Each test case is given on a new line and consists of four space-separated integers $$$a, b, c$$$ and $$$n$$$ ($$$1 \le a, b, c, n \le 10^8$$$) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.

For each test case, print "YES" if Polycarp can distribute all $$$n$$$ coins between his sisters and "NO" otherwise.

open! Printf;;

module String = struct
	include String
	let split c str =
		let str = String.concat "" [str; String.make 1 c] in
		let cur = ref [] in
		let res = ref [] in
		String.iter (fun a ->
			match a = c with
			| false -> cur := (String.make 1 a) :: !cur
			| true ->
				let char_list = List.rev (!cur) in
				res := (String.concat "" char_list) :: !res;
				cur := []) str ;
			List.rev !res
	;;

end;;

let test_num = read_int () in
for _i = 1 to test_num do
	let input = read_line () |> String.split ' ' |> List.map int_of_string in
	match input with
	| [a; b; c; n] ->
		let max = List.fold_left max a [a; b; c] in
		let rest = n - 3*max + a + b + c in
		(match rest >= 0, rest mod 3 = 0 with
		| false, _
		| true, false ->  print_endline "NO"
		| true, true -> print_endline "YES")
	| _ -> assert false
done

module String = struct
	include String
	let split c str =
		let str = String.concat "" [str; String.make 1 c] in
		let cur = ref [] in
		let res = ref [] in
		String.iter (fun a ->
			match a = c with
			| false -> cur := (String.make 1 a) :: !cur
			| true ->
				let char_list = List.rev (!cur) in
				res := (String.concat "" char_list) :: !res;
				cur := []) str ;
			!res
	;;

end;;

let test_num = read_int () in
for _i = 1 to test_num do
	let input = read_line () |> String.split ' ' |> List.map int_of_string in
	match input with
	| [a; b; c; n] ->
		let max = List.fold_left max a [a; b; c] in
		let rest = n - 3*max + a + b + c in
		(match rest >= 0, rest mod 3 = 0 with
		| false, _
		| true, false ->  print_endline "NO"
		| true, true -> print_endline "YES")
	| _ -> assert false
done


You have integer $$$n$$$. Calculate how many ways are there to fully cover belt-like area of $$$4n-2$$$ triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. $$$2$$$ coverings are different if some $$$2$$$ triangles are covered by the same diamond shape in one of them and by different diamond shapes in the other one.Please look at pictures below for better understanding.  On the left you can see the diamond shape you will use, and on the right you can see the area you want to fill. These are the figures of the area you want to fill for $$$n = 1, 2, 3, 4$$$. You have to answer $$$t$$$ independent test cases.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^{4}$$$) — the number of test cases. Each of the next $$$t$$$ lines contains a single integer $$$n$$$ ($$$1 \le n \le 10^{9}$$$).

For each test case, print the number of ways to fully cover belt-like area of $$$4n-2$$$ triangles using diamond shape. It can be shown that under given constraints this number of ways doesn't exceed $$$10^{18}$$$.

NoteIn the first test case, there are the following $$$2$$$ ways to fill the area:  In the second test case, there is a unique way to fill the area:

let scan_int () = Scanf.scanf " %d" (fun x -> x);;
let show_int n = Printf.printf "%d\n" n;;

let t = scan_int ();;
for x = 1 to t do
	let n = scan_int () in
	show_int n
done;;

open Printf
open Scanf

let read_int _ = bscanf Scanning.stdin " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdin " %d %d " (fun x y -> (x,y))
let () =
  let cases = read_int() in
  for case = 1 to cases do
    let n = read_int() in
    printf "%d\n" n
  done


Nastya came to her informatics lesson, and her teacher who is, by the way, a little bit famous here gave her the following task.Two matrices $$$A$$$ and $$$B$$$ are given, each of them has size $$$n \times m$$$. Nastya can perform the following operation to matrix $$$A$$$ unlimited number of times:   take any square square submatrix of $$$A$$$ and transpose it (i.e. the element of the submatrix which was in the $$$i$$$-th row and $$$j$$$-th column of the submatrix will be in the $$$j$$$-th row and $$$i$$$-th column after transposing, and the transposed submatrix itself will keep its place in the matrix $$$A$$$). Nastya's task is to check whether it is possible to transform the matrix $$$A$$$ to the matrix $$$B$$$.    Example of the operation As it may require a lot of operations, you are asked to answer this question for Nastya.A square submatrix of matrix $$$M$$$ is a matrix which consist of all elements which comes from one of the rows with indeces $$$x, x+1, \dots, x+k-1$$$ of matrix $$$M$$$ and comes from one of the columns with indeces $$$y, y+1, \dots, y+k-1$$$ of matrix $$$M$$$. $$$k$$$ is the size of square submatrix. In other words, square submatrix is the set of elements of source matrix which form a solid square (i.e. without holes).

The first line contains two integers $$$n$$$ and $$$m$$$ separated by space ($$$1 \leq n, m \leq 500$$$) — the numbers of rows and columns in $$$A$$$ and $$$B$$$ respectively. Each of the next $$$n$$$ lines contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th of these lines denotes the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$A$$$ ($$$1 \leq A_{ij} \leq 10^{9}$$$). Each of the next $$$n$$$ lines contains $$$m$$$ integers, the $$$j$$$-th number in the $$$i$$$-th of these lines denotes the $$$j$$$-th element of the $$$i$$$-th row of the matrix $$$B$$$ ($$$1 \leq B_{ij} \leq 10^{9}$$$).

Print "YES" (without quotes) if it is possible to transform $$$A$$$ to $$$B$$$ and "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).

NoteConsider the third example. The matrix $$$A$$$ initially looks as follows.$$$$$$ \begin{bmatrix} 1 & 2 & 3\\ 4 & 5 & 6\\ 7 & 8 & 9 \end{bmatrix} $$$$$$Then we choose the whole matrix as transposed submatrix and it becomes$$$$$$ \begin{bmatrix} 1 & 4 & 7\\ 2 & 5 & 8\\ 3 & 6 & 9 \end{bmatrix} $$$$$$Then we transpose the submatrix with corners in cells $$$(2, 2)$$$ and $$$(3, 3)$$$. $$$$$$ \begin{bmatrix} 1 & 4 & 7\\ 2 & \textbf{5} & \textbf{8}\\ 3 & \textbf{6} & \textbf{9} \end{bmatrix} $$$$$$So matrix becomes$$$$$$ \begin{bmatrix} 1 & 4 & 7\\ 2 & 5 & 6\\ 3 & 8 & 9 \end{bmatrix} $$$$$$and it is $$$B$$$.

open Printf
open Scanf

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

let rec iterate i n f =
  if i > n
  then []
  else (f i) :: iterate (i+1) n f

let diagonal_sort a n m =
  let rec f i k =
    if i > k
    then []
    else if i < n && k - i < m
    then a.(i).(k-i) :: f (i+1) k
    else f (i+1) k in
  iterate 0 (n+m-2) (fun k -> List.fast_sort (fun x y -> x - y) @@ f 0 k)

let () =
  let n = read_int () in
  let m = read_int () in
  let a = Array.(init n (fun _ -> init m read_int)) in
  let b = Array.(init n (fun _ -> init m read_int)) in
  let ans =
    if diagonal_sort a n m = diagonal_sort b n m
    then "YES"
    else "NO" in
  printf "%s\n" ans


In the capital city of Berland, Bertown, demonstrations are against the recent election of the King of Berland. Berland opposition, led by Mr. Ovalny, believes that the elections were not fair enough and wants to organize a demonstration at one of the squares.Bertown has n squares, numbered from 1 to n, they are numbered in the order of increasing distance between them and the city center. That is, square number 1 is central, and square number n is the farthest from the center. Naturally, the opposition wants to hold a meeting as close to the city center as possible (that is, they want an square with the minimum number).There are exactly k (k < n) days left before the demonstration. Now all squares are free. But the Bertown city administration never sleeps, and the approval of an application for the demonstration threatens to become a very complex process. The process of approval lasts several days, but every day the following procedure takes place:  The opposition shall apply to hold a demonstration at a free square (the one which isn't used by the administration).  The administration tries to move the demonstration to the worst free square left. To do this, the administration organizes some long-term activities on the square, which is specified in the application of opposition. In other words, the administration starts using the square and it is no longer free. Then the administration proposes to move the opposition demonstration to the worst free square. If the opposition has applied for the worst free square then request is accepted and administration doesn't spend money. If the administration does not have enough money to organize an event on the square in question, the opposition's application is accepted. If administration doesn't have enough money to organize activity, then rest of administration's money spends and application is accepted  If the application is not accepted, then the opposition can agree to the administration's proposal (that is, take the worst free square), or withdraw the current application and submit another one the next day. If there are no more days left before the meeting, the opposition has no choice but to agree to the proposal of City Hall. If application is accepted opposition can reject it. It means than opposition still can submit more applications later, but square remains free. In order to organize an event on the square i, the administration needs to spend ai bourles. Because of the crisis the administration has only b bourles to confront the opposition. What is the best square that the opposition can take, if the administration will keep trying to occupy the square in question each time? Note that the administration's actions always depend only on the actions of the opposition.

The first line contains two integers n and k — the number of squares and days left before the meeting, correspondingly (1 ≤ k < n ≤ 105). The second line contains a single integer b — the number of bourles the administration has (1 ≤ b ≤ 1018). The third line contains n space-separated integers ai — the sum of money, needed to organise an event on square i (1 ≤ ai ≤ 109). 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.

Print a single number — the minimum number of the square where the opposition can organize the demonstration.

NoteIn the first sample the opposition can act like this. On day one it applies for square 3. The administration has to organize an event there and end up with 3 bourles. If on the second day the opposition applies for square 2, the administration won't have the money to intervene.In the second sample the opposition has only the chance for the last square. If its first move occupies one of the first four squares, the administration is left with at least 4 bourles, which means that next day it can use its next move to move the opposition from any square to the last one.In the third sample administration has a lot of money, so opposition can occupy only last square.

module IntPairSet = Set.Make(
  struct
    type t = int * int
    (*let compare ((x, x') : int * int) (y, y') =
      if x < y
      then -1
      else if x > y
      then 1
      else 0*)
    let compare = compare
  end
)

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let b = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let a = Array.make n 0 in
  let () =
    for i = 0 to n - 1 do
      let k = Scanf.bscanf sb "%d " (fun s -> s) in
	a.(i) <- k
    done;
  in
  let res = ref (n - 1) in
  let ss = ref IntPairSet.empty in
  let s = ref 0L in
  let c = ref 0 in
    for i = n - 2 downto 0 do
      if Int64.add !s (Int64.of_int a.(i)) > b
      then res := i;
      ss := IntPairSet.add (a.(i), i) !ss;
      s := Int64.add !s (Int64.of_int a.(i));
      incr c;
      if !c > k - 1 then (
	let e = IntPairSet.min_elt !ss in
	let v = fst e in
	  ss := IntPairSet.remove e !ss;
	  s := Int64.sub !s (Int64.of_int v);
	  decr c;
      )
    done;
      Printf.printf "%d\n" (!res + 1);

module IntPairSet = Set.Make(
  struct
    type t = int * int
    let compare ((x, x') : int * int) (y, y') =
      if x < y
      then -1
      else if x > y
      then 1
      else 0
  end
)

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let b = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let a = Array.make n 0 in
  let () =
    for i = 0 to n - 1 do
      let k = Scanf.bscanf sb "%d " (fun s -> s) in
	a.(i) <- k
    done;
  in
  let res = ref (n - 1) in
  let ss = ref IntPairSet.empty in
  let s = ref 0L in
  let c = ref 0 in
    for i = n - 1 downto 0 do
      if Int64.add !s (Int64.of_int a.(i)) > b
      then res := i;
      ss := IntPairSet.add (a.(i), i) !ss;
      s := Int64.add !s (Int64.of_int a.(i));
      incr c;
      if !c > k - 1 then (
	let e = IntPairSet.min_elt !ss in
	let v = fst e in
	  ss := IntPairSet.remove e !ss;
	  s := Int64.sub !s (Int64.of_int v);
	  decr c;
      )
    done;
      Printf.printf "%d\n" (!res + 1);

module IntPairSet = Set.Make(
  struct
    type t = int * int
    let compare ((x, x') : int * int) (y, y') =
      if x < y
      then -1
      else if x > y
      then 1
      else 0
  end
)

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let b = Scanf.bscanf sb "%Ld " (fun s -> s) in
  let a = Array.make n 0 in
  let () =
    for i = 0 to n - 1 do
      let k = Scanf.bscanf sb "%d " (fun s -> s) in
	a.(i) <- k
    done;
  in
  let res = ref (n - 1) in
  let ss = ref IntPairSet.empty in
  let s = ref 0L in
  let c = ref 0 in
    for i = n - 2 downto 0 do
      if Int64.add !s (Int64.of_int a.(i)) > b
      then res := i;
      ss := IntPairSet.add (a.(i), i) !ss;
      s := Int64.add !s (Int64.of_int a.(i));
      incr c;
      if !c > k - 1 then (
	let e = IntPairSet.min_elt !ss in
	let v = fst e in
	  ss := IntPairSet.remove e !ss;
	  s := Int64.sub !s (Int64.of_int v);
	  decr c;
      )
    done;
      Printf.printf "%d\n" (!res + 1);


Having read half of the book called "Storm and Calm" on the IT lesson, Innocentius was absolutely determined to finish the book on the maths lessons. All was fine until the math teacher Ms. Watkins saw Innocentius reading fiction books instead of solving equations of the fifth degree. As during the last maths class Innocentius suggested the algorithm of solving equations of the fifth degree in the general case, Ms. Watkins had no other choice but to give him a new task.The teacher asked to write consecutively (without spaces) all words from the "Storm and Calm" in one long string s. She thought that a string is good if the number of vowels in the string is no more than twice more than the number of consonants. That is, the string with v vowels and c consonants is good if and only if v ≤ 2c.The task Innocentius had to solve turned out to be rather simple: he should find the number of the longest good substrings of the string s.

The only input line contains a non-empty string s consisting of no more than 2·105 uppercase and lowercase Latin letters. We shall regard letters "a", "e", "i", "o", "u" and their uppercase variants as vowels.

Print on a single line two numbers without a space: the maximum length of a good substring and the number of good substrings with this length. If no good substring exists, print "No solution" without the quotes. Two substrings are considered different if their positions of occurrence are different. So if some string occurs more than once, then it should be counted more than once.

Abo OEIS auBAAbeelii AaaBRAaaCAaaDAaaBRAaa EA

NoteIn the first sample there is only one longest good substring: "Abo" itself. The other good substrings are "b", "Ab", "bo", but these substrings have shorter length.In the second sample there is only one longest good substring: "EIS". The other good substrings are: "S", "IS".

let getint () = Scanf.scanf " %d" (fun i->i)
let getstr () = Scanf.bscanf Scanf.Scanning.stdin "%s" (fun s -> s)
let getval c=
  match c with
    | 'a' | 'e' | 'i' | 'o' | 'u' -> -1
    | _ -> 2

let _ =
  let s = String.lowercase (getstr ()) in
  let n = String.length s in
  let mn = ref 0 in
  let res = ref ~-1 in
  let mxSub  = Array.make 200200 0 in
  let prefix = Array.make 200200 0 in
  let getsum i j = prefix.(j) - (if i=0 then 0 else prefix.(i-1)) in
    for i = 0 to n-1 do
      prefix.(i) <- getval s.[i] + (if i=0 then 0 else prefix.(i-1));
    done;
    for i = 0 to n-1 do
      mxSub.(i) <- prefix.(i) - !mn;
      mn := min !mn prefix.(i);
      let lo = ref 0 and hi = ref i and ans = ref ~-1 in
        while !lo <= !hi do
          let mid = (!lo + !hi) / 2 in
            let right = getsum mid i
            and left = max 0 (if mid=0 then 0 else mxSub.(mid-1)) in
              if left+right>=0 then (ans:= mid; hi := mid-1)
              else lo := mid+1
        done;
        if !ans <> -1 then res := max !res (i - !ans + 1)
    done;
    if !res= -1 then Printf.printf "No solution\n"
    else
      begin
        let cnt = ref 0 in
          for i = 0 to n - !res do
            if getsum i (i + !res - 1)  >=0
            then cnt := !cnt + 1
          done;
          Printf.printf "%d %d\n" !res !cnt
      end

let main() =
  let f = function
    'a' | 'e' | 'i' | 'o' | 'u' -> -1
  | _ -> 2
    in
  let s = Scanf.scanf "%s" String.lowercase in
  let n = String.length s in
  let a = Array.init n (fun i -> (f s.[i])) in
  let b = Array.create (n+1) 0 in
  Array.iteri (fun i x -> b.(i+1) <- b.(i) + x) a;
  let c = Array.mapi (fun i x -> x, i) b in
  Array.stable_sort (fun x y -> compare (fst x) (fst y)) c;
  let rec g k j maxl tot =
    if k < 0 then maxl, tot
    else
      let i = snd c.(k) in
      if i > j then g (k-1) i maxl tot
      else (
        let l = j - i in
        if l < maxl then g (k-1) j maxl tot
        else g (k-1) j l (if l == maxl then (tot+1) else 1)
      )
    in
  let r,v = g n 0 0 0 in
  if r > 0 then Printf.printf "%d %d\n" r v else Printf.printf "No solution\n"
  ;;
main()

let min (x : int) y = if x < y then x else y

let fr n = n + (n land (-n))
let fl n = n land (n - 1)

let fenwick_new n =
  Array.make (n + 1) 1000000000

let fenwick_modify ft n x =
  let i = ref n in
    while !i < Array.length ft do
      ft.(!i) <- min ft.(!i) x;
      i := fr !i;
    done

let fenwick_min ft n =
  let i = ref n in
  let res = ref 1000000000 in
    while !i > 0 do
      res := min !res ft.(!i);
      i := fl !i;
    done;
    !res

let _ =
  let sb = Scanf.Scanning.stdib in
  let s = Scanf.bscanf sb "%s " (fun s -> s) in
  let n = String.length s in
  let ft = fenwick_new 800000 in
  let sum = ref 300000 in
  let res = ref (-1) in
  let a = Array.make (n + 1) !sum in
    fenwick_modify ft !sum 0;
    for i = 0 to n - 1 do
      let c = s.[i] in
	(match c with
	   | 'a' | 'e' | 'i' | 'o' | 'u'
	   | 'A' | 'E' | 'I' | 'O' | 'U' ->
	       decr sum;
	   | _ ->
	       sum := !sum + 2
	);
	let l = fenwick_min ft !sum in
	  (*Printf.printf "asd %d %d %d\n" i !sum l;*)
	  if l < 1000000000 && i + 1 - l > !res then (
	    res := i + 1 - l
	  );
	  fenwick_modify ft !sum (i + 1);
	  a.(i + 1) <- !sum
    done;
    if !res < 0
    then Printf.printf "No solution\n"
    else (
      let c = ref 0 in
	for i = !res to n do
	  if a.(i) - a.(i - !res) >= 0
	  then incr c
	done;
	Printf.printf "%d %d\n" !res !c;
    )

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

let s = String.lowercase (read_string ())
let n = String.length s

let start = n

let leftmost = Array.init (3*n+1) (fun i -> if i>=start then 0 else max_int/2)

let is_vowel c = match c with 'a' | 'e' | 'i' | 'o' | 'u' -> true | _ -> false

(* we've processed chars 0,1,2...i-1, and have the height and best for that *)
let rec fill_leftmost i height best = if i=n then (height,best) else
  if is_vowel s.[i] then (
    leftmost.(height-1) <- min leftmost.(height-1) (i+1);
    fill_leftmost (i+1) (height-1) (max best (i+1-leftmost.(height-1)))
  ) else (
    leftmost.(height+1) <- min leftmost.(height+1) i;
    leftmost.(height+2) <- min leftmost.(height+2) (i+1);
    fill_leftmost (i+1) (height+2) (max best (i+1-leftmost.(height+2)))
  )

let (height,best) = fill_leftmost 0 start 0

let rec complete h b = if h<0 then b else
  complete (h-1) (max b (n - leftmost.(h)))

let best = complete height best

let cvowel i = if is_vowel s.[i] then 1 else 0

(* vow for the range i....i+best-1, count for the previous one *)
let rec count_strings i count vow =
  let count = count + (if vow<=2*(best-vow) then 1 else 0) in
  if i+best-1 = n-1 then count else
    let vow = vow - (cvowel i) + (cvowel (i+best)) in
      count_strings (i+1) count vow

let rec count_vow i count =
  if i=best then count else count_vow (i+1) (count + (cvowel i))

let () =
  if best = 0
  then Printf.printf "No solution\n"
  else Printf.printf "%d %d\n" best (count_strings 0 0 (count_vow 0 0))

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

let s = String.lowercase (read_string ())
let n = String.length s

let start = n

let leftmost = Array.init (3*n+1) (fun i -> if i>=start then 0 else max_int/2)

let is_vowel c = match c with 'a' | 'e' | 'i' | 'o' | 'u' -> true | _ -> false

(* we've processed chars 0,1,2...i-1, and have the height and best for that *)
let rec fill_leftmost i height bc = if i=n then bc else
  let best_count (b,c) nb = if nb < b then (b,c) else if nb = b then (b,c+1) else (nb, 1) in
  if is_vowel s.[i] then (
    leftmost.(height-1) <- min leftmost.(height-1) (i+1);
    fill_leftmost (i+1) (height-1) (best_count bc (i+1-leftmost.(height-1)))
  ) else (
    leftmost.(height+1) <- min leftmost.(height+1) i;
    leftmost.(height+2) <- min leftmost.(height+2) (i+1);
    fill_leftmost (i+1) (height+2) (best_count bc (i+1-leftmost.(height+2)))
  )

let (best,count) = fill_leftmost 0 start (0,1)

let () =
  if best = 0
  then Printf.printf "No solution\n"
  else Printf.printf "%d %d\n" best count

let main() =
  let f = function
    'a' | 'e' | 'i' | 'o' | 'u' | 'y' -> -1
  | _ -> 2
    in
  let s = Scanf.scanf "%s" String.lowercase in
  let n = String.length s in
  let a = Array.init n (fun i -> (f s.[i])) in
  let b = Array.create (n+1) 0 in
  Array.iteri (fun i x -> b.(i+1) <- b.(i) + x) a;
  let c = Array.mapi (fun i x -> x, i) b in
  Array.stable_sort (fun x y -> compare (fst x) (fst y)) c;
  let rec g k j maxl tot =
    if k < 0 then maxl, tot
    else
      let i = snd c.(k) in
      if i > j then g (k-1) i maxl tot
      else (
        let l = j - i in
        if l < maxl then g (k-1) j maxl tot
        else g (k-1) j l (if l == maxl then (tot+1) else 1)
      )
    in
  let r,v = g n 0 0 0 in
  if r > 0 then Printf.printf "%d %d\n" r v else Printf.printf "No solution\n"
  ;;
main()

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

let s = String.lowercase (read_string ())
let n = String.length s

let start = n

let leftmost = Array.init (3*n+1) (fun i -> if i>=start then 0 else max_int/2)

let is_vowel c = match c with 'a' | 'e' | 'i' | 'o' | 'u' -> true | _ -> false

(* we've processed chars 0,1,2...i-1, and have the height and best for that *)
let rec fill_leftmost i height best = if i=n then (height,best) else
  if is_vowel s.[i] then (
    leftmost.(height-1) <- min leftmost.(height-1) (i+1);
    fill_leftmost (i+1) (height-1) (max best (i+1-leftmost.(height-1)))
  ) else (
    leftmost.(height+1) <- min leftmost.(height+1) i;
    leftmost.(height+2) <- min leftmost.(height+2) (i+1);
    fill_leftmost (i+1) (height+2) (max best (i+1-leftmost.(height+2)))
  )

let (height,best) = fill_leftmost 0 start 0

let rec complete h b = if h<0 then b else
  complete (h-1) (max b (n - leftmost.(h)))

let best = complete height best

let cvowel i = if is_vowel s.[i] then 1 else 0

(* vow for the range i....i+best-1, count for the previous one *)
let rec count_strings i count vow =
  let count = count + (if vow<=2*(best-vow) then 1 else 0) in
  if i+best-1 = n-1 then count else
    let vow = vow - (cvowel i) + (cvowel (i+best)) in
      count_strings (i+1) count vow

let rec count_vow i count =
  if i=best then count else count_vow (i+1) (count + (cvowel i))

;;

Printf.printf "%d %d\n" best (count_strings 0 0 (count_vow 0 0))


You are playing another computer game, and now you have to slay $$$n$$$ monsters. These monsters are standing in a circle, numbered clockwise from $$$1$$$ to $$$n$$$. Initially, the $$$i$$$-th monster has $$$a_i$$$ health.You may shoot the monsters to kill them. Each shot requires exactly one bullet and decreases the health of the targeted monster by $$$1$$$ (deals $$$1$$$ damage to it). Furthermore, when the health of some monster $$$i$$$ becomes $$$0$$$ or less than $$$0$$$, it dies and explodes, dealing $$$b_i$$$ damage to the next monster (monster $$$i + 1$$$, if $$$i < n$$$, or monster $$$1$$$, if $$$i = n$$$). If the next monster is already dead, then nothing happens. If the explosion kills the next monster, it explodes too, damaging the monster after it and possibly triggering another explosion, and so on.You have to calculate the minimum number of bullets you have to fire to kill all $$$n$$$ monsters in the circle.

The first line contains one integer $$$T$$$ ($$$1 \le T \le 150000$$$) — the number of test cases. Then the test cases follow, each test case begins with a line containing one integer $$$n$$$ ($$$2 \le n \le 300000$$$) — the number of monsters. Then $$$n$$$ lines follow, each containing two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^{12}$$$) — the parameters of the $$$i$$$-th monster in the circle. It is guaranteed that the total number of monsters in all test cases does not exceed $$$300000$$$.

For each test case, print one integer — the minimum number of bullets you have to fire to kill all of the monsters.

open Printf
open Scanf

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

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

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

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

  for case = 1 to cases do
    let n = read_int () in
    let a = Array.make n 0L in
    let b = Array.make n 0L in
    let need = Array.make n 0L in
    for i=0 to n-1 do
      a.(i) <- read_long();
      b.(i) <- read_long()
    done;

    let needtot = ref 0L in
    for i=0 to n-1 do
      need.(i) <- max 0L (a.(i) -- b.((i+n-1) mod n));
      needtot := !needtot ++ need.(i)
    done;

    let starter = max 1L (minf 0 (n-1) (fun i -> a.(i) -- need.(i))) in

    printf "%Ld\n" (starter ++ !needtot)
  done


A permutation of length n is an array containing each integer from 1 to n exactly once. For example, q = [4, 5, 1, 2, 3] is a permutation. For the permutation q the square of permutation is the permutation p that p[i] = q[q[i]] for each i = 1... n. For example, the square of q = [4, 5, 1, 2, 3] is p = q2 = [2, 3, 4, 5, 1].This problem is about the inverse operation: given the permutation p you task is to find such permutation q that q2 = p. If there are several such q find any of them.

The first line contains integer n (1 ≤ n ≤ 106) — the number of elements in permutation p. The second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — the elements of permutation p.

If there is no permutation q such that q2 = p print the number "-1". If the answer exists print it. The only line should contain n different integers qi (1 ≤ qi ≤ n) — the elements of the permutation q. If there are several solutions print any of them.

open Scanf
open Printf

let length = Array.length
let print_array l = Array.iter (fun a -> printf "%d " (a+1)) l
let print_array2 l = Array.iter (fun a -> print_array a; print_newline ()) l
let square p =
    let n = Array.length p in
    Array.init n (fun a -> p.(p.(a)))

let read_int _ = scanf " %d" (fun x -> x)
let read_perm _ = scanf " %d" (fun x -> (x-1))
let read_array num =
    Array.init num read_perm

let add x l =
    l := (x :: !l)

type permutation = int array

let split_cycles ar =
    let n = Array.length ar in
    let visited = Array.make n false
    and out = ref [] in
    for i = 0 to n-1 do
        if not visited.(i) then
            begin
                let per = ref [] and x = ref i in
                while not visited.(!x) do
                    add (!x) per;
                    visited.(!x) <- true;
                    x := ar.(!x)
                done;
                let x = Array.of_list (List.rev !per)
                in add x out
            end
    done;
    Array.of_list !out

let cmp a b =
    Array.length a - Array.length b

let root_odd ar =
    let n = Array.length ar in
    let m = (n+1)/2 in
    assert (n mod 2 = 1);
    Array.init n (fun x -> if x mod 2 = 0 then ar.(x/2) else ar.(m + x/2))

let root_even a b =
    assert (Array.length a = Array.length b);
    assert (Array.length a mod 2 = 0);
    let n = Array.length a in
    Array.init (2*n) (fun x -> if x mod 2 = 0 then a.(x/2) else b.(x/2))

let get_answer ar = (* assume sorted *)
    let n = Array.length ar
    and i = ref 0
    and out = ref []
    and error = ref false in
    while !i < n do
        let l = Array.length ar.(!i) in
        if l mod 2 = 0 then
            begin
                if !i = n - 1 then (incr i; error := true)
                else if Array.length ar.(!i + 1) <> l then (i := n; error := true)
                else (add (root_even ar.(!i) ar.(!i + 1)) out; i := !i + 2)
            end
        else
            begin
                add (root_odd ar.(!i)) out;
                incr i
            end
    done;
    if !error then [||]
    else Array.of_list !out

let convert n ar =
    let out = Array.make n 0
    and k = Array.length ar in
    for i = 0 to k - 1 do
        let a = ar.(i) in
        let l = Array.length a in
        for j = 0 to l - 1 do
            if j = l - 1 then out.(a.(j)) <- a.(0)
            else out.(a.(j)) <- a.(j+1)
        done
    done;
    out

let n = read_int ()
let ar = read_array n
let cycles = split_cycles ar
let () = Array.sort cmp cycles
(*let () = print_array2 cycles; print_endline "===================="*)
let ans = get_answer cycles
let () =
    if ans = [||] then printf "-1\n"
    else
        let out = convert n ans in
        print_array out (*; print_string "\nSquare:\n"; print_array (square out) *)

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s) - 1
    done;
    let u = Array.make n false in
    let cs = ref [] in
    let _ =
      for i = 0 to n - 1 do
	if not u.(i) then (
	  let pos = ref i in
	  let c = ref [] in
	    while not u.(!pos) do
	      u.(!pos) <- true;
	      c := !pos :: !c;
	      pos := a.(!pos);
	    done;
	    let c = Array.of_list (List.rev !c) in
	      cs := (Array.length c, c) :: !cs
	)
      done;
    in
    let cs = Array.of_list !cs in
    let res = Array.make n 0 in
    let skip = ref false in
      Array.sort compare cs;
      for i = 0 to Array.length cs - 1 do
	if not !skip then (
	let (k, p) = cs.(i) in
(*Printf.printf "qwe %d\n" k;*)
	  if k mod 2 <> 0 then (
	    for j = 0 to k - 1 do
	      res.(p.(j)) <- p.((j + k / 2 + 1) mod k)
	    done;
	  ) else (
	    if i + 1 < Array.length cs && fst (cs.(i + 1)) = k then (
	      let (_, p') = cs.(i + 1) in
		for j = 0 to k - 1 do
(*Printf.printf "asd %d %d %d %d\n" i k p.(j) p'.(j);*)
		  res.(p.(j)) <- p'.(j);
		  res.(p'.(j)) <- p.((j + 1) mod k)
		done;
		skip := true;
	    ) else (
	      Printf.printf "-1\n";
	      exit 0;
	    )
	  )
	) else skip := false
      done;
      for i = 0 to n - 1 do
	Printf.printf "%d " (res.(i) + 1);
      done;
      Printf.printf "\n"

open Scanf
open Printf

let length = Array.length
let print_array l = Array.iter (fun a -> printf "%d " a) l
let print_array2 l = Array.iter (fun a -> print_array a; print_newline ()) l
let square p =
    let n = Array.length p in
    Array.init n (fun a -> p.(p.(a)-1))

let read_int _ = scanf " %d" (fun x -> x)
let read_array num =
    Array.init num read_int

let add x l =
    l := (x :: !l)

type permutation = int array

let split_cycles ar =
    let n = Array.length ar in
    let visited = Array.make n false
    and out = ref [] in
    for i = 0 to n-1 do
        if not visited.(i) then
            let per = ref [] and x = ref i in
            while not visited.(!x) do
                add (!x + 1) per;
                visited.(!x) <- true;
                x := ar.(!x) - 1
            done;
            let x = Array.of_list (List.rev !per)
            in add x out
    done;
    Array.of_list !out

let cmp a b =
    Array.length a - Array.length b

let root_odd ar =
    let n = Array.length ar in
    assert (n mod 2 = 1);
    Array.init n (fun a -> ar.(2*a mod n))

let root_even a b =
    assert (Array.length a = Array.length b);
    assert (Array.length a mod 2 = 0);
    let n = Array.length a in
    Array.init (2*n) (fun x -> if x mod 2 = 0 then a.(x/2) else b.(x/2))

let get_answer ar = (* assume sorted *)
    let n = Array.length ar
    and i = ref 0
    and out = ref []
    and error = ref false in
    while !i < n do
        let l = Array.length ar.(!i) in
        if l mod 2 = 0 then
            begin
                if !i = n - 1 then (incr i; error := true)
                else if Array.length ar.(!i + 1) <> l then (i := n; error := true)
                else (add (root_even ar.(!i) ar.(!i + 1)) out; i := !i + 2)
            end
        else
            begin
                add (root_odd ar.(!i)) out;
                incr i
            end
    done;
    if !error then [||]
    else Array.of_list !out

let convert n ar =
    let out = Array.make n 0
    and k = Array.length ar in
    for i = 0 to k - 1 do
        let a = ar.(i) in
        let l = Array.length a in
        for j = 0 to l - 1 do
            if j = l - 1 then out.(a.(j)-1) <- a.(0)
            else out.(a.(j)-1) <- a.(j+1)
        done
    done;
    out

let n = read_int ()
let ar = read_array n
let cycles = split_cycles ar
let () = Array.sort cmp cycles
(*let () = print_array2 cycles; print_endline "===================="*)
let ans = get_answer cycles
let () =
    if ans = [||] then printf "-1\n"
    else
        let out = convert n ans in
        print_array out (*; print_string "\nSquare:\n"; print_array (square out) *)

open Scanf
open Printf

let length = Array.length
let print_array l = Array.iter (fun a -> printf "%d " a) l
let print_array2 l = Array.iter (fun a -> print_array a; print_newline ()) l

let read_int _ = scanf " %d" (fun x -> x)
let read_array num =
    Array.init num read_int

let add x l =
    l := (x :: !l)

type permutation = int array

let split_cycles ar =
    let n = Array.length ar in
    let visited = Array.make n false
    and out = ref [] in
    for i = 0 to n-1 do
        if not visited.(i) then
            let per = ref [] and x = ref i in
            while not visited.(!x) do
                add (!x + 1) per;
                visited.(!x) <- true;
                x := ar.(!x) - 1
            done;
            let x = Array.of_list !per
            in add x out
    done;
    Array.of_list !out

let cmp a b =
    Array.length a - Array.length b

let root_odd ar =
    let n = Array.length ar in
    assert (n mod 2 = 1);
    Array.init n (fun a -> ar.(2*a mod n))

let root_even a b =
    assert (Array.length a = Array.length b);
    assert (Array.length a mod 2 = 0);
    let n = Array.length a in
    Array.init (2*n) (fun x -> if x mod 2 = 0 then a.(x/2) else b.(x/2))

let get_answer ar = (* assume sorted *)
    let n = Array.length ar
    and i = ref 0
    and out = ref []
    and error = ref false in
    while !i < n do
        let l = Array.length ar.(!i) in
        if l mod 2 = 0 then
            begin
                if !i = n - 1 then (incr i; error := true)
                else if Array.length ar.(!i + 1) <> l then (i := n; error := true)
                else (add (root_even ar.(!i) ar.(!i + 1)) out; i := !i + 2)
            end
        else
            begin
                add (root_odd ar.(!i)) out;
                incr i
            end
    done;
    if !error then [||]
    else Array.of_list !out

let convert n ar =
    let out = Array.make n 0
    and k = Array.length ar in
    for i = 0 to k - 1 do
        let a = ar.(i) in
        let l = Array.length a in
        for j = 0 to l - 1 do
            if j = l - 1 then out.(a.(j)-1) <- a.(0)
            else out.(a.(j)-1) <- a.(j+1)
        done
    done;
    out

let n = read_int ()
let ar = read_array n
let cycles = split_cycles ar
let _ = Array.sort cmp cycles
let ans = get_answer cycles
let () =
    if ans = [||] then printf "-1\n"
    else
        let out = convert n ans in
        print_array out


The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew.

The first line contains an integer n, which is the number of people in the crew (1 ≤ n ≤ 100). Then follow n lines. The i-th of those lines contains two words — the name of the crew member who is i-th in line, and his status on the ship. The words are separated by exactly one space. There are no other spaces in the line. The names consist of Latin letters, the first letter is uppercase, the rest are lowercase. The length of any name is from 1 to 10 characters. The status can have the following values: rat for a rat, woman for a woman, child for a child, man for a man, captain for the captain. The crew contains exactly one captain.

Print n lines. The i-th of them should contain the name of the crew member who must be the i-th one to leave the ship.

6
Jack captain
Alice woman
Charlie man
Teddy rat
Bob child
Julia woman

module Person = struct
	type t =
		Rat of string     |
		Woman of string   |
		Child of string   |
		Man of string     |
		Captain of string
	;;
	let priority = function
		| Rat _ -> 3
		| (Woman _|Child _) -> 2
		| Man _ -> 1
		| Captain _ -> 0
	;;
	let compare a b =
		priority b - priority a
	;;
	let of_string n t =
		match t with
		| "rat"     -> Rat n
		| "woman"   -> Woman n
		| "child"   -> Child n
		| "man"     -> Man n
		| "captain" -> Captain n
		| _ -> invalid_arg "Undefined rank"
	;;
	let to_string = function
		| Rat s -> s
		| Woman s -> s
		| Child s -> s
		| Man s -> s
		| Captain s -> s
	;;
end;;

let () =
	let n = read_int () in
	let persons = Array.init n (fun _ ->
		Scanf.scanf " %s %s" Person.of_string
	) in
	let _ = Array.stable_sort Person.compare persons in
		Array.iter (fun p ->
			Printf.printf "%s\n" (Person.to_string p)
		) persons
;;


Permutation $$$p$$$ is a sequence of integers $$$p=[p_1, p_2, \dots, p_n]$$$, consisting of $$$n$$$ distinct (unique) positive integers between $$$1$$$ and $$$n$$$, inclusive. For example, the following sequences are permutations: $$$[3, 4, 1, 2]$$$, $$$[1]$$$, $$$[1, 2]$$$. The following sequences are not permutations: $$$[0]$$$, $$$[1, 2, 1]$$$, $$$[2, 3]$$$, $$$[0, 1, 2]$$$.The important key is in the locked box that you need to open. To open the box you need to enter secret code. Secret code is a permutation $$$p$$$ of length $$$n$$$. You don't know this permutation, you only know the array $$$q$$$ of prefix maximums of this permutation. Formally:  $$$q_1=p_1$$$,  $$$q_2=\max(p_1, p_2)$$$,  $$$q_3=\max(p_1, p_2,p_3)$$$,  ...  $$$q_n=\max(p_1, p_2,\dots,p_n)$$$. You want to construct any possible suitable permutation (i.e. any such permutation, that calculated $$$q$$$ for this permutation is equal to the given array).

The first line contains integer number $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the input. Then $$$t$$$ test cases follow. The first line of a test case contains one integer $$$n$$$ $$$(1 \le n \le 10^{5})$$$ — the number of elements in the secret code permutation $$$p$$$. The second line of a test case contains $$$n$$$ integers $$$q_1, q_2, \dots, q_n$$$ $$$(1 \le q_i \le n)$$$ — elements of the array $$$q$$$ for secret permutation. It is guaranteed that $$$q_i \le q_{i+1}$$$ for all $$$i$$$ ($$$1 \le i < n$$$). The sum of all values $$$n$$$ over all the test cases in the input doesn't exceed $$$10^5$$$.

For each test case, print:   If it's impossible to find such a permutation $$$p$$$, print "-1" (without quotes).  Otherwise, print $$$n$$$ distinct integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$). If there are multiple possible answers, you can print any of them.

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

let rec to_set m =
  if m = 0 then
    []
  else
    m::(to_set (m-1))

let previous = ref (-1)
let rec remove x l =
  match l with
  | [] -> assert false
  | y::l -> if x = y then l
    else
      y::(remove x l)

let rec find_perm l p cand s =
  match l with
  | [] -> p
  | x::l ->
    let cand',y =
      if x = !previous && !previous <> -1 then
        let rec find = function
            | [] -> failwith "Oops"
            | y::l ->
              if y <= x then
                if IS.mem y s then find l else l,y
              else
                failwith "Oops"
        in find cand
      else
        cand,x
    in
    previous := x;
    find_perm l (y::p) cand' (IS.add y s)

let _ =
  let n = int_of_string (input_line stdin) in
  for i = 1 to n do
    previous := -1;
    let m = int_of_string (input_line stdin) in
    let l = List.map int_of_string @@ Str.split (Str.regexp " ") (input_line stdin) in
    let set = List.rev @@ to_set m in
    let rec pp fmt = function
      | [] -> Format.fprintf fmt ""
      | [x] -> Format.fprintf fmt "%d" x
      | x::l -> Format.fprintf fmt "%d %a" x pp l
    in
    try
      let l' = List.rev @@ find_perm l [] set IS.empty in
      Format.printf "%a@." pp l'
    with _ -> Format.printf "-1@."
  done

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

let rec to_set m =
  if m = 0 then
    IS.empty
  else
    IS.add m (to_set (m-1))

let previous = ref (-1)

let rec find_perm l p s =
  match l with
  | [] -> p
  | x::l ->
    let y  = if x = !previous && !previous <> -1 then
        IS.choose (IS.filter (fun y -> y <= x) s)
      else
        x
    in
    previous := x;
    let s' = IS.remove y s in
    find_perm l (y::p) s'

let _ =
  let n = int_of_string (input_line stdin) in
  for i = 1 to n do
    let m = int_of_string (input_line stdin) in
    let l = List.map int_of_string @@ Str.split (Str.regexp " ") (input_line stdin) in
    let set = to_set m in
    let rec pp fmt = function
      | [] -> Format.fprintf fmt ""
      | [x] -> Format.fprintf fmt "%d" x
      | x::l -> Format.fprintf fmt "%d %a" x pp l
    in
    try
      let l' = List.rev @@ find_perm l [] set in
      Format.printf "%a@." pp l'
    with _ -> Format.printf "-1@."
  done

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

let rec to_set m =
  if m = 0 then
    []
  else
    m::(to_set (m-1))

let previous = ref (-1)
let rec remove x l =
  match l with
  | [] -> assert false
  | y::l -> if x = y then l
    else
      y::(remove x l)

let rec find_perm l p s =
  match l with
  | [] -> p
  | x::l ->
    let y = if x = !previous && !previous <> -1 then
        match s with
        | [] -> failwith "Oops"
        | y::_ -> if y <= x then y else failwith "oops"
      else
        x
    in
    previous := x;
    let s' = remove y s in
    find_perm l (y::p) s'

let _ =
  let n = int_of_string (input_line stdin) in
  for i = 1 to n do
    previous := -1;
    let m = int_of_string (input_line stdin) in
    let l = List.map int_of_string @@ Str.split (Str.regexp " ") (input_line stdin) in
    let set = to_set m in
    let rec pp fmt = function
      | [] -> Format.fprintf fmt ""
      | [x] -> Format.fprintf fmt "%d" x
      | x::l -> Format.fprintf fmt "%d %a" x pp l
    in
    try
      let l' = List.rev @@ find_perm l [] set in
      Format.printf "%a@." pp l'
    with _ -> Format.printf "-1@."
  done

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

let rec to_set m =
  if m = 0 then
    IS.empty
  else
    IS.add m (to_set (m-1))

let rec find_perm l p s =
  match l with
  | [] -> p
  | x::l ->
    let y = IS.choose (IS.filter (fun y -> y <= x) s) in
    let s' = IS.remove y s in
    find_perm l (y::p) s'

let _ =
  let n = int_of_string (input_line stdin) in
  for i = 1 to n do
    let m = int_of_string (input_line stdin) in
    let l = List.map int_of_string @@ Str.split (Str.regexp " ") (input_line stdin) in
    let set = to_set m in
    let rec pp fmt = function
      | [] -> Format.fprintf fmt ""
      | [x] -> Format.fprintf fmt "%d" x
      | x::l -> Format.fprintf fmt "%d %a" x pp l
    in
    try
      let l' = List.rev @@ find_perm l [] set in
      Format.printf "%a@." pp l'
    with _ -> Format.printf "-1@."
  done

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

let rec to_set m =
  if m = 0 then
    []
  else
    m::(to_set (m-1))

let previous = ref (-1)
let rec remove x l =
  match l with
  | [] -> assert false
  | y::l -> if x = y then l
    else
      y::(remove x l)

let rec find_perm l p s =
  match l with
  | [] -> p
  | x::l ->
    let y = if x = !previous && !previous <> -1 then
        match s with
        | [] -> failwith "Oops"
        | x::_ -> x
      else
        x
    in
    previous := x;
    let s' = remove y s in
    find_perm l (y::p) s'

let _ =
  let n = int_of_string (input_line stdin) in
  for i = 1 to n do
    previous := -1;
    let m = int_of_string (input_line stdin) in
    let l = List.map int_of_string @@ Str.split (Str.regexp " ") (input_line stdin) in
    let set = to_set m in
    let rec pp fmt = function
      | [] -> Format.fprintf fmt ""
      | [x] -> Format.fprintf fmt "%d" x
      | x::l -> Format.fprintf fmt "%d %a" x pp l
    in
    try
      let l' = List.rev @@ find_perm l [] set in
      Format.printf "%a@." pp l'
    with _ -> Format.printf "-1@."
  done

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

let rec to_set m =
  if m = 0 then
    IS.empty
  else
    IS.add m (to_set (m-1))

let previous = ref (-1)

let rec find_perm l p s =
  match l with
  | [] -> p
  | x::l ->
    let y  = if x = !previous then
        IS.choose (IS.filter (fun y -> y <= x) s)
      else
        x
    in
    previous := x;
    let s' = IS.remove y s in
    find_perm l (y::p) s'

let _ =
  let n = int_of_string (input_line stdin) in
  for i = 1 to n do
    let m = int_of_string (input_line stdin) in
    let l = List.map int_of_string @@ Str.split (Str.regexp " ") (input_line stdin) in
    let set = to_set m in
    let rec pp fmt = function
      | [] -> Format.fprintf fmt ""
      | [x] -> Format.fprintf fmt "%d" x
      | x::l -> Format.fprintf fmt "%d %a" x pp l
    in
    try
      let l' = List.rev @@ find_perm l [] set in
      Format.printf "%a@." pp l'
    with _ -> Format.printf "-1@."
  done


In ABBYY a wonderful Smart Beaver lives. This time, he began to study history. When he read about the Roman Empire, he became interested in the life of merchants.The Roman Empire consisted of n cities numbered from 1 to n. It also had m bidirectional roads numbered from 1 to m. Each road connected two different cities. Any two cities were connected by no more than one road.We say that there is a path between cities c1 and c2 if there exists a finite sequence of cities t1, t2, ..., tp (p ≥ 1) such that:  t1 = c1  tp = c2  for any i (1 ≤ i < p), cities ti and ti + 1 are connected by a road We know that there existed a path between any two cities in the Roman Empire.In the Empire k merchants lived numbered from 1 to k. For each merchant we know a pair of numbers si and li, where si is the number of the city where this merchant's warehouse is, and li is the number of the city where his shop is. The shop and the warehouse could be located in different cities, so the merchants had to deliver goods from the warehouse to the shop.Let's call a road important for the merchant if its destruction threatens to ruin the merchant, that is, without this road there is no path from the merchant's warehouse to his shop. Merchants in the Roman Empire are very greedy, so each merchant pays a tax (1 dinar) only for those roads which are important for him. In other words, each merchant pays di dinars of tax, where di (di ≥ 0) is the number of roads important for the i-th merchant.The tax collection day came in the Empire. The Smart Beaver from ABBYY is very curious by nature, so he decided to count how many dinars each merchant had paid that day. And now he needs your help.

The first input line contains two integers n and m, separated by a space, n is the number of cities, and m is the number of roads in the empire. The following m lines contain pairs of integers ai, bi (1 ≤ ai, bi ≤ n, ai ≠ bi), separated by a space — the numbers of cities connected by the i-th road. It is guaranteed that any two cities are connected by no more than one road and that there exists a path between any two cities in the Roman Empire. The next line contains a single integer k — the number of merchants in the empire. The following k lines contain pairs of integers si, li (1 ≤ si, li ≤ n), separated by a space, — si is the number of the city in which the warehouse of the i-th merchant is located, and li is the number of the city in which the shop of the i-th merchant is located. The input limitations for getting 20 points are:    1 ≤ n ≤ 200  1 ≤ m ≤ 200  1 ≤ k ≤ 200  The input limitations for getting 50 points are:    1 ≤ n ≤ 2000  1 ≤ m ≤ 2000  1 ≤ k ≤ 2000  The input limitations for getting 100 points are:    1 ≤ n ≤ 105  1 ≤ m ≤ 105  1 ≤ k ≤ 105

Print exactly k lines, the i-th line should contain a single integer di — the number of dinars that the i-th merchant paid.

NoteThe given sample is illustrated in the figure below.   Let's describe the result for the first merchant. The merchant's warehouse is located in city 1 and his shop is in city 5. Let us note that if either road, (1, 2) or (2, 3) is destroyed, there won't be any path between cities 1 and 5 anymore. If any other road is destroyed, the path will be preserved. That's why for the given merchant the answer is 2.

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let es = Array.make n [] in
  let () =
    for i = 1 to m do
      let u = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
      let v = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
      let is_bridge = ref false in
	es.(u) <- (v, is_bridge) :: es.(u);
	es.(v) <- (u, is_bridge) :: es.(v);
    done
  in
  let es = Array.map Array.of_list es in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let s = Array.make k 0 in
  let l = Array.make k 0 in
  let () =
    for i = 0 to k - 1 do
      s.(i) <- Scanf.bscanf sb "%d " (fun s -> s) - 1;
      l.(i) <- Scanf.bscanf sb "%d " (fun s -> s) - 1;
    done
  in
  let min (x : int) y = if x < y then x else y in
  let used = Array.make n false in
  let t = ref 0 in
  let e = Array.make n 0 in
  let up = Array.make n 0 in
  let rec dfs u prev =
    used.(u) <- true;
    e.(u) <- !t;
    up.(u) <- !t;
    incr t;
    for i = 0 to Array.length es.(u) - 1 do
      let (v, is_bridge) = es.(u).(i) in
	if v <> prev then (
	  if not used.(v) then (
	    dfs v u;
	    up.(u) <- min up.(u) up.(v);
	    if up.(v) > e.(u) then (
	      is_bridge := true;
	      (*Printf.printf "bridge %d %d\n" u v*)
	    )
	  ) else (
	    up.(u) <- min up.(u) e.(v);
	  )
	)
    done;
  in
  let res = ref 0 in
  let rec dfs2 u dest dist =
    used.(u) <- true;
    if u = dest then (
      res := dist
    );
    for i = 0 to Array.length es.(u) - 1 do
      let (v, is_bridge) = es.(u).(i) in
	if not used.(v) then (
	  let dist =
	    if !is_bridge
	    then dist + 1
	    else dist
	  in
	    dfs2 v dest dist;
	)
    done;
  in
    for i = 0 to n - 1 do
      if not used.(i)
      then dfs i (-1)
    done;
    for i = 0 to k - 1 do
      for j = 0 to n - 1 do
	used.(j) <- false
      done;
      dfs2 s.(i) l.(i) 0;
      Printf.printf "%d\n" !res;
    done

module type ExtremumType =
sig
  type t
  val extremum : t -> t -> bool
end

module type RMQ =
sig
  type t
  type elt
  val of_array : elt array -> t
  val rmq : t -> int -> int -> int
end

module type RMQMake =
sig
  module Make(Ext : ExtremumType) : RMQ with type elt = Ext.t
end

module RMQST =
struct
  module Make(Ext : ExtremumType) : RMQ with type elt = Ext.t =
  struct
    type elt = Ext.t
    type t = {a : elt array;
	      m : int array array}
    let ext = Ext.extremum
    let of_array a =
      let n = Array.length a in
      let k = ref 0
      and d = ref 1 in
	while !d <= n do
	  d := 2 * !d;
	  incr k
	done;
	let k = !k in
	let m = Array.make_matrix k n 0 in
	  for i = 0 to n - 1 do
	    m.(0).(i) <- i;
	  done;
	  for j = 1 to k - 1 do
	    for i = 0 to n - (1 lsl j) do
	      let i2 = i + (1 lsl (j - 1)) in
		m.(j).(i) <-
		  if ext a.(m.(j - 1).(i)) a.(m.(j - 1).(i2))
		  then m.(j - 1).(i)
		  else m.(j - 1).(i2)
	    done
	  done;
	  {a = a;
	   m = m}
    let rmq data x y =
      let a = data.a
      and m = data.m in
      let l = y - x + 1 in
      let k = ref 0
      and d = ref 1 in
	while !d <= l do
	  d := 2 * !d;
	  incr k
	done;
	let k = !k - 1 in
	let i2 = y - (1 lsl k) + 1 in
	  if ext a.(m.(k).(x)) a.(m.(k).(i2))
	  then m.(k).(x)
	  else m.(k).(i2)
  end
end

module RMQSTmin =
  RMQST.Make(
    struct
      type t = int
      let extremum (x : t) (y : t) = x < y
    end
  )

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let m = Scanf.bscanf sb "%d " (fun s -> s) in
  let es = Array.make n [] in
  let () =
    for i = 1 to m do
      let u = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
      let v = Scanf.bscanf sb "%d " (fun s -> s) - 1 in
      let is_bridge = ref false in
	es.(u) <- (v, is_bridge) :: es.(u);
	es.(v) <- (u, is_bridge) :: es.(v);
    done
  in
  let es = Array.map Array.of_list es in
  let k = Scanf.bscanf sb "%d " (fun s -> s) in
  let s = Array.make k 0 in
  let l = Array.make k 0 in
  let () =
    for i = 0 to k - 1 do
      s.(i) <- Scanf.bscanf sb "%d " (fun s -> s) - 1;
      l.(i) <- Scanf.bscanf sb "%d " (fun s -> s) - 1;
    done
  in
  let min (x : int) y = if x < y then x else y in
  let used = Array.make n false in
  let t = ref 0 in
  let e = Array.make n 0 in
  let up = Array.make n 0 in
  let rec dfs u prev =
    used.(u) <- true;
    e.(u) <- !t;
    up.(u) <- !t;
    incr t;
    for i = 0 to Array.length es.(u) - 1 do
      let (v, is_bridge) = es.(u).(i) in
	if v <> prev then (
	  if not used.(v) then (
	    dfs v u;
	    up.(u) <- min up.(u) up.(v);
	    if up.(v) > e.(u) then (
	      is_bridge := true;
	      (*Printf.printf "bridge %d %d\n" u v*)
	    )
	  ) else (
	    up.(u) <- min up.(u) e.(v);
	  )
	)
    done;
  in
  let stack = Array.make (2 * n) (fun _ -> ()) in
  let stack_pos = ref 0 in
  let rec execute () =
    if !stack_pos > 0 then (
      decr stack_pos;
      let f = stack.(!stack_pos) in
	f ();
	execute ()
    )
  in
  let rec dfs u prev =
    used.(u) <- true;
    e.(u) <- !t;
    up.(u) <- !t;
    incr t;
    let rec aux i =
      if i < Array.length es.(u) then (
	stack.(!stack_pos) <- (fun () -> aux (i + 1));
	incr stack_pos;
	let (v, is_bridge) = es.(u).(i) in
	  if v <> prev then (
	    if not used.(v) then (
	      let f () =
		up.(u) <- min up.(u) up.(v);
		if up.(v) > e.(u) then (
		  is_bridge := true;
		  (*Printf.printf "bridge %d %d\n" u v*)
		)
	      in
		stack.(!stack_pos) <- f;
		incr stack_pos;
		stack.(!stack_pos) <- (fun () -> dfs v u);
		incr stack_pos;
	    ) else (
	      up.(u) <- min up.(u) e.(v);
	    )
	  );
      )
    in
      aux 0
  in
  let color = Array.make n (-1) in
  let c = ref 0 in
  let rec dfs2 u =
    used.(u) <- true;
    color.(u) <- !c;
    for i = 0 to Array.length es.(u) - 1 do
      let (v, is_bridge) = es.(u).(i) in
	if not used.(v) && not !is_bridge then (
	  dfs2 v
	)
    done
  in
  let rec dfs2 u =
    used.(u) <- true;
    color.(u) <- !c;
    let rec aux i =
      if i < Array.length es.(u) then (
	stack.(!stack_pos) <- (fun () -> aux (i + 1));
	incr stack_pos;
	let (v, is_bridge) = es.(u).(i) in
	    if not used.(v) && not !is_bridge then (
	      stack.(!stack_pos) <- (fun () -> dfs2 v);
	      incr stack_pos;
	    )
      )
    in
      aux 0
  in
    for i = 0 to n - 1 do
      if not used.(i) then (
	stack_pos := 0;
	dfs i (-1);
	execute ()
      )
    done;
    for j = 0 to n - 1 do
      used.(j) <- false
    done;
    for i = 0 to n - 1 do
      if not used.(i) then (
	stack_pos := 0;
	dfs2 i;
	execute ();
	incr c
      )
    done;
    let c = !c in
    let es2 = Array.make c [] in
    let () =
      for i = 0 to n - 1 do
	for j = 0 to Array.length es.(i) - 1 do
	  let (v, is_bridge) = es.(i).(j) in
	    if !is_bridge then (
	      let u = color.(i)
	      and v = color.(v) in
		es2.(u) <- v :: es2.(u);
		es2.(v) <- u :: es2.(v);
	    )
	done
      done
    in
    let es = Array.map Array.of_list es2 in
    let used = Array.make c false in
    let d = Array.make (2 * c) 0 in
    let de = Array.make (2 * c) 0 in
    let g1 = Array.make c 0 in
    let g2 = Array.make c 0 in
    let pos = ref 0 in
    let rec dfs3 u depth =
      used.(u) <- true;
      g1.(u) <- !pos;
      d.(!pos) <- depth;
      de.(!pos) <- u;
      incr pos;
      for i = 0 to Array.length es.(u) - 1 do
	let v = es.(u).(i) in
	  if not used.(v) then (
	    dfs3 v (depth + 1);
	    g2.(u) <- !pos;
	    d.(!pos) <- depth;
	    de.(!pos) <- u;
	    incr pos;
	  )
      done
    in
    let rec dfs3 u depth =
      used.(u) <- true;
      g1.(u) <- !pos;
      d.(!pos) <- depth;
      de.(!pos) <- u;
      incr pos;
      let rec aux i =
	if i < Array.length es.(u) then (
	  stack.(!stack_pos) <- (fun () -> aux (i + 1));
	  incr stack_pos;
	  let v = es.(u).(i) in
	    if not used.(v) then (
	      let f () =
		g2.(u) <- !pos;
		d.(!pos) <- depth;
		de.(!pos) <- u;
		incr pos;
	      in
		stack.(!stack_pos) <- f;
		incr stack_pos;
		stack.(!stack_pos) <- (fun () -> dfs3 v (depth + 1));
		incr stack_pos;
	    )
	)
      in
	aux 0
    in
      stack_pos := 0;
      dfs3 0 0;
      execute ();
      let rmq = RMQSTmin.of_array d in
	for i = 0 to k - 1 do
	  let u = color.(s.(i))
	  and v = color.(l.(i)) in
	  let w =
	    if g1.(u) < g1.(v)
	    then RMQSTmin.rmq rmq g1.(u) g1.(v)
	    else RMQSTmin.rmq rmq g1.(v) g1.(u)
	  in
	  let depth = d.(w) in
	  let res = d.(g1.(u)) - depth + d.(g1.(v)) - depth in
	    Printf.printf "%d\n" res;
	done