A tree is a connected undirected graph with n - 1 edges, where n denotes the number of vertices. Vertices are numbered 1 through n.Limak is a little polar bear. His bear family prepares a New Year tree every year. One year ago their tree was more awesome than usually. Thus, they decided to prepare the same tree in the next year. Limak was responsible for remembering that tree.It would be hard to remember a whole tree. Limak decided to describe it in his notebook instead. He took a pen and wrote n - 1 lines, each with two integers — indices of two vertices connected by an edge.Now, the New Year is just around the corner and Limak is asked to reconstruct that tree. Of course, there is a problem. He was a very little bear a year ago, and he didn't know digits and the alphabet, so he just replaced each digit with a question mark — the only character he knew. That means, for any vertex index in his notes he knows only the number of digits in it. At least he knows there were no leading zeroes.Limak doesn't want to disappoint everyone. Please, take his notes and reconstruct a New Year tree. Find any tree matching Limak's records and print its edges in any order. It's also possible that Limak made a mistake and there is no suitable tree – in this case print "-1" (without the quotes).

The first line contains a single integer n (2 ≤ n ≤ 200 000) — the number of vertices. Each of the next n - 1 lines contains two space-separated non-empty strings, both consisting of questions marks only. No string has more characters than the number of digits in n.

If there is no tree matching Limak's records, print the only line with "-1" (without the quotes). Otherwise, describe any tree matching Limak's notes. Print n - 1 lines, each with two space-separated integers – indices of vertices connected by an edge. You can print edges in any order.

open Printf
open Scanf

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

(* -----------------------------Begin MaxFlow----------------------------------*)

(* Implementation of Dinic's algorithm for max flow. See ../spoj/PROFIT/
   for additional algorithms. *)

let infinite_c = 10000 (* "infinite" capacity *)

let maxflow s t adj cap =
  (* s and t are nodes (numbers). g is a graph (represented via an
     array of adjacency lists). c is a 1-d array of capacities.  The
     adjacency list on node v stores pairs like (w,i) where w is the
     other node, and i is the index into the capacity array for where
     this capacity is stored.  It's set up so that i lxor 1 is where the
     capacity of edge (w,v) is stored.  We compute the maximum flow in
     the same representation as the capacities.  It returns (f,resid)
     where f is the maximum flow, and resid is the residual capacities
     that result from that flow.
  *)

  let c = Array.copy cap in
  let n = Array.length adj in
  let alive = Array.make n [] in
  let level = Array.make n 0 in
  let queue = Array.make n 0 in
  let front = ref 0 in
  let back = ref 0 in

  let push w = queue.(!back) <- w; back := !back+1 in
  let eject() = let x = queue.(!front) in front := !front + 1; x; in

  let rec bfs () =
    let rec loop () =
      if !front = !back then false else
	let v = eject() in
	if level.(v) = level.(t) then true else (
	  List.iter (
	    fun (w,i) -> if level.(w) < 0 && c.(i) > 0 then (
	      level.(w) <- level.(v) + 1;
	      push w
	    )
	  ) adj.(v);
	  loop ()
	)
    in
    level.(s) <- 0;
    back := 0; front := 0;
    push s;
    loop ();
  in

  let rec dfs v cap =
    (* Does a DFS from v looking for a path to t.  It tries to push cap units
       of flow to t.  It returns the amount of flow actually pushed *)
    if v=t then cap else
      let rec loop total remaining li =
	match li with
	  | [] ->
	    alive.(v) <- [];
	    total
	  | (w,i)::tail ->
	    if level.(w) = level.(v)+1 && c.(i) > 0 then (
	      let p = dfs w (min c.(i) remaining) in
	      c.(i) <- c.(i) - p;
	      c.(i lxor 1) <- c.(i lxor 1) + p;
	      if remaining-p = 0 then (
		alive.(v) <- li;
		total+p
	      ) else loop (total+p) (remaining-p) tail
	    ) else loop total remaining tail
      in loop 0 cap alive.(v)
  in

  let rec main_loop flow_so_far =
    Array.fill level 0 n (-1);
    Array.blit adj 0 alive 0 n;
    if bfs () then main_loop (flow_so_far + (dfs s infinite_c)) else (flow_so_far, c)
  in
  main_loop 0

(* ------------------------------End MaxFlow-----------------------------------*)

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)
let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)
let sum i j f = fold i j (fun i a -> (f i) + a) 0
let list_contains li x = List.exists (fun e -> e=x) li
let sortp (a,b) = (min a b, max a b)
let rec digits n = if n=0 then 0 else 1 + digits (n/10)

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

let all_spanning_trees n nedges edges =
  let connected elist =
    let mark = Array.make n false in
    let rec dfs u =
      if not mark.(u) then (
	mark.(u) <- true;
	for v = 0 to n-1 do
	  if list_contains elist (sortp (u,v)) then dfs v
	done
      )
    in
    dfs 0;
    forall 0 (n-1) (fun i -> mark.(i));
  in

  let rec list_trees i elist ac =
    if List.length elist = n-1 then
      if connected elist then elist::ac else ac
    else if i = nedges then ac
    else
      let ac = list_trees (i+1) elist ac in
      list_trees (i+1) (edges.(i)::elist) ac
  in

  list_trees 0 [] []

let () =
  let n = read_int () in
  let input = Array.init (n-1) (
    fun _ ->
      let a = -1 + String.length (read_string()) in
      let b = -1 + String.length (read_string()) in
      (a,b)
  ) in

  try (
    let nb = 1 + maxf 0 (n-2) (fun i -> snd (sortp input.(i))) in
    (* number of bundles *)
    if nb <> digits n then raise Not_found;
    let graph = Array.make_matrix nb nb 0 in
    for i=0 to n-2 do
      let (a,b) = sortp input.(i) in
      graph.(a).(b) <- graph.(a).(b) + 1;
    done;

    let edges = Array.of_list (
      fold 0 (nb-2) (
	fun u ac -> fold (u+1) (nb-1)
	  (fun v ac -> if graph.(u).(v) > 0 then (u,v)::ac else ac) ac
      ) []
    ) in

    let nedges = Array.length edges in
    let valence = Array.make nb 0 in
    let base = Array.make nb 0 in

    for i=0 to nb-1 do
      let (lo,hi) = (10 ^ i, min ((10 ^ (i+1)) - 1) n) in
      base.(i) <- lo;
      valence.(i) <- (hi - lo + 1) - graph.(i).(i) - 1;
      if valence.(i) < 0 then raise Not_found;
    done;

    let test_tree elist =
      let nv = nb + nedges + 2 in (* number of vertices in flow graph *)
      let (s,t) = (nv-2, nv-1) in
      let ne = nb + 3 * nedges in  (* number of edges in flow graph*)
      let adj = Array.make nv [] in
      let cap = Array.make (2*ne) 0 in

      let edge_no = ref 0 in
      let add_edge u v c =
	let en = !edge_no in
	adj.(u) <- (v,en)::adj.(u);
	adj.(v) <- (u,en+1)::adj.(v);
	cap.(en) <- c;
	cap.(en+1) <- 0;
	edge_no := 2 + en
      in

      for i = 0 to nedges-1 do
	let (u,v) = edges.(i) in
	let w = nb+i in
	let c = graph.(u).(v) in
	if c > 0 then (
	  let c = if list_contains elist (u,v) then c-1 else c in
	  add_edge s w c;
	  add_edge w u c;
	  add_edge w v c
	)
      done;

      for i=0 to nb-1 do
	add_edge i t valence.(i)
      done;

      let (f,res) = maxflow s t adj cap in
      let required_flow = sum 0 (nb-1) (fun i -> valence.(i)) in
      if f <> required_flow then None else (
	let cur = Array.copy base in
	let tree = List.map (fun (u,v) -> (base.(u), base.(v))) elist in

	(* generate the coning edges *)
	let tree = fold nb (nb+nedges-1) (
	  fun w ac ->
	    (* the first two elements of adj.(w) are the two vertices
	       we need to work with *)
	    let x = List.hd adj.(w) in
	    let y = List.hd (List.tl adj.(w)) in

	    let proc (v,ind) (v',_) ac =
	      (* cone the base of v' to the vertices of v *)
	      fold 1 (cap.(ind) - res.(ind)) (
		fun _ ac ->
		  cur.(v) <- cur.(v) + 1;
		  (base.(v'), cur.(v))::ac
	      ) ac
	    in
	    proc x y (proc y x ac);
	) tree in

	(* generate the edges internal to a bundle *)
	let tree = fold 0 (nb-1) (
	  fun v ac ->
	    fold 1 graph.(v).(v) (
	      fun _ ac ->
		cur.(v) <- cur.(v) + 1;
		(base.(v), cur.(v))::ac
	    ) ac
	) tree in

	Some tree
      )
    in

    let rec try_trees tlist =
      match tlist with
	| [] -> raise Not_found
	| elist::tail ->
	  match test_tree elist with
	    | None -> try_trees tail
	    | Some st ->
	      (* let's output the tree in exactly the form of the input *)
	      let h = Hashtbl.create 100 in
	      let insert (i,j) =
		let (i,j) = sortp (i,j) in
		let (p,q) = (-1 + digits i, -1 + digits j) in
		let c = try Hashtbl.find h (p,q) with Not_found -> [] in
		Hashtbl.replace h (p,q) ((i,j)::c)
	      in
	      let remove_and_get x =
		let (p,q) = sortp x in
		let li = Hashtbl.find h (p,q) in
		let (i,j) = List.hd li in
		Hashtbl.replace h (p,q) (List.tl li);
		if (p,q) = x then (i,j) else (j,i)
	      in
	      List.iter insert st;
	      for i=0 to n-2 do
		let (a,b) = remove_and_get input.(i) in
		printf "%d %d\n" a b
	      done
    in

    try_trees (all_spanning_trees nb nedges edges)

  ) with Not_found -> printf "-1\n"

open Printf
open Scanf

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

(* -----------------------------Begin MaxFlow----------------------------------*)

(* Implementation of Dinic's algorithm for max flow. See ../spoj/PROFIT/
   for additional algorithms. *)

let infinite_c = 10000 (* "infinite" capacity *)

let maxflow s t adj cap =
  (* s and t are nodes (numbers). g is a graph (represented via an
     array of adjacency lists). c is a 1-d array of capacities.  The
     adjacency list on node v stores pairs like (w,i) where w is the
     other node, and i is the index into the capacity array for where
     this capacity is stored.  It's set up so that i lxor 1 is where the
     capacity of edge (w,v) is stored.  We compute the maximum flow in
     the same representation as the capacities.  It returns (f,resid)
     where f is the maximum flow, and resid is the residual capacities
     that result from that flow.
  *)

  let c = Array.copy cap in
  let n = Array.length adj in
  let alive = Array.make n [] in
  let level = Array.make n 0 in
  let queue = Array.make n 0 in
  let front = ref 0 in
  let back = ref 0 in

  let push w = queue.(!back) <- w; back := !back+1 in
  let eject() = let x = queue.(!front) in front := !front + 1; x; in

  let rec bfs () =
    let rec loop () =
      if !front = !back then false else
	let v = eject() in
	if level.(v) = level.(t) then true else (
	  List.iter (
	    fun (w,i) -> if level.(w) < 0 && c.(i) > 0 then (
	      level.(w) <- level.(v) + 1;
	      push w
	    )
	  ) adj.(v);
	  loop ()
	)
    in
    level.(s) <- 0;
    back := 0; front := 0;
    push s;
    loop ();
  in

  let rec dfs v cap =
    (* Does a DFS from v looking for a path to t.  It tries to push cap units
       of flow to t.  It returns the amount of flow actually pushed *)
    if v=t then cap else
      let rec loop total remaining li =
	match li with
	  | [] ->
	    alive.(v) <- [];
	    total
	  | (w,i)::tail ->
	    if level.(w) = level.(v)+1 && c.(i) > 0 then (
	      let p = dfs w (min c.(i) remaining) in
	      c.(i) <- c.(i) - p;
	      c.(i lxor 1) <- c.(i lxor 1) + p;
	      if remaining-p = 0 then (
		alive.(v) <- li;
		total+p
	      ) else loop (total+p) (remaining-p) tail
	    ) else loop total remaining tail
      in loop 0 cap alive.(v)
  in

  let rec main_loop flow_so_far =
    Array.fill level 0 n (-1);
    Array.blit adj 0 alive 0 n;
    if bfs () then main_loop (flow_so_far + (dfs s infinite_c)) else (flow_so_far, c)
  in
  main_loop 0

(* ------------------------------End MaxFlow-----------------------------------*)

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)
let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)
let sum i j f = fold i j (fun i a -> (f i) + a) 0
let list_contains li x = List.exists (fun e -> e=x) li
let sortp (a,b) = (min a b, max a b)
let rec digits n = if n=0 then 0 else 1 + digits (n/10)

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

let all_spanning_trees n nedges edges =
  let connected elist =
    let mark = Array.make n false in
    let rec dfs u =
      if not mark.(u) then (
	mark.(u) <- true;
	for v = 0 to n-1 do
	  if list_contains elist (sortp (u,v)) then dfs v
	done
      )
    in
    dfs 0;
    forall 0 (n-1) (fun i -> mark.(i));
  in

  let rec list_trees i elist ac =
    if List.length elist = n-1 then
      if connected elist then elist::ac else ac
    else if i = nedges then ac
    else
      let ac = list_trees (i+1) elist ac in
      list_trees (i+1) (edges.(i)::elist) ac
  in

  list_trees 0 [] []

let () =
  let n = read_int () in
  let input = Array.init (n-1) (
    fun _ ->
      let a = -1 + String.length (read_string()) in
      let b = -1 + String.length (read_string()) in
      (a,b)
  ) in

  try (
    let nb = 1 + maxf 0 (n-2) (fun i -> snd input.(i)) in
    (* number of bundles *)
    if nb <> digits n then raise Not_found;
    let graph = Array.make_matrix nb nb 0 in
    for i=0 to n-2 do
      let (a,b) = sortp input.(i) in
      graph.(a).(b) <- graph.(a).(b) + 1;
    done;

    let edges = Array.of_list (
      fold 0 (nb-2) (
	fun u ac -> fold (u+1) (nb-1)
	  (fun v ac -> if graph.(u).(v) > 0 then (u,v)::ac else ac) ac
      ) []
    ) in

    let nedges = Array.length edges in
    let valence = Array.make nb 0 in
    let base = Array.make nb 0 in

    for i=0 to nb-1 do
      let (lo,hi) = (10 ^ i, min ((10 ^ (i+1)) - 1) n) in
      base.(i) <- lo;
      valence.(i) <- (hi - lo + 1) - graph.(i).(i) - 1;
      if valence.(i) < 0 then raise Not_found;
    done;

    let test_tree elist =
      let nv = nb + nedges + 2 in (* number of vertices in flow graph *)
      let (s,t) = (nv-2, nv-1) in
      let ne = nb + 3 * nedges in  (* number of edges in flow graph*)
      let adj = Array.make nv [] in
      let cap = Array.make (2*ne) 0 in

      let edge_no = ref 0 in
      let add_edge u v c =
	let en = !edge_no in
	adj.(u) <- (v,en)::adj.(u);
	adj.(v) <- (u,en+1)::adj.(v);
	cap.(en) <- c;
	cap.(en+1) <- 0;
	edge_no := 2 + en
      in

      for i = 0 to nedges-1 do
	let (u,v) = edges.(i) in
	let w = nb+i in
	let c = graph.(u).(v) in
	if c > 0 then (
	  let c = if list_contains elist (u,v) then c-1 else c in
	  add_edge s w c;
	  add_edge w u c;
	  add_edge w v c
	)
      done;

      for i=0 to nb-1 do
	add_edge i t valence.(i)
      done;

      let (f,res) = maxflow s t adj cap in
      let required_flow = sum 0 (nb-1) (fun i -> valence.(i)) in
      if f <> required_flow then None else (
	let cur = Array.copy base in
	let tree = List.map (fun (u,v) -> (base.(u), base.(v))) elist in

	(* generate the coning edges *)
	let tree = fold nb (nb+nedges-1) (
	  fun w ac ->
	    (* the first two elements of adj.(w) are the two vertices
	       we need to work with *)
	    let x = List.hd adj.(w) in
	    let y = List.hd (List.tl adj.(w)) in

	    let proc (v,ind) (v',_) ac =
	      (* cone the base of v' to the vertices of v *)
	      fold 1 (cap.(ind) - res.(ind)) (
		fun _ ac ->
		  cur.(v) <- cur.(v) + 1;
		  (base.(v'), cur.(v))::ac
	      ) ac
	    in
	    proc x y (proc y x ac);
	) tree in

	(* generate the edges internal to a bundle *)
	let tree = fold 0 (nb-1) (
	  fun v ac ->
	    fold 1 graph.(v).(v) (
	      fun _ ac ->
		cur.(v) <- cur.(v) + 1;
		(base.(v), cur.(v))::ac
	    ) ac
	) tree in

	Some tree
      )
    in

    let rec try_trees tlist =
      match tlist with
	| [] -> raise Not_found
	| elist::tail ->
	  match test_tree elist with
	    | None -> try_trees tail
	    | Some st ->
	      (* let's output the tree in exactly the form of the input *)
	      let h = Hashtbl.create 100 in
	      let insert (i,j) =
		let (i,j) = sortp (i,j) in
		let (p,q) = (-1 + digits i, -1 + digits j) in
		let c = try Hashtbl.find h (p,q) with Not_found -> [] in
		Hashtbl.replace h (p,q) ((i,j)::c)
	      in
	      let remove_and_get x =
		let (p,q) = sortp x in
		let li = Hashtbl.find h (p,q) in
		let (i,j) = List.hd li in
		Hashtbl.replace h (p,q) (List.tl li);
		if (p,q) = x then (i,j) else (j,i)
	      in
	      List.iter insert st;
	      for i=0 to n-2 do
		let (a,b) = remove_and_get input.(i) in
		printf "%d %d\n" a b
	      done
    in

    try_trees (all_spanning_trees nb nedges edges)

  ) with Not_found -> printf "-1\n"

open Printf
open Scanf

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

(* -----------------------------Begin MaxFlow----------------------------------*)

(* Implementation of Dinic's algorithm for max flow. See ../spoj/PROFIT/
   for additional algorithms. *)

let infinite_c = 10000 (* "infinite" capacity *)

let maxflow s t adj cap =
  (* s and t are nodes (numbers). g is a graph (represented via an
     array of adjacency lists). c is a 1-d array of capacities.  The
     adjacency list on node v stores pairs like (w,i) where w is the
     other node, and i is the index into the capacity array for where
     this capacity is stored.  It's set up so that i lxor 1 is where the
     capacity of edge (w,v) is stored.  We compute the maximum flow in
     the same representation as the capacities.  It returns (f,resid)
     where f is the maximum flow, and resid is the residual capacities
     that result from that flow.
  *)

  let c = Array.copy cap in
  let n = Array.length adj in
  let alive = Array.make n [] in
  let level = Array.make n 0 in
  let queue = Array.make n 0 in
  let front = ref 0 in
  let back = ref 0 in

  let push w = queue.(!back) <- w; back := !back+1 in
  let eject() = let x = queue.(!front) in front := !front + 1; x; in

  let rec bfs () =
    let rec loop () =
      if !front = !back then false else
	let v = eject() in
	if level.(v) = level.(t) then true else (
	  List.iter (
	    fun (w,i) -> if level.(w) < 0 && c.(i) > 0 then (
	      level.(w) <- level.(v) + 1;
	      push w
	    )
	  ) adj.(v);
	  loop ()
	)
    in
    level.(s) <- 0;
    back := 0; front := 0;
    push s;
    loop ();
  in

  let rec dfs v cap =
    (* Does a DFS from v looking for a path to t.  It tries to push cap units
       of flow to t.  It returns the amount of flow actually pushed *)
    if v=t then cap else
      let rec loop total remaining li =
	match li with
	  | [] ->
	    alive.(v) <- [];
	    total
	  | (w,i)::tail ->
	    if level.(w) = level.(v)+1 && c.(i) > 0 then (
	      let p = dfs w (min c.(i) remaining) in
	      c.(i) <- c.(i) - p;
	      c.(i lxor 1) <- c.(i lxor 1) + p;
	      if remaining-p = 0 then (
		alive.(v) <- li;
		total+p
	      ) else loop (total+p) (remaining-p) tail
	    ) else loop total remaining tail
      in loop 0 cap alive.(v)
  in

  let rec main_loop flow_so_far =
    Array.fill level 0 n (-1);
    Array.blit adj 0 alive 0 n;
    if bfs () then main_loop (flow_so_far + (dfs s infinite_c)) else (flow_so_far, c)
  in
  main_loop 0

(* ------------------------------End MaxFlow-----------------------------------*)

let rec fold i j f init = if i>j then init else fold (i+1) j f (f i init)
let maxf i j f = fold (i+1) j (fun k a -> max (f k) a) (f i)
let rec forall i j f = (i>j) || ((f i) && forall (i+1) j f)
let sum i j f = fold i j (fun i a -> (f i) + a) 0
let list_contains li x = List.exists (fun e -> e=x) li
let sortp (a,b) = (min a b, max a b)
let rec digits n = if n=0 then 0 else 1 + digits (n/10)

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

let all_spanning_trees n nedges edges =
  let connected elist =
    let mark = Array.make n false in
    let rec dfs u =
      if not mark.(u) then (
	mark.(u) <- true;
	for v = 0 to n-1 do
	  if list_contains elist (sortp (u,v)) then dfs v
	done
      )
    in
    dfs 0;
    forall 0 (n-1) (fun i -> mark.(i));
  in

  let rec list_trees i elist ac =
    if List.length elist = n-1 then
      if connected elist then elist::ac else ac
    else if i = nedges then ac
    else
      let ac = list_trees (i+1) elist ac in
      list_trees (i+1) (edges.(i)::elist) ac
  in

  list_trees 0 [] []

let () =
  let n = read_int () in
  let input = Array.init (n-1) (
    fun _ ->
      let a = -1 + String.length (read_string()) in
      let b = -1 + String.length (read_string()) in
      (a,b)
  ) in

  try (
    let nb = 1 + maxf 0 (n-2) (fun i -> snd input.(i)) in
    (* number of bundles *)
    if nb <> digits n then raise Not_found;
    let graph = Array.make_matrix nb nb 0 in
    for i=0 to n-2 do
      let (a,b) = sortp input.(i) in
      graph.(a).(b) <- graph.(a).(b) + 1;
    done;

    let edges = Array.of_list (
      fold 0 (nb-2) (
	fun u ac -> fold (u+1) (nb-1)
	  (fun v ac -> if graph.(u).(v) > 0 then (u,v)::ac else ac) ac
      ) []
    ) in

    let nedges = Array.length edges in
    let valence = Array.make nb 0 in
    let base = Array.make nb 0 in

    for i=0 to nb-1 do
      let (lo,hi) = (10 ^ i, min ((10 ^ (i+1)) - 1) n) in
      base.(i) <- lo;
      valence.(i) <- (hi - lo + 1) - graph.(i).(i) - 1;
      if valence.(i) < 0 then raise Not_found;
    done;

    let test_tree elist =
      let nv = nb + nedges + 2 in (* number of vertices in flow graph *)
      let (s,t) = (nv-2, nv-1) in
      let ne = nb + 3 * nedges in  (* number of edges in flow graph*)
      let adj = Array.make nv [] in
      let cap = Array.make (2*ne) 0 in

      let edge_no = ref 0 in
      let add_edge u v c =
	let en = !edge_no in
	adj.(u) <- (v,en)::adj.(u);
	adj.(v) <- (u,en+1)::adj.(v);
	cap.(en) <- c;
	cap.(en+1) <- 0;
	edge_no := 2 + en
      in

      for i = 0 to nedges-1 do
	let (u,v) = edges.(i) in
	let w = nb+i in
	let c = graph.(u).(v) in
	if c > 0 then (
	  let c = if list_contains elist (u,v) then c-1 else c in
	  add_edge s w c;
	  add_edge w u c;
	  add_edge w v c
	)
      done;

      for i=0 to nb-1 do
	add_edge i t valence.(i)
      done;

      let (f,res) = maxflow s t adj cap in
      let required_flow = sum 0 (nb-1) (fun i -> valence.(i)) in
      if f <> required_flow then None else (
	let cur = Array.init nb (fun i -> base.(i)) in
	let tree = List.map (fun (u,v) -> (base.(u), base.(v))) elist in

	(* generate the coning edges *)
	let tree = fold nb (2*nb-2) (
	  fun w ac ->
	    (* the first two elements of adj.(w) are the two vertices
	       we need to work with *)
	    let x = List.hd adj.(w) in
	    let y = List.hd (List.tl adj.(w)) in

	    let proc (v,ind) (v',_) ac =
	      (* cone the base of v' to the vertices of v *)
	      fold 1 (cap.(ind) - res.(ind)) (
		fun _ ac ->
		  cur.(v) <- cur.(v) + 1;
		  (base.(v'), cur.(v))::ac
	      ) ac
	    in
	    proc x y (proc y x ac);
	) tree in

	(* generate the edges internal to a bundle *)
	let tree = fold 0 (nb-1) (
	  fun v ac ->
	    fold 1 graph.(v).(v) (
	      fun _ ac ->
		cur.(v) <- cur.(v) + 1;
		(base.(v), cur.(v))::ac
	    ) ac
	) tree in

	Some tree
      )
    in

    let rec try_trees tlist =
      match tlist with
	| [] -> raise Not_found
	| elist::tail ->
	  match test_tree elist with
	    | None -> try_trees tail
	    | Some st ->
	      (* let's output the tree in exactly the form of the input *)
	      let h = Hashtbl.create 100 in
	      let insert (i,j) =
		let (i,j) = sortp (i,j) in
		let (p,q) = (-1 + digits i, -1 + digits j) in
		let c = try Hashtbl.find h (p,q) with Not_found -> [] in
		Hashtbl.replace h (p,q) ((i,j)::c)
	      in
	      let remove_and_get x =
		let (p,q) = sortp x in
		let li = Hashtbl.find h (p,q) in
		let (i,j) = List.hd li in
		Hashtbl.replace h (p,q) (List.tl li);
		if (p,q) = x then (i,j) else (j,i)
	      in
	      List.iter insert st;
	      for i=0 to n-2 do
		let (i,j) = remove_and_get input.(i) in
		printf "%d %d\n" i j
	      done
    in

    try_trees (all_spanning_trees nb nedges edges)

  ) with Not_found -> printf "-1\n"


Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number.One day Polycarpus wondered which secretaries are talking via the Spyke and which are not. For each secretary, he wrote out either the session number of his call or a 0 if this secretary wasn't talking via Spyke at that moment.Help Polycarpus analyze these data and find out the number of pairs of secretaries that are talking. If Polycarpus has made a mistake in the data and the described situation could not have taken place, say so.Note that the secretaries can correspond via Spyke not only with each other, but also with the people from other places. Also, Spyke conferences aren't permitted — that is, one call connects exactly two people.

The first line contains integer n (1 ≤ n ≤ 103) — the number of secretaries in Polycarpus's corporation. The next line contains n space-separated integers: id1, id2, ..., idn (0 ≤ idi ≤ 109). Number idi equals the number of the call session of the i-th secretary, if the secretary is talking via Spyke, or zero otherwise. Consider the secretaries indexed from 1 to n in some way.

Print a single integer — the number of pairs of chatting secretaries, or -1 if Polycarpus's got a mistake in his records and the described situation could not have taken place.

NoteIn the first test sample there are two Spyke calls between secretaries: secretary 2 and secretary 4, secretary 3 and secretary 5.In the second test sample the described situation is impossible as conferences aren't allowed.

(* CF Arguments 291B *)
open Filename;;
open Str;;

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

let cout = open_out "output.txt";;
let gr () = Scanf.bscanf cin " %d" (fun i -> i);;
let grf () = Scanf.scanf " %f" (fun i -> i);;
let grl () = Scanf.scanf " %Ld" (fun i -> i);;
let rdln() = input_line Pervasives.stdin;;
(* let spli s = Str.split (Str.regexp " ") s;; *)
let printlisti li = List.iter (fun i -> (print_int i; print_string " ")) li;;
let printlists ls = List.iter (fun s -> (print_string (s ^ " "))) ls;;
let printlisti64 li = List.iter (fun i -> (print_string (Int64.to_string i); print_string " ")) li;;
let printarri ai = Array.iter (fun i -> (print_int i; print_string " ")) ai;;
let rec readlist n acc = match n with
	| 0 -> List.rev acc
	| _ -> readlist (n -1) (gr() :: acc);;
let debug = false;;

let n = gr()

let rec countpairs ls cnt = match ls with
	| [] -> cnt
	| 0 :: tl -> countpairs tl cnt
	| a :: b :: c :: tl when a == b && b == c -> (-1)
	| a :: b :: tl when a == b -> countpairs tl (cnt +1)
	| hd :: tl -> countpairs tl cnt;;

let main() =
	let ids = readlist n [] in
	let sids = List.sort compare ids in
	let cnt = countpairs sids 0 in
	print_int cnt;;

main ();;


One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:   G has exactly n vertices, numbered from 1 to n.  For all pairs of vertices i and j, where i ≠ j, there is an edge connecting them if and only if characters si and sj are either equal or neighbouring in the alphabet. That is, letters in pairs "a"-"b" and "b"-"c" are neighbouring, while letters "a"-"c" are not. Vasya painted the resulting graph near the string and then erased the string. Next day Vasya's friend Petya came to a lecture and found some graph at his desk. He had heard of Vasya's adventure and now he wants to find out whether it could be the original graph G, painted by Vasya. In order to verify this, Petya needs to know whether there exists a string s, such that if Vasya used this s he would produce the given graph G.

The first line of the input contains two integers n and m  — the number of vertices and edges in the graph found by Petya, respectively. Each of the next m lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the edges of the graph G. It is guaranteed, that there are no multiple edges, that is any pair of vertexes appear in this list no more than once.

In the first line print "Yes" (without the quotes), if the string s Petya is interested in really exists and "No" (without the quotes) otherwise. If the string s exists, then print it on the second line of the output. The length of s must be exactly n, it must consist of only letters "a", "b" and "c" only, and the graph built using this string must coincide with G. If there are multiple possible answers, you may print any of them.

NoteIn the first sample you are given a graph made of two vertices with an edge between them. So, these vertices can correspond to both the same and adjacent letters. Any of the following strings "aa", "ab", "ba", "bb", "bc", "cb", "cc" meets the graph's conditions. In the second sample the first vertex is connected to all three other vertices, but these three vertices are not connected with each other. That means that they must correspond to distinct letters that are not adjacent, but that is impossible as there are only two such letters: a and c.

open Printf
open Scanf

let read_pair () = bscanf Scanning.stdib " %d %d " (fun x y -> (x,y))
let () =
  let (n,m) = read_pair () in

  let mat = Array.make_matrix n n true in

  for i=0 to m-1 do
    let (u,v) = read_pair() in
    let (u,v) = (u-1, v-1) in
    mat.(u).(v) <- false;
    mat.(v).(u) <- false;
  done;

  for v=0 to n-1 do mat.(v).(v) <- false done;

  let find =
    let rec loop (r,c) = if r=n then None else (
      if mat.(r).(c) then Some (r,c) else
      loop (if c<n-1 then (r,c+1) else (r+1,0))
    ) in
    loop (0,0)
  in

  match find with
    | None ->
      printf "Yes\n";
      for i=0 to n-1 do printf "b" done;
      print_newline()
    | Some (start,_) ->

      let label = Array.make n (-1) in
      let hist = Array.make 2 0 in
      let bipartite = ref true in
      let rec dfs v lab =
	if label.(v) >= 0 then (
	  if label.(v) <> lab then bipartite := false
	) else (
	  label.(v) <- lab;
	  hist.(lab) <- hist.(lab) + 1;
	  for w = 0 to n-1 do
	    if mat.(v).(w) then dfs w (1-lab)
	  done
	)
      in

      dfs start 0;

      if !bipartite && m = (n * (n-1))/2 - hist.(0) * hist.(1) then (
	printf "Yes\n";
	for v=0 to n-1 do
	  let letter = match label.(v) with
	    | -1 -> 'b'
	    | 0 -> 'a'
	    | 1 -> 'c'
	    | _ -> failwith "bad label"
	  in
	  printf "%c" letter
	done;
	print_newline()
      ) else (
	printf "No\n"
      )

open Printf
open Scanf

let read_pair () = bscanf Scanning.stdib " %d %d " (fun x y -> (x,y))
let () =
  let (n,m) = read_pair () in

  let mat = Array.make_matrix n n true in

  for i=0 to m-1 do
    let (u,v) = read_pair() in
    let (u,v) = (u-1, v-1) in
    mat.(u).(v) <- false;
    mat.(v).(u) <- false;
  done;

  for v=0 to n-1 do mat.(v).(v) <- false done;

  let find =
    let rec loop (r,c) = if r=n then None else (
      if mat.(r).(c) then Some (r,c) else
      loop (if c<n-1 then (r,c+1) else (r+1,0))
    ) in
    loop (0,0)
  in

  match find with
    | None ->
      printf "Yes\n";
      for i=0 to n-1 do printf "b" done;
      print_newline()
    | Some (start,_) ->

      let label = Array.make n (-1) in
      let hist = Array.make 2 0 in
      let bipartite = ref true in
      let rec dfs v lab =
	if label.(v) >= 0 then (
	  if label.(v) <> lab then bipartite := false
	) else (
	  label.(v) <- lab;
	  hist.(lab) <- hist.(lab) + 1;
	  for w = 0 to n-1 do
	    if mat.(v).(w) then dfs w (1-lab)
	  done
	)
      in

      dfs start 0;

      if !bipartite && m = hist.(0) * hist.(1) then (
	printf "Yes\n";
	for v=0 to n-1 do
	  let letter = match label.(v) with
	    | -1 -> 'b'
	    | 0 -> 'a'
	    | 1 -> 'c'
	    | _ -> failwith "bad label"
	  in
	  printf "%c" letter
	done;
	print_newline()
      ) else (
	printf "No\n"
      )

open Printf
open Scanf

let read_pair () = bscanf Scanning.stdib " %d %d " (fun x y -> (x,y))
let () =
  let (n,m) = read_pair () in

  let mat = Array.make_matrix n n true in

  for i=0 to m-1 do
    let (u,v) = read_pair() in
    let (u,v) = (u-1, v-1) in
    mat.(u).(v) <- false;
    mat.(v).(u) <- false;
  done;

  for v=0 to n-1 do mat.(v).(v) <- false done;

  let find =
    let rec loop (r,c) = if r=n then None else (
      if mat.(r).(c) then Some (r,c) else
      loop (if c<n-1 then (r,c+1) else (r+1,0))
    ) in
    loop (0,0)
  in

  match find with
    | None ->
      printf "Yes\n";
      for i=0 to n-1 do printf "b" done;
      print_newline()
    | Some (start,_) ->

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

      let bipartite = ref true in

      let rec dfs v lab =
	if label.(v) >= 0 then (
	  if label.(v) <> lab then bipartite := false
	) else (
	  label.(v) <- lab;
	  for w = 0 to n-1 do
	    if mat.(v).(w) then dfs w (1-lab)
	  done
	)
      in

      dfs start 0;

      if !bipartite then (
	printf "Yes\n";
	for v=0 to n-1 do
	  let letter = match label.(v) with
	    | -1 -> 'b'
	    | 0 -> 'a'
	    | 1 -> 'c'
	    | _ -> failwith "bad label"
	  in
	  printf "%c" letter
	done;
	print_newline()
      ) else (
	printf "No\n"
      )


Peter decided to wish happy birthday to his friend from Australia and send him a card. To make his present more mysterious, he decided to make a chain. Chain here is such a sequence of envelopes A = {a1,  a2,  ...,  an}, where the width and the height of the i-th envelope is strictly higher than the width and the height of the (i  -  1)-th envelope respectively. Chain size is the number of envelopes in the chain. Peter wants to make the chain of the maximum size from the envelopes he has, the chain should be such, that he'll be able to put a card into it. The card fits into the chain if its width and height is lower than the width and the height of the smallest envelope in the chain respectively. It's forbidden to turn the card and the envelopes. Peter has very many envelopes and very little time, this hard task is entrusted to you.

The first line contains integers n, w, h (1  ≤ n ≤ 5000, 1 ≤ w,  h  ≤ 106) — amount of envelopes Peter has, the card width and height respectively. Then there follow n lines, each of them contains two integer numbers wi and hi — width and height of the i-th envelope (1 ≤ wi,  hi ≤ 106).

In the first line print the maximum chain size. In the second line print the numbers of the envelopes (separated by space), forming the required chain, starting with the number of the smallest envelope. Remember, please, that the card should fit into the smallest envelope. If the chain of maximum size is not unique, print any of the answers. If the card does not fit into any of the envelopes, print number 0 in the single line.

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

type envelope = { w: int; h: int; i: int }

let lbound a n x =
  let rec go l h =
    if l = h then
      l
    else
      let m = (l+h)/2 in
      if a.(m).h < x.h then
        go (m+1) h
      else
        go l m
  in go 0 n

let () =
  let n = read_int 0 in
  let a = Array.make (n+1) { w = 0; h = 0; i = 0 } in
  let pred = Array.make (n+1) (-1) in
  for i = 0 to n do
    let w = read_int 0 in
    let h = read_int 0 in
    a.(i) <- { w; h; i }
  done;
  Array.sort (fun x y -> if x.w <> y.w then x.w-y.w else y.h-x.h) a;

  let rec lis size i =
    if i > n then
      size
    else if a.(i).i = 0 then (
      a.(0) <- a.(i);
      lis 1 (i+1)
    ) else if size = 0 then
      lis 0 (i+1)
    else (
      let x = lbound a size a.(i) in
      if x > 0 then (
        a.(x) <- a.(i);
        pred.(a.(x).i) <- a.(x-1).i
      );
      lis (if x = size then size+1 else size) (i+1)
    )
  in
  let size = lis 0 0 in
  Printf.printf "%d\n" (size-1);

  let rec plan i acc =
    if pred.(i) < 0 then
      acc
    else
      plan pred.(i) (i::acc)
  in
  if size > 0 then
    List.iter (Printf.printf "%d ") (plan a.(size-1).i [])

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

type envelope = { w: int; h: int; i: int }

let cmp x y =
  if x.w <> y.w then x.w-y.w else y.h-x.h

let lbound a n x =
  let rec go l h =
    if l = h then
      l
    else
      let m = (l+h)/2 in
      if cmp a.(m) x < 0 then
        go (m+1) h
      else
        go l m
  in go 0 n

let () =
  let n = read_int 0 in
  let a = Array.make (n+1) { w = 0; h = 0; i = 0 } in
  let pred = Array.make (n+1) (-1) in
  for i = 0 to n do
    let w = read_int 0 in
    let h = read_int 0 in
    a.(i) <- { w; h; i }
  done;
  Array.sort cmp a;

  let rec lis size i =
    if i > n then
      size
    else if a.(i).i = 0 then (
      a.(0) <- a.(i);
      lis 1 (i+1)
    ) else (
      if size > 0 then (
        let x = lbound a size a.(i) in
        if x > 0 then (
          a.(x) <- a.(i);
          pred.(a.(x).i) <- a.(x-1).i
        );
        lis (if x = size then size+1 else size) (i+1)
      ) else
        lis size (i+1)
    )
  in
  let size = lis 0 0 in
  Printf.printf "%d\n" (size-1);

  let rec plan i acc =
    if pred.(i) < 0 then
      acc
    else
      plan pred.(i) (i::acc)
  in
  if size > 0 then
    List.iter (Printf.printf "%d ") (plan a.(size-1).i [])


Consider a sequence of digits of length $$$2^k$$$ $$$[a_1, a_2, \ldots, a_{2^k}]$$$. We perform the following operation with it: replace pairs $$$(a_{2i+1}, a_{2i+2})$$$ with $$$(a_{2i+1} + a_{2i+2})\bmod 10$$$ for $$$0\le i<2^{k-1}$$$. For every $$$i$$$ where $$$a_{2i+1} + a_{2i+2}\ge 10$$$ we get a candy! As a result, we will get a sequence of length $$$2^{k-1}$$$.Less formally, we partition sequence of length $$$2^k$$$ into $$$2^{k-1}$$$ pairs, each consisting of 2 numbers: the first pair consists of the first and second numbers, the second of the third and fourth $$$\ldots$$$, the last pair consists of the ($$$2^k-1$$$)-th and ($$$2^k$$$)-th numbers. For every pair such that sum of numbers in it is at least $$$10$$$, we get a candy. After that, we replace every pair of numbers with a remainder of the division of their sum by $$$10$$$ (and don't change the order of the numbers).Perform this operation with a resulting array until it becomes of length $$$1$$$. Let $$$f([a_1, a_2, \ldots, a_{2^k}])$$$ denote the number of candies we get in this process. For example: if the starting sequence is $$$[8, 7, 3, 1, 7, 0, 9, 4]$$$ then:After the first operation the sequence becomes $$$[(8 + 7)\bmod 10, (3 + 1)\bmod 10, (7 + 0)\bmod 10, (9 + 4)\bmod 10]$$$ $$$=$$$ $$$[5, 4, 7, 3]$$$, and we get $$$2$$$ candies as $$$8 + 7 \ge 10$$$ and $$$9 + 4 \ge 10$$$.After the second operation the sequence becomes $$$[(5 + 4)\bmod 10, (7 + 3)\bmod 10]$$$ $$$=$$$ $$$[9, 0]$$$, and we get one more candy as $$$7 + 3 \ge 10$$$. After the final operation sequence becomes $$$[(9 + 0) \bmod 10]$$$ $$$=$$$ $$$[9]$$$. Therefore, $$$f([8, 7, 3, 1, 7, 0, 9, 4]) = 3$$$ as we got $$$3$$$ candies in total.You are given a sequence of digits of length $$$n$$$ $$$s_1, s_2, \ldots s_n$$$. You have to answer $$$q$$$ queries of the form $$$(l_i, r_i)$$$, where for $$$i$$$-th query you have to output $$$f([s_{l_i}, s_{l_i+1}, \ldots, s_{r_i}])$$$. It is guaranteed that $$$r_i-l_i+1$$$ is of form $$$2^k$$$ for some nonnegative integer $$$k$$$.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the sequence. The second line contains $$$n$$$ digits $$$s_1, s_2, \ldots, s_n$$$ ($$$0 \le s_i \le 9$$$). The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$) — the number of queries. Each of the next $$$q$$$ lines contains two integers $$$l_i$$$, $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — $$$i$$$-th query. It is guaranteed that $$$r_i-l_i+1$$$ is a nonnegative integer power of $$$2$$$.

Output $$$q$$$ lines, in $$$i$$$-th line output single integer — $$$f([s_{l_i}, s_{l_i + 1}, \ldots, s_{r_i}])$$$, answer to the $$$i$$$-th query.

NoteThe first example illustrates an example from the statement.$$$f([7, 3, 1, 7]) = 1$$$: sequence of operations is $$$[7, 3, 1, 7] \to [(7 + 3)\bmod 10, (1 + 7)\bmod 10]$$$ $$$=$$$ $$$[0, 8]$$$ and one candy as $$$7 + 3 \ge 10$$$ $$$\to$$$ $$$[(0 + 8) \bmod 10]$$$ $$$=$$$ $$$[8]$$$, so we get only $$$1$$$ candy.$$$f([9]) = 0$$$ as we don't perform operations with it.

module M = Map.Make (struct type t = int * int let compare = compare end)

let () =
    let split s =
        let rec loop i cur flag acc =
            if i = String.length s then (
                if flag then cur :: acc else acc
            ) else (
                match flag, s.[i] with
                | true,  ' ' -> loop (i + 1) 0 false (cur :: acc)
                | false, ' ' -> loop (i + 1) 0 false acc
                | true,  v   -> loop (i + 1) (cur * 10 + int_of_char v - 48) true acc
                | false, v   -> loop (i + 1) (cur * 10 + int_of_char v - 48) true acc
            )
        in
        List.rev (loop 0 0 false [])
    in
    let main () =
        let _ = int_of_string (read_line ()) in
        let s = Array.of_list (split (read_line ())) in
        let q = int_of_string (read_line ()) in
        let arr = Array.make_matrix 16 100001 (-1) in
        let lookup = Array.make 65537 (-1) in
        for i = 0 to 15 do
            lookup.((2 lsl i) - 1) <- i;
        done;
        let query () =
            let l, r = Scanf.sscanf (read_line ()) "%d %d" (fun l r -> l - 1, r - 1) in
            let rec subq l r =
                if l = r then 0 else
                    let key = lookup.(r - l) in
                    if arr.(key).(l) >= 0 then arr.(key).(l) else
                        if r = l + 1 then (
                            let sum = s.(l) + s.(r) in
                            let c = if sum >= 10 then 1 else 0 in
                            c * 10 + sum mod 10
                        ) else
                            let ab1 = subq l ((r + l) / 2) in
                            let ab2 = subq ((r + l) / 2 + 1) r in
                            let a1 = ab1 / 10 in
                            let b1 = ab1 mod 10 in
                            let a2 = ab2 / 10 in
                            let b2 = ab2 mod 10 in
                            let a = if b1 + b2 >= 10 then a1 + a2 + 1 else a1 + a2 in
                            let b = (b1 + b2) mod 10 in
                            let v = a * 10 + b in
                            let () = arr.(key).(l) <- v in
                            v
            in
            let candy10 = subq l r in
            Printf.printf "%d\n" (candy10 / 10)
        in
        for i = 1 to q do
            query ()
        done
    in
    main ()


There are $$$n$$$ slimes in a row. Each slime has an integer value (possibly negative or zero) associated with it.Any slime can eat its adjacent slime (the closest slime to its left or to its right, assuming that this slime exists). When a slime with a value $$$x$$$ eats a slime with a value $$$y$$$, the eaten slime disappears, and the value of the remaining slime changes to $$$x - y$$$.The slimes will eat each other until there is only one slime left. Find the maximum possible value of the last slime.

The first line of the input contains an integer $$$n$$$ ($$$1 \le n \le 500\,000$$$) denoting the number of slimes. The next line contains $$$n$$$ integers $$$a_i$$$ ($$$-10^9 \le a_i \le 10^9$$$), where $$$a_i$$$ is the value of $$$i$$$-th slime.

Print an only integer — the maximum possible value of the last slime.

NoteIn the first example, a possible way of getting the last slime with value $$$4$$$ is:  Second slime eats the third slime, the row now contains slimes $$$2, -1, 1$$$ Second slime eats the third slime, the row now contains slimes $$$2, -2$$$ First slime eats the second slime, the row now contains $$$4$$$ In the second example, the first slime can keep eating slimes to its right to end up with a value of $$$4$$$.

open Printf open Scanf
module MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end
module MyInt64 = struct
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v)) let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v) let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done
	let string_of_list ?(separator=" ") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls "" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
	let (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v
	let ceildiv m n = (m+n-1L) / n
end open MyInt64

let foldi_left f v a =
	let m = ref v in for i=0 to (Array.length a -$ 1) do
		m := f !m (~~|i) a.(i)
	done; !m
let for_all f a =
	let fc = ref true in
	for i=0 to (Array.length a -$1 ) do
		if not (f a.(i)) then fc := false
	done; !fc

let sum a = Array.fold_left (+) 0L a

let () =
	let n = get_i64 0 in
	let a = input_i64_array n in
	Array.sort compare a;
	(
		if n = 1L then a @ (0L) else
		if a @ (n-1L) < 0L then (
			(* (a @ (n-1L)) - sum a *)
			labs (sum a) + (a @ (n-1L)) * 2L
		) else if a @ 0L > 0L then (
			labs (sum a) - (a @ 0L) * 2L
		) else (
			foldi_left (fun (sneg,f,spos,pmin) i v ->
				if v < 0L then (sneg - v,f,spos,pmin)
				else if not f && v >= 0L then (
					(sneg,true,v,v)
				)
				else (
					(sneg,f,spos+v,pmin)
				)
			) (0L,false,0L,0L) a
			|> (fun (sneg,_,spos,pmin) -> sneg + spos)
		)
		(*
			foldi_left (fun (sneg,f,spos,pmin) i v ->
				if v < 0L then (sneg - v,f,spos,pmin)
				else if not f && v >= 0L then (
					(sneg,true,v,v)
				)
				else (
					(sneg,f,spos+v,pmin)
				)
			) (0L,false,0L,0L) a
			|> (fun (sneg,_,spos,pmin) -> sneg + spos - pmin * 2L)
		) *)
	)
	|> printf "%Ld\n"
(*
	foldi_left (fun (sneg,f) i v ->
		if v < 0L then (sneg - v,f)
		else if i = n-1L then (

		) else (

		)
	) 0L a
	|> printf "%Ld\n" *)

open Printf open Scanf
module MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end
module MyInt64 = struct
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v)) let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v) let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done
	let string_of_list ?(separator=" ") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls "" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
	let (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v
	let ceildiv m n = (m+n-1L) / n
end open MyInt64

let foldi_left f v a =
	let m = ref v in for i=0 to (Array.length a -$ 1) do
		m := f !m (~~|i) a.(i)
	done; !m
let for_all f a =
	let fc = ref true in
	for i=0 to (Array.length a -$1 ) do
		if not (f a.(i)) then fc := false
	done; !fc

let sum a = Array.fold_left (+) 0L a

let () =
	let n = get_i64 0 in
	let a = input_i64_array n in
	Array.sort compare a;
	(
		if a @ (n-1L) < 0L then (
			(a @ (n-1L)) - sum a
		) else (
			foldi_left (fun (sneg,f,spos,pmin) i v ->
				if v < 0L then (sneg - v,f,spos,pmin)
				else if not f && v >= 0L then (
					(sneg,true,v,v)
				)
				else (
					(sneg,f,spos+v,pmin)
				)
			) (0L,false,0L,0L) a
			|> (fun (sneg,_,spos,pmin) -> sneg + spos - pmin * 2L)
		)
	)
	|> printf "%Ld\n"

open Printf open Scanf
module MyInt = struct let (+) = (+) let (-) = (-) let (/) = (/) let ( * ) = ( * ) let (mod) = (mod) let (%) = (mod) let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v end
module MyInt64 = struct
	let (+$) = (+) let (-$) = (-) let (/$) = (/) let ( *$) = ( * ) let (+) p q = Int64.add p q let (-) p q = Int64.sub p q let ( * ) p q = Int64.mul p q let (/) p q = Int64.div p q let (+=) r v = r := !r + v let (-=) r v = r := !r - v let ( *=) r v= r := !r * v let (/=) r v = r := !r / v let labs p = if p < 0L then -1L*p else p let (~|) p = Int64.to_int p let (~~|) p = Int64.of_int p let input_i64_array n = Array.init (~| n) (fun _ -> Scanf.scanf " %Ld" (fun v -> v)) let get_i64 _ = Scanf.scanf " %Ld" (fun v -> v) let get_2_i64 _ = Scanf.scanf " %Ld %Ld" (fun u v -> u,v) let get_3_i64 _ = Scanf.scanf " %Ld %Ld %Ld" (fun u v w -> u,v,w) let get_4_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld" (fun u v w x -> u,v,w,x) let get_5_i64 _ = Scanf.scanf " %Ld %Ld %Ld %Ld %Ld" (fun u v w x y -> u,v,w,x,y) let print_i64_endline n = n |> Int64.to_string |> print_endline let (mod) m n = m - (m/n) * n let (%) = (mod) let rec gcd m n = match m,n with | m,0L -> m | m,n -> gcd n (m mod n) let lcm m n = (m*n) / gcd m n let rep from_ to_ fbod = let i,f = ref ~|from_,ref true in while !i <= ~|to_ && !f do match fbod ~~| !i with | `Break -> f := false | _ -> i := !i +$ 1; done
	let string_of_list ?(separator=" ") f ls = let rec f0 a s = match a with | [] -> s | [h] -> s ^ (f h) ^ separator | h::t -> f0 t (s ^ (f h) ^ separator) in f0 ls "" let char_list_of_string str = let rec f0 i a = if i<0 then a else f0 (i-$1) (str.[i]::a) in f0 (String.length str -$ 1) [] let string_of_char_list ls = List.fold_left (fun u v -> u ^ (String.make 1 v)) "" ls
	let (@@@) = (@) let (@) a i = a.(~|i) let (<@) a (i,v) = a.(~|i) <- v
	let ceildiv m n = (m+n-1L) / n
end open MyInt64

let foldi_left f v a =
	let m = ref v in for i=0 to (Array.length a -$ 1) do
		m := f !m (~~|i) a.(i)
	done; !m
let for_all f a =
	let fc = ref true in
	for i=0 to (Array.length a -$1 ) do
		if not (f a.(i)) then fc := false
	done; !fc

let sum a = Array.fold_left (+) 0L a

let () =
	let n = get_i64 0 in
	let a = input_i64_array n in
	Array.sort compare a;
	(
		if n = 1L then a @ (0L) else
		if a @ (n-1L) < 0L then (
			(* (a @ (n-1L)) - sum a *)
			labs (sum a) + (a @ (n-1L)) * 2L
		) else (
			foldi_left (fun (sneg,f,spos,pmin) i v ->
				if v < 0L then (sneg - v,f,spos,pmin)
				else if not f && v >= 0L then (
					(sneg,true,v,v)
				)
				else (
					(sneg,f,spos+v,pmin)
				)
			) (0L,false,0L,0L) a
			|> (fun (sneg,_,spos,pmin) -> sneg + spos - pmin * 2L)
		)
	)
	|> printf "%Ld\n"


The Fair Nut found a string $$$s$$$. The string consists of lowercase Latin letters. The Nut is a curious guy, so he wants to find the number of strictly increasing sequences $$$p_1, p_2, \ldots, p_k$$$, such that:   For each $$$i$$$ ($$$1 \leq i \leq k$$$), $$$s_{p_i} =$$$ 'a'.  For each $$$i$$$ ($$$1 \leq i < k$$$), there is such $$$j$$$ that $$$p_i < j < p_{i + 1}$$$ and $$$s_j =$$$ 'b'. The Nut is upset because he doesn't know how to find the number. Help him.This number should be calculated modulo $$$10^9 + 7$$$.

The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 10^5$$$) consisting of lowercase Latin letters.

In a single line print the answer to the problem — the number of such sequences $$$p_1, p_2, \ldots, p_k$$$ modulo $$$10^9 + 7$$$.

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

module CumulSumArray = struct
  let make a =
    let ln = Array.length a
    in let a1 = Array.make (ln+$1) 0L in for i=1 to ln do a1.(i) <- a1.(i-$1) + a.(i-$1) done; a1
  let sum l r a = (* 0-origin,closed *)
    if l>r then 0L else (a.(r+$1) - a.(l))
  let sum_1orig l r a = sum (l-$1) (r-$1) a
end
module Imos = struct
  let make n = Array.make (i32 n +$ 2) 0L
  let add_destructive_closed l r a =
    a.(l+$1) <- a.(l+$1) + 1L;
    a.(r+$2) <- a.(r+$2) - 1L
  let add_destructive_1orig_closed l r a =
    a.(l) <- a.(l) + 1L;
    a.(r+$1) <- a.(r+$1) - 1L
  let add_destructive_1orig_closed_safe l r a =
    let l = max l 0 in a.(l) <- a.(l) + 1L;
    let r = min (r+$1) (Array.length a-$1) in a.(r) <- a.(r) - 1L
  let cumulate_destructive a =
    for i=1 to Array.length a -$ 2 do a.(i) <- a.(i) + a.(i-$1) done
end
let () =
  let s = scanf " %s" @@ id in
  let n = String.length s in
  (* let a = make (String.length s) 'z' in
  (* let b = make (String.length s) 0L in *)
  let b = Imos.make @@ i64 n in
  String.iteri (fun i v -> a.(i) <- v;
    (* if v='b' then b.(i) <- 1L; *)
    if v='b' then Imos.add_destructive_1orig_closed i i b;
  ) s;
  Imos.cumulate_destructive b;
  (* let b_query = Imos.make b in *)
  (* iteri (fun i v ->
    if v='a' then (

    )
  ) a; *)
  let dp = make (n+$1) 0L in
  let fprev = ref false in
  repi 1 n (fun i ->
    if s.[i] = 'a' then (
      dp.(i) <- dp.(i) + 1L;
    )
  ) *)
  (* let r = ref [] in
  let rr = ref [] in
  String.iter (fun v ->
    (* printf "%c:" v; *)
    if v='a' then r := v::!r
    else if v='b' then (
      if List.length !r > 0 then (
        rr := (List.rev !r) :: !rr;
        r := []
      )
    );
    (* List.iter (fun ls -> print_list (String.make 1) ls) (List.rev !rr); *)
    (* print_list (String.make 1) !r; *)
  ) s;
  if List.length !r > 0 then (
    rr := (List.rev !r) :: !rr;
  );
  rr := List.rev !rr;
  (* List.iter (fun ls -> print_list (String.make 1) ls) !rr; *)
  List.fold_left (fun u ls ->
    let k = llen ls in
    let r = u + u * k + k in
    (* printf "%Ld\n" r; *)
    r
  ) 0L !rr
  |> printf "%Ld\n"; *)
  let md = 1000000007L in
  let r = ref 0L in let rr = ref [] in
  String.iter (fun v ->
    if v='a' then r += 1L
    else if v='b' then (
      if !r>0L then (
        rr := !r :: !rr;
        r := 0L
      )
    )
  ) s;
  if !r>0L then rr := !r :: !rr;
  let rr = List.rev !rr in
  List.fold_left (fun u k ->
    let r = (u + ((u * k) mod md) + k) mod md in
    r
  ) 0L rr
  |> printf "%Ld\n";


Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program results in two integers x and y (x + y = 10; x, y ≥ 0). These numbers mean that x packets successfully reached the corresponding server through the network and y packets were lost.Today Polycarpus has performed overall n ping commands during his workday. Now for each server Polycarpus wants to know whether the server is "alive" or not. Polycarpus thinks that the server is "alive", if at least half of the packets that we send to this server reached it successfully along the network.Help Polycarpus, determine for each server, whether it is "alive" or not by the given commands and their results.

The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of commands Polycarpus has fulfilled. Each of the following n lines contains three integers — the description of the commands. The i-th of these lines contains three space-separated integers ti, xi, yi (1 ≤ ti ≤ 2; xi, yi ≥ 0; xi + yi = 10). If ti = 1, then the i-th command is "ping a", otherwise the i-th command is "ping b". Numbers xi, yi represent the result of executing this command, that is, xi packets reached the corresponding server successfully and yi packets were lost. It is guaranteed that the input has at least one "ping a" command and at least one "ping b" command.

In the first line print string "LIVE" (without the quotes) if server a is "alive", otherwise print "DEAD" (without the quotes). In the second line print the state of server b in the similar format.

NoteConsider the first test case. There 10 packets were sent to server a, 5 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall there were 10 packets sent to server b, 6 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network.Consider the second test case. There were overall 20 packages sent to server a, 10 of them reached it. Therefore, at least half of all packets sent to this server successfully reached it through the network. Overall 10 packets were sent to server b, 0 of them reached it. Therefore, less than half of all packets sent to this server successfully reached it through the network.

let read_three () = Scanf.bscanf Scanf.Scanning.stdib " %d %d %d " (fun x y z -> (x,y,z))
let read_int () = Scanf.bscanf Scanf.Scanning.stdib " %d " (fun x -> x)

let () =
  let n = read_int() in
  let ret = Array.make 2 0 in
  let tot = Array.make 2 0 in
    for i=0 to n-1 do
      let (t,x,y) = read_three() in
      let t = t-1 in
    ret.(t) <- ret.(t) + x;
    tot.(t) <- tot.(t) + 10;
    done;
    for j=0 to 1 do
      if 2*ret.(j) >= tot.(j) then print_string "LIVE\n" else print_string "DEAD\n"
    done

let n = read_int()

let goods = Array.make 2 0 ;;
let totals = Array.make 2 0 ;;

let handle i good bad =
    let total = good + bad in
    let idx = i - 1 in
        Array.set goods idx (Array.get goods idx + good) ;
        Array.set totals idx (Array.get totals idx + total);;

for i = 1 to n do
    Scanf.scanf "%d %d %d\n" handle
done ;;

for i = 0 to 1 do
    Printf.printf "%s\n" (if (Array.get goods i) >= (Array.get totals i) / 2 then "LIVE" else "DEAD" );
done ;;

let n = read_int()

let goods = Array.make 2 0 ;;
let totals = Array.make 2 0 ;;

let handle i good total =
    let idx = i - 1 in
        Array.set goods idx (Array.get goods idx + good) ;
        Array.set totals idx (Array.get totals idx + total);;

for i = 1 to n do
    Scanf.scanf "%d %d %d\n" handle
done ;;

for i = 0 to 1 do
    Printf.printf "%s\n" (if (Array.get goods i) >= (Array.get totals i) / 2 then "LIVE" else "DEAD" );
done ;;


Ivan decided to prepare for the test on solving integer equations. He noticed that all tasks in the test have the following form:  You are given two positive integers $$$u$$$ and $$$v$$$, find any pair of integers (not necessarily positive) $$$x$$$, $$$y$$$, such that: $$$$$$\frac{x}{u} + \frac{y}{v} = \frac{x + y}{u + v}.$$$$$$  The solution $$$x = 0$$$, $$$y = 0$$$ is forbidden, so you should find any solution with $$$(x, y) \neq (0, 0)$$$. Please help Ivan to solve some equations of this form.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of test cases. The next lines contain descriptions of test cases. The only line of each test case contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq 10^9$$$) — the parameters of the equation.

For each test case print two integers $$$x$$$, $$$y$$$ — a possible solution to the equation. It should be satisfied that $$$-10^{18} \leq x, y \leq 10^{18}$$$ and $$$(x, y) \neq (0, 0)$$$. We can show that an answer always exists. If there are multiple possible solutions you can print any.

(*
x/u+y/v=(x+y)/(u+v)
(x*(u+v)/u)+(y*(u+v)/v) = x+y
x*v/u+y*u/v = 0
x=-y*u/v**2
*)

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

let run_case = function
| () ->
     let u=read_long () in
     let v=read_long () in
     let y=Int64.mul (Int64.mul v v) (-1L) in
     let x=Int64.mul u u in
     Printf.printf "%Ld %Ld\n" x y
;;

let rec iter_cases = function
| 0 -> ()
| t ->
     run_case ();
     iter_cases (t-1)
;;

let t=read_int () in
iter_cases (t);;


One day, Vogons wanted to build a new hyperspace highway through a distant system with $$$n$$$ planets. The $$$i$$$-th planet is on the orbit $$$a_i$$$, there could be multiple planets on the same orbit. It's a pity that all the planets are on the way and need to be destructed.Vogons have two machines to do that.  The first machine in one operation can destroy any planet at cost of $$$1$$$ Triganic Pu.  The second machine in one operation can destroy all planets on a single orbit in this system at the cost of $$$c$$$ Triganic Pus. Vogons can use each machine as many times as they want.Vogons are very greedy, so they want to destroy all planets with minimum amount of money spent. Can you help them to know the minimum cost of this project?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then the test cases follow. Each test case consists of two lines. The first line contains two integers $$$n$$$ and $$$c$$$ ($$$1 \le n, c \le 100$$$) — the number of planets and the cost of the second machine usage. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the orbit of the $$$i$$$-th planet.

For each test case print a single integer — the minimum cost of destroying all planets.

NoteIn the first test case, the cost of using both machines is the same, so you can always use the second one and destroy all planets in orbit $$$1$$$, all planets in orbit $$$2$$$, all planets in orbit $$$4$$$, all planets in orbit $$$5$$$.In the second test case, it is advantageous to use the second machine for $$$2$$$ Triganic Pus to destroy all the planets in orbit $$$2$$$, then destroy the remaining two planets using the first machine.In the third test case, you can use the first machine twice or the second machine once.In the fourth test case, it is advantageous to use the first machine twice.

open Printf
open Scanf

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

let read_int _ = bscanf Scanning.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,c) = read_pair () in
    let a = Array.init n read_int in
    let hist = Array.make 101 0 in
    for i=0 to n-1 do
      hist.(a.(i)) <- hist.(a.(i)) + 1
    done;
    let answer = sum 0 100 (fun x -> min hist.(x) c) in
    printf "%d\n" answer
  done


Monocarp has forgotten the password to his mobile phone. The password consists of $$$4$$$ digits from $$$0$$$ to $$$9$$$ (note that it can start with the digit $$$0$$$).Monocarp remembers that his password had exactly two different digits, and each of these digits appeared exactly two times in the password. Monocarp also remembers some digits which were definitely not used in the password.You have to calculate the number of different sequences of $$$4$$$ digits that could be the password for Monocarp's mobile phone (i. e. these sequences should meet all constraints on Monocarp's password).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of testcases. The first line of each testcase contains a single integer $$$n$$$ ($$$1 \le n \le 8$$$) — the number of digits for which Monocarp remembers that they were not used in the password. The second line contains $$$n$$$ different integers $$$a_1, a_2, \dots a_n$$$ ($$$0 \le a_i \le 9$$$) representing the digits that were not used in the password. Note that the digits $$$a_1, a_2, \dots, a_n$$$ are given in ascending order.

For each testcase, print one integer — the number of different $$$4$$$-digit sequences that meet the constraints.

NoteIn the first example, all possible passwords are: "3377", "3737", "3773", "7337", "7373", "7733".

module A = Array
module L = List
module I = Int64

let pf = Printf.printf
let sf = Scanf.scanf
let read_int () = sf " %d" (fun x -> x)
let read_array read n = A.init n (fun _ -> read ())

let read_matrix read n m = A.init n (fun _ -> read_array read m)

let () =
  let t = read_int () in
  for _ = 1 to t do
    let n = read_int () in
    let _a = read_array read_int n in
    pf "%d\n" (3 * (10 - n) * (10 - n - 1))
  done;

  (* let totalN = 1 lsl n in
  let a = read_array (fun _ -> I.of_int @@ read_int ()) totalN in
  let segSize = (n + 1) / 2 in
  let groupsSize = n - segSize in
  let maxXor = 1 lsl segSize in
  let totGroups = 1 lsl groupsSize in

  let maxSum = A.make totGroups I.zero in
  let maxPref = A.make totGroups I.zero in
  let maxSuf = A.make totGroups I.zero in
  let sums = A.make totGroups I.zero in
  let prefSums = A.make totalN I.zero in

  prefSums.(0) <- a.(0);
  for i = 1 to totalN - 1 do
    prefSums.(i) <- I.add prefSums.(i - 1) @@ a.(i);
  done;

  let sumSeg l r =
    if (l = 0) then prefSums.(r)
    else I.sub prefSums.(r) prefSums.(l - 1)
  in

  let ans = A.make totalN I.zero in
  let prevSmallP = ref (-1) in

  for xr = 0 to totalN - 1 do
    let smallP = xr lsr groupsSize in

    if (!prevSmallP <> smallP) then begin
      prevSmallP := smallP;
      for gr = 0 to totGroups - 1 do
        let grShift = gr * maxXor in
        let prefSum = ref I.zero in
        let minPref = ref I.zero in
        let totSum = sumSeg grShift (grShift + maxXor - 1) in

        maxSum.(gr) <- I.zero;
        maxPref.(gr) <- I.zero;
        maxSuf.(gr) <- totSum;
        sums.(gr) <- totSum;

        for i = 0 to maxXor - 1 do
          let cur = a.(i lxor smallP + grShift) in
          prefSum := I.add !prefSum cur;
          maxSum.(gr) <- max maxSum.(gr) (I.sub !prefSum !minPref);
          maxPref.(gr) <- max maxPref.(gr) !prefSum;
          maxSuf.(gr) <- max maxSuf.(gr) (I.sub totSum !prefSum);
          minPref := min !minPref !prefSum;
        done
      done
    end;

    let bigP = xr land (totGroups - 1) in
    let mPref = ref maxPref.(bigP) in
    let mSuf = ref maxSuf.(bigP) in
    let mSum = ref maxSum.(bigP) in
    let sm = ref sums.(bigP) in
    for grXored = 1 to totGroups - 1 do
      let gr = grXored lxor bigP in
      mSum := max (max !mSum maxSum.(gr)) (I.add !mSuf maxPref.(gr));
      mPref := max !mPref (I.add !sm maxPref.(gr));
      mSuf := max (I.add !mSuf sums.(gr)) maxSuf.(gr);
      sm := I.add !sm sums.(gr)
    done;
    ans.(xr) <- !mSum;
  done;

  let xr = ref 0 in
  let q = read_int () in
  for _ = 1 to q do
    let b = read_int () in
    xr := !xr lxor (1 lsl b);
    let nxr = (!xr lsr segSize) + (!xr land (maxXor - 1)) * totGroups in
    pf "%Ld\n" ans.(nxr);
  done; *)


While resting on the ship after the "Russian Code Cup" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size n × m, consisting of positive integers such that the sum of the squares of numbers for each row and each column was also a square.Since checking the correctness of the table manually is difficult, Misha asks you to make each number in the table to not exceed 108.

The first line contains two integers n and m (1 ≤ n, m ≤ 100)  — the size of the table.

Print the table that meets the condition: n lines containing m integers, separated by spaces. If there are multiple possible answers, you are allowed to print anyone. It is guaranteed that there exists at least one correct answer.

let read_int()=Scanf.scanf " %d" (fun x->x);;
let n=read_int() and m=read_int();;
let mat=Array.make_matrix (n+1) (m+1) 1;;
let is_square a=(int_of_float(sqrt(float_of_int(a)))*int_of_float(sqrt(float_of_int(a)))=a);;
if n=2 then
   begin
   for j=1 to m do
      mat.(1).(j)<-mat.(1).(j)*3;
      mat.(2).(j)<-mat.(2).(j)*4
   done
   end
else
   begin
   if is_square n then () else
      begin
      if n mod 2=1 then
         begin
         for j=1 to m do
            mat.(1).(j)<-mat.(1).(j)*2
         done;
         for j=1 to m do
            mat.(n).(j)<-mat.(n).(j)*(n+1)/2
         done
         end
      else
         begin
         for j=1 to m do
            mat.(n).(j)<-mat.(n).(j)*(n-2)/2
         done
         end
      end
   end;;

if m=2 then
   begin
   for i=1 to n do
      mat.(i).(1)<-mat.(i).(1)*3;
      mat.(i).(2)<-mat.(i).(2)*4
   done
   end
else
   begin
   if is_square m then () else
      begin
      if m mod 2=1 then
         begin
         for i=1 to n do
            mat.(i).(1)<-mat.(i).(1)*2
         done;
         for i=1 to n do
            mat.(i).(m)<-mat.(i).(m)*(m+1)/2
         done
         end
      else
         begin
         for i=1 to n do
            mat.(i).(m)<-mat.(i).(m)*(m-2)/2
         done
         end
      end
   end;;
for i=1 to n do
   for j=1 to m do
      Printf.printf "%d " mat.(i).(j)
   done;
   print_newline()
done;;

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 a = Array.make_matrix n m 0 in
  let x = Array.make m 2 in
  let y = Array.make n 2 in
    if m = 1
    then x.(0) <- 1
    else if m = 2
    then (
      x.(0) <- 3;
      x.(1) <- 4;
    ) else x.(m - 1) <- m - 2;
    if n = 1
    then y.(0) <- 1
    else if n = 2
    then (
      y.(0) <- 3;
      y.(1) <- 4;
    ) else y.(n - 1) <- n - 2;
    for i = 0 to n - 1 do
      for j = 0 to m - 1 do
	a.(i).(j) <- y.(i) * x.(j);
      done;
    done;
    for i = 0 to n - 1 do
      for j = 0 to m - 1 do
	Printf.printf "%d " a.(i).(j);
      done;
      Printf.printf "\n"
    done;


Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≤ li < ri ≤ n). The answer to the query li, ri is the number of such integers i (li ≤ i < ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.

The first line contains string s of length n (2 ≤ n ≤ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≤ li < ri ≤ n).

Print m integers — the answers to the queries in the order in which they are given in the input.

let read format = Scanf.scanf format (fun x -> x)

let make_list n =
    let rec loop i list =
        if i < n
        then
            let a = read "%d " in
            let b = read "%d " in
            loop (i + 1) ((a, b) :: list)
        else
            List.rev list
    in loop 0 []

let get_identical_pairs string =
    let l = String.length string in
    let pairs = Array.make l 0 in
    let rec loop i previous count =
        if i < l
        then
            let current = string.[i] in
            (if current = previous
            then
                (pairs.(i) <- (count + 1);
                loop (i + 1) current (count + 1))
            else
                (pairs.(i) <- count;
                loop (i + 1) current count));
        else
            pairs
    in loop 1 string.[0] 0

let count_identical_pairs pairs (a, b) =
    pairs.(b - 1) - pairs.(a - 1)

let input () =
    let string = read "%s " in
    let n = read "%d " in
    let queries = make_list n in
    (string, queries)

let solve (string, queries) =
    let pairs = get_identical_pairs string in
    let result = List.map (count_identical_pairs pairs) queries in
    result

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


You are given a board of size $$$n \times n$$$, where $$$n$$$ is odd (not divisible by $$$2$$$). Initially, each cell of the board contains one figure.In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell $$$(i, j)$$$ you can move the figure to cells:   $$$(i - 1, j - 1)$$$;  $$$(i - 1, j)$$$;  $$$(i - 1, j + 1)$$$;  $$$(i, j - 1)$$$;  $$$(i, j + 1)$$$;  $$$(i + 1, j - 1)$$$;  $$$(i + 1, j)$$$;  $$$(i + 1, j + 1)$$$; Of course, you can not move figures to cells out of the board. It is allowed that after a move there will be several figures in one cell.Your task is to find the minimum number of moves needed to get all the figures into one cell (i.e. $$$n^2-1$$$ cells should contain $$$0$$$ figures and one cell should contain $$$n^2$$$ figures).You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 200$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains one integer $$$n$$$ ($$$1 \le n < 5 \cdot 10^5$$$) — the size of the board. It is guaranteed that $$$n$$$ is odd (not divisible by $$$2$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$5 \cdot 10^5$$$ ($$$\sum n \le 5 \cdot 10^5$$$).

For each test case print the answer — the minimum number of moves needed to get all the figures into one cell.

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

let rec get_somme = function
| 0 -> 0L
| n -> Int64.add (Int64.mul 8L (Int64.mul (Int64.of_int n) (Int64.of_int n))) (get_somme (n - 1))
in

let nbTests = read () in
for iTest = 1 to nbTests do
   let n = (read () - 1) / 2 in

   print_string (Int64.to_string (get_somme n));
   print_newline()
done;


You are given an array $$$a$$$ consisting of $$$n$$$ integers. Each $$$a_i$$$ is one of the six following numbers: $$$4, 8, 15, 16, 23, 42$$$.Your task is to remove the minimum number of elements to make this array good.An array of length $$$k$$$ is called good if $$$k$$$ is divisible by $$$6$$$ and it is possible to split it into $$$\frac{k}{6}$$$ subsequences $$$4, 8, 15, 16, 23, 42$$$.Examples of good arrays:  $$$[4, 8, 15, 16, 23, 42]$$$ (the whole array is a required sequence);  $$$[4, 8, 4, 15, 16, 8, 23, 15, 16, 42, 23, 42]$$$ (the first sequence is formed from first, second, fourth, fifth, seventh and tenth elements and the second one is formed from remaining elements);  $$$[]$$$ (the empty array is good). Examples of bad arrays:   $$$[4, 8, 15, 16, 42, 23]$$$ (the order of elements should be exactly $$$4, 8, 15, 16, 23, 42$$$);  $$$[4, 8, 15, 16, 23, 42, 4]$$$ (the length of the array is not divisible by $$$6$$$);  $$$[4, 8, 15, 16, 23, 42, 4, 8, 15, 16, 23, 23]$$$ (the first sequence can be formed from first six elements but the remaining array cannot form the required sequence).

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ (each $$$a_i$$$ is one of the following numbers: $$$4, 8, 15, 16, 23, 42$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$.

Print one integer — the minimum number of elements you have to remove to obtain a good array.

let read_x x_of_string () = read_line () |> Str.(split (regexp " ")) |> List.map x_of_string;;
let read_ints = read_x int_of_string;;
let read_int64s = read_x Int64.of_string;;
let print_x string_of_x xs = List.map string_of_x xs |> String.concat " " |> print_endline;;
let print_ints = print_x string_of_int;;
let print_int64s = print_x Int64.to_string;;

let [n] = read_ints ();;
let a = read_ints ();;
let c = Array.make 6 0;;
let r = ref 0;;
let pos = function
  | 4 -> Some 0
  | 8 -> Some 1
  | 15 -> Some 2
  | 16 -> Some 3
  | 23 -> Some 4
  | 42 -> Some 5
  | _ -> None;;
let step x = match pos x with
  | Some 0 -> c.(0) <- c.(0) + 1
  | Some p -> if c.(p) < c.(p-1) then c.(p) <- c.(p) + 1 else incr r
  | None -> incr r;;
List.map step a;;
for i = 4 downto 0 do
  r := !r + c.(i) - c.(i+1);
  c.(i) <- c.(i+1);
done;;
print_ints [!r];;


The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that one could any point of any country can be reached from any point of any other State.Since roads are always expensive, the governments of the states of the newly formed alliance asked you to help them assess the costs. To do this, you have been issued a map that can be represented as a rectangle table consisting of n rows and m columns. Any cell of the map either belongs to one of three states, or is an area where it is allowed to build a road, or is an area where the construction of the road is not allowed. A cell is called passable, if it belongs to one of the states, or the road was built in this cell. From any passable cells you can move up, down, right and left, if the cell that corresponds to the movement exists and is passable.Your task is to construct a road inside a minimum number of cells, so that it would be possible to get from any cell of any state to any cell of any other state using only passable cells.It is guaranteed that initially it is possible to reach any cell of any state from any cell of this state, moving only along its cells. It is also guaranteed that for any state there is at least one cell that belongs to it.

The first line of the input contains the dimensions of the map n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns respectively. Each of the next n lines contain m characters, describing the rows of the map. Digits from 1 to 3 represent the accessory to the corresponding state. The character '.' corresponds to the cell where it is allowed to build a road and the character '#' means no construction is allowed in this cell.

Print a single integer — the minimum number of cells you need to build a road inside in order to connect all the cells of all states. If such a goal is unachievable, print -1.

open Printf
open Scanf

let shortest_path n graph s =
  let inf = 10_000_000 in
  let frozen = Array.make n false in
  let dist = Array.make n inf in
  let rec dijkstra (zero,one) =
    if zero=[] && one=[] then dist else
      let (zero,one) = if zero=[] then (one,[]) else (zero,one) in
      let (v,zero) = (List.hd zero, List.tl zero) in
      let rec loop wlist (zero,one) = match wlist with [] -> (zero,one)
	| (l,w)::wlist ->
	    if dist.(w) <= dist.(v) + l then loop wlist (zero,one) else (
	      dist.(w) <- dist.(v) + l;
	      let (zero,one) = if l=0 then (w::zero, one) else (zero, w::one) in
		loop wlist (zero,one)
	    )
      in
	if frozen.(v) then dijkstra (zero,one) else (
	  frozen.(v) <- true;
	  dijkstra (loop graph.(v) (zero,one))
	)
  in
    dist.(s) <- 0;
    dijkstra ([s], [])

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_string () = bscanf Scanning.stdib " %s " (fun x -> x)
let read_pair () = bscanf Scanning.stdib " %d %d " (fun x y -> (x,y))
let isdigit c = c <= '9' && c >= '0'

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 () =
  let (n,m) = read_pair () in
  let board = Array.init n (fun _ -> read_string()) in

  let ng = n*m in
  let graph = Array.make ng [] in

  let vertex i j = i*m + j in

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

  let start = Array.make 3 0 in

  for i=0 to n-1 do
    for j=0 to m-1 do
      let v = vertex i j in
      let c = board.(i).[j] in
      if isdigit c then start.((int_of_char c) - int_of_char '1') <- v;
      let inbounds i j = 0<=i && i<n && 0<=j && j<m in
      List.iter (fun (i',j') ->
	if inbounds i' j' then (
	  let v' = vertex i' j' in
	  let c' = board.(i').[j'] in
	  if isdigit c && c = c' then addedge (v,v') 0
	  else if c <> '#' && c' <> '#' then addedge (v,v') 1
	)
      ) [(i-1,j);(i+1,j);(i,j-1);(i,j+1)];
    done
  done;

  let dist = Array.make 3 [||] in

  for i=0 to 2 do
    dist.(i) <- shortest_path ng graph start.(i)
  done;

  let score = -2 +
    minf 0 (ng-1) (fun v -> dist.(0).(v)+dist.(1).(v)+dist.(2).(v))
  in

  printf "%d\n" (if score>ng then -1 else score)

open Printf
open Scanf

let shortest_path n graph s =
  let inf = 1_000_000 in
  let frozen = Array.make n false in
  let dist = Array.make n inf in
  let rec dijkstra (zero,one) =
    if zero=[] && one=[] then dist else
      let (zero,one) = if zero=[] then (one,[]) else (zero,one) in
      let (v,zero) = (List.hd zero, List.tl zero) in
      let rec loop wlist (zero,one) = match wlist with [] -> (zero,one)
	| (l,w)::wlist ->
	    if dist.(w) <= dist.(v) + l then loop wlist (zero,one) else (
	      dist.(w) <- dist.(v) + l;
	      let (zero,one) = if l=0 then (w::zero, one) else (zero, w::one) in
		loop wlist (zero,one)
	    )
      in
	if frozen.(v) then dijkstra (zero,one) else (
	  frozen.(v) <- true;
	  dijkstra (loop graph.(v) (zero,one))
	)
  in
    dist.(s) <- 0;
    dijkstra ([s], [])

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let read_string () = bscanf Scanning.stdib " %s " (fun x -> x)
let read_pair () = bscanf Scanning.stdib " %d %d " (fun x y -> (x,y))
let isdigit c = c <= '9' && c >= '0'

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 () =
  let (n,m) = read_pair () in
  let board = Array.init n (fun _ -> read_string()) in

  let ng = n*m in
  let graph = Array.make ng [] in

  let vertex i j = i*m + j in

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

  let start = Array.make 3 0 in

  for i=0 to n-1 do
    for j=0 to m-1 do
      let v = vertex i j in
      let c = board.(i).[j] in
      if isdigit c then start.((int_of_char c) - int_of_char '1') <- v;
      let inbounds i j = 0<=i && i<n && 0<=j && j<m in
      List.iter (fun (i',j') ->
	if inbounds i' j' then (
	  let v' = vertex i' j' in
	  let c' = board.(i').[j'] in
	  if isdigit c && isdigit c' then addedge (v,v') 0
	  else if c <> '#' && c' <> '#' then addedge (v,v') 1
	)
      ) [(i-1,j);(i+1,j);(i,j-1);(i,j+1)];
    done
  done;

  let dist = Array.make 3 [||] in

  for i=0 to 2 do
    dist.(i) <- shortest_path ng graph start.(i)
  done;

  let score = -1 +
    minf 0 (ng-1) (fun v -> dist.(0).(v)+dist.(1).(v)+dist.(2).(v))
  in

  printf "%d\n" (if score>ng then -1 else score)


Polycarp has just attempted to pass the driving test. He ran over the straight road with the signs of four types.  speed limit: this sign comes with a positive integer number — maximal speed of the car after the sign (cancel the action of the previous sign of this type);  overtake is allowed: this sign means that after some car meets it, it can overtake any other car;  no speed limit: this sign cancels speed limit if any (car can move with arbitrary speed after this sign);  no overtake allowed: some car can't overtake any other car after this sign. Polycarp goes past the signs consequentially, each new sign cancels the action of all the previous signs of it's kind (speed limit/overtake). It is possible that two or more "no overtake allowed" signs go one after another with zero "overtake is allowed" signs between them. It works with "no speed limit" and "overtake is allowed" signs as well.In the beginning of the ride overtake is allowed and there is no speed limit.You are given the sequence of events in chronological order — events which happened to Polycarp during the ride. There are events of following types:  Polycarp changes the speed of his car to specified (this event comes with a positive integer number);  Polycarp's car overtakes the other car;  Polycarp's car goes past the "speed limit" sign (this sign comes with a positive integer);  Polycarp's car goes past the "overtake is allowed" sign;  Polycarp's car goes past the "no speed limit";  Polycarp's car goes past the "no overtake allowed"; It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).After the exam Polycarp can justify his rule violations by telling the driving instructor that he just didn't notice some of the signs. What is the minimal number of signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view?

The first line contains one integer number n (1 ≤ n ≤ 2·105) — number of events. Each of the next n lines starts with integer t (1 ≤ t ≤ 6) — the type of the event. An integer s (1 ≤ s ≤ 300) follows in the query of the first and the third type (if it is the query of first type, then it's new speed of Polycarp's car, if it is the query of third type, then it's new speed limit). It is guaranteed that the first event in chronological order is the event of type 1 (Polycarp changed the speed of his car to specified).

Print the minimal number of road signs Polycarp should say he didn't notice, so that he would make no rule violations from his point of view.

NoteIn the first example Polycarp should say he didn't notice the "speed limit" sign with the limit of 70 and the second "speed limit" sign with the limit of 120.In the second example Polycarp didn't make any rule violation.In the third example Polycarp should say he didn't notice both "no overtake allowed" that came after "overtake is allowed" sign.


Little penguin Polo likes permutations. But most of all he likes permutations of integers from 0 to n, inclusive.For permutation p = p0, p1, ..., pn, Polo has defined its beauty — number .Expression  means applying the operation of bitwise excluding "OR" to numbers x and y. This operation exists in all modern programming languages, for example, in language C++ and Java it is represented as "^" and in Pascal — as "xor".Help him find among all permutations of integers from 0 to n the permutation with the maximum beauty.

The single line contains a positive integer n (1 ≤ n ≤ 106).

In the first line print integer m the maximum possible beauty. In the second line print any permutation of integers from 0 to n with the beauty equal to m. If there are several suitable permutations, you are allowed to print any of them.

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

let ( ++ ) a b = Int64.add a b

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

let () =
  let n = read_int() in
  let ans = Array.make (n+1) 0 in
  let add (a,b) = ans.(a) <- b; ans.(b) <- a in

  let rec log n i = if (1 lsl (i+1)) >= n then i else log n (i+1) in

  let rec build_answer n =
    if n<=0 then ()
    else if n=1 then add (0,1)
    else
      let k = log (n+1) 0 in
      let p = 1 lsl k in
      let a = n + 1 - p in

      let rec build_pairs i =
	let hi = n-a+1+i in
	let lo = n-a-i in
	  if hi > n then () else (
	    add (lo,hi);
	    build_pairs (i+1)
	  )
      in
	build_pairs 0;
	build_answer (n-2*a)
  in

  let () = build_answer n in
  let score = sum 0 n (fun i -> Int64.of_int (i lxor ans.(i))) in
    Printf.printf "%Ld\n" score;
    for i=0 to n do
      Printf.printf "%d " ans.(i)
    done;
    print_newline()

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

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

let () =
  let n = read_int() in
  let ans = Array.make (n+1) 0 in
  let add (a,b) = ans.(a) <- b; ans.(b) <- a in

  let rec log n i = if (1 lsl (i+1)) >= n then i else log n (i+1) in

  let rec build_answer n =
    if n<=0 then ()
    else if n=1 then add (0,1)
    else
      let k = log (n+1) 0 in
      let p = 1 lsl k in
      let a = n + 1 - p in

      let rec build_pairs i =
	let hi = n-a+1+i in
	let lo = n-a-i in
	  if hi > n then () else (
	    add (lo,hi);
	    build_pairs (i+1)
	  )
      in
	build_pairs 0;
	build_answer (n-2*a)
  in

  let () = build_answer n in
  let score = sum 0 n (fun i -> i lxor ans.(i)) in
    Printf.printf "%d\n" score;
    for i=0 to n do
      Printf.printf "%d " ans.(i)
    done;
    print_newline()