While dad was at work, a little girl Tanya decided to play with dad's password to his secret database. Dad's password is a string consisting of n + 2 characters. She has written all the possible n three-letter continuous substrings of the password on pieces of paper, one for each piece of paper, and threw the password out. Each three-letter substring was written the number of times it occurred in the password. Thus, Tanya ended up with n pieces of paper.Then Tanya realized that dad will be upset to learn about her game and decided to restore the password or at least any string corresponding to the final set of three-letter strings. You have to help her in this difficult task. We know that dad's password consisted of lowercase and uppercase letters of the Latin alphabet and digits. Uppercase and lowercase letters of the Latin alphabet are considered distinct.

The first line contains integer n (1 ≤ n ≤ 2·105), the number of three-letter substrings Tanya got.  Next n lines contain three letters each, forming the substring of dad's password. Each character in the input is a lowercase or uppercase Latin letter or a digit.

If Tanya made a mistake somewhere during the game and the strings that correspond to the given set of substrings don't exist, print "NO".  If it is possible to restore the string that corresponds to given set of substrings, print "YES", and then print any suitable password option.

(* --- *)
let concat_chars cs = String.concat "" (List.map (String.make 1) cs)

let explode str =
  let exploded = ref [] in
  for i = String.length str - 1 downto 0 do
    exploded := str.[i] :: !exploded
  done ;
  !exploded

let split_on_char c str =
  let exploded = explode str in
  let cs', pending' =
    List.fold_right
      (fun x (ls, pending) ->
        match (x = c, pending) with
        | false, _ -> (ls, x :: pending)
        | true, [] -> (ls, pending)
        | true, _ -> (pending :: ls, []) )
      exploded ([], [])
  in
  List.map concat_chars (if pending' = [] then cs' else pending' :: cs')

(* --- *)
let update h k f =
  Hashtbl.replace h k
  @@ if Hashtbl.mem h k then f @@ Some (Hashtbl.find h k) else f None

(* --- *)
exception InputError of string

let read_into_pair () =
  let e = read_line () |> String.trim in
  match explode e with
  | [a; b; c] -> (concat_chars [a; b], concat_chars [b; c], c)
  | _ -> raise @@ InputError "unexpected input"

(* --- *)
let seqs_count = read_line () |> int_of_string

let degs = Hashtbl.create (62 * 62)

let adj = Hashtbl.create (62 * 62)

;;
for i = 1 to seqs_count do
  let f', t', char_of_path = read_into_pair () in
  update degs f' (fun r -> match r with None -> 1 | Some d -> d + 1) ;
  update degs t' (fun r -> match r with None -> -1 | Some d -> d - 1) ;
  Hashtbl.add adj f' (t', char_of_path)
done

let find_eu start_v =
  let cir = ref [] in
  let rec h vertex =
    while Hashtbl.mem adj vertex do
      let next_vertex, char_of_path = Hashtbl.find adj vertex in
      Hashtbl.remove adj vertex ; h next_vertex
    done ;
    cir := vertex :: !cir
  in
  h start_v ;
  (* ensure it's connected *)
  if List.length !cir = seqs_count + 1 then (
    Printf.printf "YES\n" ;
    Printf.printf "%s" start_v ;
    List.iter (fun s -> Printf.printf "%c" s.[1]) @@ List.tl !cir ;
    Printf.printf "\n" )
  else Printf.printf "NO\n"

let more_outgoings, more_ingoings, last_balanced =
  Hashtbl.fold
    (fun k d (more_outgoings, more_ingoings, last_balanced) ->
      if d < 0 then (more_outgoings, k :: more_ingoings, last_balanced)
      else if d > 0 then (k :: more_outgoings, more_ingoings, last_balanced)
      else (more_outgoings, more_ingoings, Some k) )
    degs ([], [], None)

;;
match (more_outgoings, more_ingoings, last_balanced) with
| [x], [y], _ when Hashtbl.find degs x = 1 && Hashtbl.find degs y = -1 ->
    find_eu x
| [], [], Some x -> find_eu x
| _ -> Printf.printf "NO\n"

(** a node is a string value and list
 * of outgoing edges *)
type node = {
  v : string;
  e : int list;
  i : int;
  o : int;
}
let empty_node v = { v; e = []; i = 0; o = 0 }

(** doubly-linked list element *)
type 'a el = {
  v : 'a;
  mutable next : 'a el option;
  mutable prev : 'a el option;
}

exception No_trail

let get_password edges nodes n =
  (* dlist of tour *)
  let dl = { v = n; next = None; prev = None } in
  (* end of list *)
  let tl = ref dl in

  (* get the initial trail *)
  let rec trail n tl =
    let node = Hashtbl.find nodes n in
    match node.e with
    | e :: es ->
        let e = String.sub edges.(e) 1 2 in
        let el = { v = e; next = None; prev = Some !tl } in
        !tl.next <- Some el;
        tl := el;
        Hashtbl.replace nodes n { node with e = es };
        trail e tl
    | [] -> ()
  in
  trail n tl;

  (* build the final password *)
  let rec build n =
    (* follow any further edges from this node
     * if necessary *)
    let next = n.next in
    let tl = ref n in
    trail n.v tl;
    (* check that we generated a cycle *)
    if !tl.v = n.v then
      !tl.next <- next
    else
      raise No_trail;

    match n.next with
    | None -> ()
    | Some n -> build n
  in
  build dl;
  dl

let rec print_password p =
  match p.next with
  | None -> ()
  | Some n ->
      print_char n.v.[1];
      print_password n

let () = Scanf.scanf "%d\n" (fun n ->
  (* read all 3-letter substrings (edges of the graph) *)
  let edges = Array.init n (fun _ -> Scanf.scanf "%s\n" (fun e -> e)) in
  (* adjacency list
   * - maps node to a list of
   *   indices into the edges array
   *)
  let nodes = Hashtbl.create n in
  Array.iteri (fun i e ->
    (* start and end nodes of the edge *)
    let hd = String.sub e 0 2
    and tl = String.sub e 1 2 in
    let hd_node =
      if Hashtbl.mem nodes hd
      then Hashtbl.find nodes hd
      else (empty_node hd)
    in
    let hd_node = { hd_node with
      e = (i :: hd_node.e);
      o = (hd_node.o + 1);
    } in
    Hashtbl.replace nodes hd hd_node;
    let tl_node =
      if Hashtbl.mem nodes tl
      then Hashtbl.find nodes tl
      else (empty_node tl)
    in
    Hashtbl.replace nodes tl { tl_node with i = (tl_node.i + 1) }
  ) edges;
  (* find nodes with odd degree *)
  let (i, o) = Hashtbl.fold (fun n v (i, o) ->
    match v.o - v.i with
    |  1 -> i, n :: o
    | -1 -> n :: i, o
    |  _ -> i, o
    ) nodes ([], [])
  in
  let start = match o with
  | [n] -> Some n
  | []  -> Some (String.sub edges.(0) 0 2)
  | _   -> None
  in
  match start with
  | None   -> print_endline "NO"
  | Some n ->
      try
        let p = get_password edges nodes n in
        let disjoint = Hashtbl.fold (fun _ v b ->
          b || List.length v.e > 0
        ) nodes false
        in
        if disjoint
        then print_endline "NO"
        else begin
          print_endline "YES";
          print_string (String.sub n 0 2);
          print_password p;
          print_char '\n'
        end
      with
      | No_trail -> print_endline "NO"
)

(* --- *)
let concat_chars cs = String.concat "" (List.map (String.make 1) cs)

let explode str =
  let exploded = ref [] in
  for i = String.length str - 1 downto 0 do
    exploded := str.[i] :: !exploded
  done ;
  !exploded

let split_on_char c str =
  let exploded = explode str in
  let cs', pending' =
    List.fold_right
      (fun x (ls, pending) ->
        match (x = c, pending) with
        | false, _ -> (ls, x :: pending)
        | true, [] -> (ls, pending)
        | true, _ -> (pending :: ls, []) )
      exploded ([], [])
  in
  List.map concat_chars (if pending' = [] then cs' else pending' :: cs')

(* --- *)
let update h k f =
  Hashtbl.replace h k
  @@ if Hashtbl.mem h k then f @@ Some (Hashtbl.find h k) else f None

(* --- *)
exception InputError of string

let read_into_pair () =
  let e = read_line () |> String.trim in
  match explode e with
  | [a; b; c] -> (concat_chars [a; b], concat_chars [b; c], c)
  | _ -> raise @@ InputError "unexpected input"

(* --- *)
let seqs_count = read_line () |> int_of_string

let degs = Hashtbl.create (62 * 62)

let adj = Hashtbl.create (62 * 62)

;;
for i = 1 to seqs_count do
  let f', t', char_of_path = read_into_pair () in
  update degs f' (fun r -> match r with None -> 1 | Some d -> d + 1) ;
  update degs t' (fun r -> match r with None -> -1 | Some d -> d - 1) ;
  Hashtbl.add adj f' (t', char_of_path)
done

let find_eu start_v =
  let cir = ref [] in
  let rec h vertex =
    while Hashtbl.mem adj vertex do
      let next_vertex, char_of_path = Hashtbl.find adj vertex in
      Hashtbl.remove adj vertex ; h next_vertex
    done ;
    cir := vertex :: !cir
  in
  h start_v ;
  if List.length !cir = seqs_count + 1 then (
    Printf.printf "YES\n" ;
    Printf.printf "%s" start_v ;
    List.iter (fun s -> Printf.printf "%c" s.[1]) @@ List.tl !cir ;
    Printf.printf "\n" )
  else Printf.printf "NO\n"

let more_outgoings, more_ingoings, last_balanced =
  Hashtbl.fold
    (fun k d (more_outgoings, more_ingoings, last_balanced) ->
      if d < 0 then (more_outgoings, k :: more_ingoings, last_balanced)
      else if d > 0 then (k :: more_outgoings, more_ingoings, last_balanced)
      else (more_outgoings, more_ingoings, Some k) )
    degs ([], [], None)

;;
match (more_outgoings, more_ingoings, last_balanced) with
| [x], [_], _ -> find_eu x
| [], [], Some x -> find_eu x
| _ -> Printf.printf "NO\n"

(* --- *)
let concat_chars cs = String.concat "" (List.map (String.make 1) cs)

let explode str =
  let exploded = ref [] in
  for i = String.length str - 1 downto 0 do
    exploded := str.[i] :: !exploded
  done ;
  !exploded

let split_on_char c str =
  let exploded = explode str in
  let cs', pending' =
    List.fold_right
      (fun x (ls, pending) ->
        match (x = c, pending) with
        | false, _ -> (ls, x :: pending)
        | true, [] -> (ls, pending)
        | true, _ -> (pending :: ls, []) )
      exploded ([], [])
  in
  List.map concat_chars (if pending' = [] then cs' else pending' :: cs')

(* --- *)
let update h k f =
  Hashtbl.replace h k
  @@ if Hashtbl.mem h k then f @@ Some (Hashtbl.find h k) else f None

(* --- *)
exception InputError of string

let read_into_pair () =
  let e = read_line () |> String.trim in
  match explode e with
  | [a; b; c] -> (concat_chars [a; b], concat_chars [b; c], c)
  | _ -> raise @@ InputError "unexpected input"

(* --- *)
let seqs_count = read_line () |> int_of_string

let degs = Hashtbl.create (62 * 62)

let adj = Hashtbl.create (62 * 62)

;;
for i = 1 to seqs_count do
  let f', t', char_of_path = read_into_pair () in
  update degs f' (fun r -> match r with None -> 1 | Some d -> d + 1) ;
  update degs t' (fun r -> match r with None -> -1 | Some d -> d - 1) ;
  Hashtbl.add adj f' (t', char_of_path)
done

let find_eu start_v =
  Printf.printf "YES\n" ;
  Printf.printf "%s" start_v ;
  let rec h vertex =
    while Hashtbl.mem adj vertex do
      let next_vertex, char_of_path = Hashtbl.find adj vertex in
      Hashtbl.remove adj vertex ;
      Printf.printf "%c" char_of_path ;
      h next_vertex
    done
  in
  h start_v ; Printf.printf "\n"

let more_outgoings, more_ingoings, last_balanced =
  Hashtbl.fold
    (fun k d (more_outgoings, more_ingoings, last_balanced) ->
      if d < 0 then (more_outgoings, k :: more_ingoings, last_balanced)
      else if d > 0 then (k :: more_outgoings, more_ingoings, last_balanced)
      else (more_outgoings, more_ingoings, Some k) )
    degs ([], [], None)

;;
match (more_outgoings, more_ingoings, last_balanced) with
| [x], [_], _ -> find_eu x
| [], [], Some x -> find_eu x
| _ -> Printf.printf "NO\n"

(* --- *)
let concat_chars cs = String.concat "" (List.map (String.make 1) cs)

let explode str =
  let exploded = ref [] in
  for i = String.length str - 1 downto 0 do
    exploded := str.[i] :: !exploded
  done ;
  !exploded

let split_on_char c str =
  let exploded = explode str in
  let cs', pending' =
    List.fold_right
      (fun x (ls, pending) ->
         match (x = c, pending) with
         | false, _ -> (ls, x :: pending)
         | true, [] -> (ls, pending)
         | true, _ -> (pending :: ls, []) )
      exploded ([], [])
  in
  List.map concat_chars (if pending' = [] then cs' else pending' :: cs')

(* --- *)
let update h k f =
  Hashtbl.replace h k
  @@ if Hashtbl.mem h k then f @@ Some (Hashtbl.find h k) else f None

(* --- *)
exception InputError of string

let read_into_pair () =
  let e = read_line () |> String.trim in
  match explode e with
  | [a; b; c] -> (concat_chars [a; b], concat_chars [b; c], c)
  | _ -> raise @@ InputError "unexpected input"

(* --- *)
let seqs_count = read_line () |> int_of_string

let degs = Hashtbl.create (62 * 62)

let adj = Hashtbl.create (62 * 62)

;;
for i = 1 to seqs_count do
  let f', t', char_of_path = read_into_pair () in
  update degs f' (fun r -> match r with None -> 1 | Some d -> d + 1) ;
  update degs t' (fun r -> match r with None -> -1 | Some d -> d - 1) ;
  Hashtbl.add adj f' (t', char_of_path)
done

let find_eu start_v =
  Printf.printf "YES\n" ;
  Printf.printf "%s" start_v;
  let cir = ref [] in
  let rec h vertex =
    while Hashtbl.mem adj vertex do
      let next_vertex, char_of_path = Hashtbl.find adj vertex in
      Hashtbl.remove adj vertex ; h next_vertex
    done ;
    cir := vertex :: !cir
  in
  h start_v ;
  List.iter (fun s -> Printf.printf "%c" s.[1]) @@ List.tl !cir ;
  Printf.printf "\n"

let more_outgoings, more_ingoings, last_balanced =
  Hashtbl.fold
    (fun k d (more_outgoings, more_ingoings, last_balanced) ->
       if d < 0 then (more_outgoings, k :: more_ingoings, last_balanced)
       else if d > 0 then (k :: more_outgoings, more_ingoings, last_balanced)
       else (more_outgoings, more_ingoings, Some k) )
    degs ([], [], None)

;;
match (more_outgoings, more_ingoings, last_balanced) with
| [x], [_], _ -> find_eu x
| [], [], Some x -> find_eu x
| _ -> Printf.printf "NO\n"

(* --- *)
let concat_chars cs = String.concat "" (List.map (String.make 1) cs)

let explode str =
  let exploded = ref [] in
  for i = String.length str - 1 downto 0 do
    exploded := str.[i] :: !exploded
  done ;
  !exploded

let split_on_char c str =
  let exploded = explode str in
  let cs', pending' =
    List.fold_right
      (fun x (ls, pending) ->
        match (x = c, pending) with
        | false, _ -> (ls, x :: pending)
        | true, [] -> (ls, pending)
        | true, _ -> (pending :: ls, []) )
      exploded ([], [])
  in
  List.map concat_chars (if pending' = [] then cs' else pending' :: cs')

(* --- *)
let update h k f =
  Hashtbl.replace h k
  @@ if Hashtbl.mem h k then f @@ Some (Hashtbl.find h k) else f None

(* --- *)
exception InputError of string

let read_into_pair () =
  let e = read_line () |> String.trim in
  match explode e with
  | [a; b; c] -> (concat_chars [a; b], concat_chars [b; c], c)
  | _ -> raise @@ InputError "unexpected input"

(* --- *)
let seqs_count = read_line () |> int_of_string

let degs = Hashtbl.create (62 * 62)

let adj = Hashtbl.create (62 * 62)

;;
for i = 1 to seqs_count do
  let f', t', char_of_path = read_into_pair () in
  update degs f' (fun r -> match r with None -> 1 | Some d -> d + 1) ;
  update degs t' (fun r -> match r with None -> -1 | Some d -> d - 1) ;
  Hashtbl.add adj f' (t', char_of_path)
done

let find_eu start_v =
  Printf.printf "YES\n" ;
  Printf.printf "%s" start_v ;
  let acc = ref [] in
  let rec h vertex =
    while Hashtbl.mem adj vertex do
      let next_vertex, char_of_path = Hashtbl.find adj vertex in
      Hashtbl.remove adj vertex ;
      acc := char_of_path :: !acc ;
      h next_vertex
    done
  in
  h start_v ;
  List.iter (fun c -> Printf.printf "%c" c) !acc ;
  Printf.printf "\n"

let more_outgoings, more_ingoings, last_balanced =
  Hashtbl.fold
    (fun k d (more_outgoings, more_ingoings, last_balanced) ->
      if d < 0 then (more_outgoings, k :: more_ingoings, last_balanced)
      else if d > 0 then (k :: more_outgoings, more_ingoings, last_balanced)
      else (more_outgoings, more_ingoings, Some k) )
    degs ([], [], None)

;;
match (more_outgoings, more_ingoings, last_balanced) with
| [x], [_], _ -> find_eu x
| [], [], Some x -> find_eu x
| _ -> Printf.printf "NO\n"

(** a node is a string value and list
 * of outgoing edges *)
type node = {
  v : string;
  e : int list;
  i : int;
  o : int;
}
let empty_node v = { v; e = []; i = 0; o = 0 }

(** doubly-linked list element *)
type 'a el = {
  v : 'a;
  mutable next : 'a el option;
  mutable prev : 'a el option;
}

let get_password edges nodes n =
  (* dlist of tour *)
  let dl = { v = n; next = None; prev = None } in
  (* end of list *)
  let tl = ref dl in

  (* get the initial trail *)
  let rec trail n tl =
    let node = Hashtbl.find nodes n in
    match node.e with
    | e :: es ->
        let e = String.sub edges.(e) 1 2 in
        let el = { v = e; next = None; prev = Some !tl } in
        !tl.next <- Some el;
        tl := el;
        Hashtbl.replace nodes n { node with e = es };
        trail e tl
    | [] -> ()
  in
  trail n tl;

  (* print the final password *)
  let rec print n =
    print_char n.v.[1];

    (* follow any further edges from this node
     * if necessary *)
    let next = n.next in
    let tl = ref n in
    trail n.v tl;
    !tl.next <- next;

    match n.next with
    | None -> ()
    | Some n -> print n
  in
  print dl;
  print_char '\n'

let () = Scanf.scanf "%d\n" (fun n ->
  (* read all 3-letter substrings (edges of the graph) *)
  let edges = Array.init n (fun _ -> Scanf.scanf "%s\n" (fun e -> e)) in
  (* adjacency list
   * - maps node to a list of
   *   indices into the edges array
   *)
  let nodes = Hashtbl.create n in
  Array.iteri (fun i e ->
    (* start and end nodes of the edge *)
    let hd = String.sub e 0 2
    and tl = String.sub e 1 2 in
    let hd_node =
      if Hashtbl.mem nodes hd
      then Hashtbl.find nodes hd
      else (empty_node hd)
    in
    let hd_node = { hd_node with
      e = (i :: hd_node.e);
      o = (hd_node.o + 1);
    } in
    Hashtbl.replace nodes hd hd_node;
    let tl_node =
      if Hashtbl.mem nodes tl
      then Hashtbl.find nodes tl
      else (empty_node tl)
    in
    Hashtbl.replace nodes tl { tl_node with i = (tl_node.i + 1) }
  ) edges;
  (* find nodes with odd degree *)
  let (i, o) = Hashtbl.fold (fun n v (i, o) ->
    match v.o - v.i with
    |  1 -> i, n :: o
    | -1 -> n :: i, o
    |  _ -> i, o
    ) nodes ([], [])
  in
  let start = match o with
  | [n] -> Some n
  | []  -> Some (String.sub edges.(0) 0 2)
  | _   -> None
  in
  match start with
  | None   -> print_endline "NO"
  | Some n ->
      print_endline "YES";
      print_char n.[0];
      get_password edges nodes n
)

let get_password edges nodes s =
  print_string s;
  let rec printer s =
    match Hashtbl.find nodes s with
    | hd :: tl ->
        let e = edges.(hd) in
        print_char e.[2];
        Hashtbl.replace nodes s tl;
        printer (String.sub e 1 2)
    | [] -> () (* done *)
  in
  printer s;
  print_endline ""

let () =
  Scanf.scanf "%d\n" (fun n ->
    (* array of edges *)
    let edges = Array.init n (fun _ -> Scanf.scanf "%s\n" (fun l -> l)) in
    (* adjacency list *)
    let nodes = Hashtbl.create n in
    (* degree of each node *)
    let degree = Hashtbl.create n in
    (* add edges to adjacency list and
     * calculate the degree of nodes *)
    Array.iteri (fun i s ->
      (* start of edge *)
      let hd = String.sub s 0 2
      (* end of edge *)
      and tl = String.sub s 1 2 in
      (* add edge to adjacency list *)
      let edges =
        if Hashtbl.mem nodes hd
        then Hashtbl.find nodes hd
        else []
      in
      Hashtbl.replace nodes hd (i :: edges);
      if not (Hashtbl.mem nodes tl)
      then Hashtbl.add nodes tl [];
      (* increase out degree of start node *)
      let (i, o) =
        if Hashtbl.mem degree hd
        then Hashtbl.find degree hd
        else (0, 0)
      in
      Hashtbl.replace degree hd (i, o + 1);
      (* increase in degree of end node *)
      let (i, o) =
        if Hashtbl.mem degree tl
        then Hashtbl.find degree tl
        else (0, 0)
      in
      Hashtbl.replace degree tl (i + 1, o)
    ) edges;
    (* a directed graph has an Eulerian trail iff at
     * most one node each has o-i = 1 and i-o = 1.
     * fold over the hashtbl to find these nodes *)
    let (inl, outl) =
      Hashtbl.fold (fun s (i, o) (inl, outl) ->
        match o - i with
        |  1 -> (inl, s :: outl)
        | -1 -> (s :: inl, outl)
        |  _ -> (inl, outl)
      ) degree ([], [])
    in
    let start = match outl with
    | [s] -> Some s
    | []  -> Some (String.sub edges.(0) 0 2)
    | _   -> None
    in
    match start with
    | Some s -> print_endline "YES"; get_password edges nodes s
    | None   -> print_endline "NO"
  )

(** a node is a string value and list
 * of outgoing edges *)
type node = {
  v : string;
  e : int list;
  i : int;
  o : int;
}
let empty_node v = { v; e = []; i = 0; o = 0 }

(** doubly-linked list element *)
type 'a el = {
  v : 'a;
  mutable next : 'a el option;
  mutable prev : 'a el option;
}

let get_password edges nodes n =
  (* dlist of tour *)
  let dl = { v = n; next = None; prev = None } in
  (* end of list *)
  let tl = ref dl in

  (* get the initial trail *)
  let rec trail n tl =
    let node = Hashtbl.find nodes n in
    match node.e with
    | e :: es ->
        let e = String.sub edges.(e) 1 2 in
        let el = { v = e; next = None; prev = Some !tl } in
        !tl.next <- Some el;
        tl := el;
        Hashtbl.replace nodes n { node with e = es };
        trail e tl
    | [] -> ()
  in
  trail n tl;

  (* build the final password *)
  let rec build n =
    (* follow any further edges from this node
     * if necessary *)
    let next = n.next in
    let tl = ref n in
    trail n.v tl;
    !tl.next <- next;

    match n.next with
    | None -> ()
    | Some n -> build n
  in
  build dl;
  dl

let rec print_password p =
  match p.next with
  | None -> ()
  | Some n ->
      print_char n.v.[1];
      print_password n

let () = Scanf.scanf "%d\n" (fun n ->
  (* read all 3-letter substrings (edges of the graph) *)
  let edges = Array.init n (fun _ -> Scanf.scanf "%s\n" (fun e -> e)) in
  (* adjacency list
   * - maps node to a list of
   *   indices into the edges array
   *)
  let nodes = Hashtbl.create n in
  Array.iteri (fun i e ->
    (* start and end nodes of the edge *)
    let hd = String.sub e 0 2
    and tl = String.sub e 1 2 in
    let hd_node =
      if Hashtbl.mem nodes hd
      then Hashtbl.find nodes hd
      else (empty_node hd)
    in
    let hd_node = { hd_node with
      e = (i :: hd_node.e);
      o = (hd_node.o + 1);
    } in
    Hashtbl.replace nodes hd hd_node;
    let tl_node =
      if Hashtbl.mem nodes tl
      then Hashtbl.find nodes tl
      else (empty_node tl)
    in
    Hashtbl.replace nodes tl { tl_node with i = (tl_node.i + 1) }
  ) edges;
  (* find nodes with odd degree *)
  let (i, o) = Hashtbl.fold (fun n v (i, o) ->
    match v.o - v.i with
    |  1 -> i, n :: o
    | -1 -> n :: i, o
    |  _ -> i, o
    ) nodes ([], [])
  in
  let start = match o with
  | [n] -> Some n
  | []  -> Some (String.sub edges.(0) 0 2)
  | _   -> None
  in
  match start with
  | None   -> print_endline "NO"
  | Some n ->
      let p = get_password edges nodes n in
      let disjoint = Hashtbl.fold (fun _ v b ->
        b || List.length v.e > 0
      ) nodes false
      in
      if disjoint
      then print_endline "NO"
      else begin
        print_endline "YES";
        print_string (String.sub n 0 2);
        print_password p;
        print_char '\n'
      end
)


You're given two arrays $$$a[1 \dots n]$$$ and $$$b[1 \dots n]$$$, both of the same length $$$n$$$.In order to perform a push operation, you have to choose three integers $$$l, r, k$$$ satisfying $$$1 \le l \le r \le n$$$ and $$$k > 0$$$. Then, you will add $$$k$$$ to elements $$$a_l, a_{l+1}, \ldots, a_r$$$.For example, if $$$a = [3, 7, 1, 4, 1, 2]$$$ and you choose $$$(l = 3, r = 5, k = 2)$$$, the array $$$a$$$ will become $$$[3, 7, \underline{3, 6, 3}, 2]$$$.You can do this operation at most once. Can you make array $$$a$$$ equal to array $$$b$$$?(We consider that $$$a = b$$$ if and only if, for every $$$1 \le i \le n$$$, $$$a_i = b_i$$$)

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 20$$$) — the number of test cases in the input. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100\ 000$$$) — the number of elements in each array. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$). The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$). It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$10^5$$$.

For each test case, output one line containing "YES" if it's possible to make arrays $$$a$$$ and $$$b$$$ equal by performing at most once the described operation or "NO" if it's impossible. You can print each letter in any case (upper or lower).

NoteThe first test case is described in the statement: we can perform a push operation with parameters $$$(l=3, r=5, k=2)$$$ to make $$$a$$$ equal to $$$b$$$.In the second test case, we would need at least two operations to make $$$a$$$ equal to $$$b$$$.In the third test case, arrays $$$a$$$ and $$$b$$$ are already equal.In the fourth test case, it's impossible to make $$$a$$$ equal to $$$b$$$, because the integer $$$k$$$ has to be positive.

let rec check l l' r b =
  match l,l',r with
  | [],[],_ -> true
  | x::l,y::l',None ->
    if x = y then check l l' None b
    else
    if b then false
    else if x < y then
      check  l l' (Some (y -x)) true
    else
      false
  | x::l,y::l', Some r ->
    if x = y then check l l' None true
    else if r = y - x then
      check l l' (Some r) true
    else false
  | _ -> assert false

let _ =
  let n = int_of_string (input_line stdin) in
  for i = 1 to n do
    let _ = int_of_string (input_line stdin) in
    let l = List.map int_of_string @@ Str.split (Str.regexp " ") (input_line stdin) in
    let r = List.map int_of_string @@ Str.split (Str.regexp " ") (input_line stdin) in
    if check l r None false then
      Format.printf "YES@."
    else
      Format.printf "NO@."
  done


Roy and Biv have a set of n points on the infinite number line.Each point has one of 3 colors: red, green, or blue.Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it connects.They want to do this in such a way that they will both see that all the points are connected (either directly or indirectly).However, there is a catch: Roy cannot see the color red and Biv cannot see the color blue.Therefore, they have to choose the edges in such a way that if all the red points are removed, the remaining blue and green points are connected (and similarly, if all the blue points are removed, the remaining red and green points are connected).Help them compute the minimum cost way to choose edges to satisfy the above constraints.

The first line will contain an integer n (1 ≤ n ≤ 300 000), the number of points. The next n lines will contain two tokens pi and ci (pi is an integer, 1 ≤ pi ≤ 109, ci is a uppercase English letter 'R', 'G' or 'B'), denoting the position of the i-th point and the color of the i-th point. 'R' means red, 'G' denotes green, and 'B' means blue. The positions will be in strictly increasing order.

Print a single integer, the minimum cost way to solve the problem.

NoteIn the first sample, it is optimal to draw edges between the points (1,2), (1,4), (3,4). These have costs 4, 14, 5, respectively.

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

let 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

open Printf
open Scanf

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

let () =
  let n = read_int () in
  let where = Array.make n 0L in
  let green = Array.make (n+1) (-1) in
  let ngreen = ref 1 in
  let bluelist = Array.make (n+1) [] in
  let redlist = Array.make (n+1) [] in

  for i=0 to n-1 do
    where.(i) <- long (read_int());
    match (read_string()).[0] with
      | 'G' ->
	green.(!ngreen) <- i;
	ngreen := 1 + !ngreen
      | 'B' ->
	bluelist.(!ngreen-1) <- i::bluelist.(!ngreen-1)
      | 'R' ->
	redlist.(!ngreen-1) <- i::redlist.(!ngreen-1)
      | _ -> failwith "bad color"
  done;

  let ngreen = !ngreen in (* counts the extra fake green point at the start *)

  for j=0 to ngreen-1 do
    bluelist.(j) <- List.rev bluelist.(j);
    redlist.(j) <- List.rev redlist.(j);
  done;

  (* functions for non-empty list li *)
  let first li =  where.(List.hd li) in
  let last li = let n = List.length li in where.(List.nth li (n-1)) in

  let maxgap g0 g1 li =
    (* g0 and g1 are green coordinates that surround the list (of indices).
       This returns the maximum gap in the sequence [g0,li,g1] *)
    if li = [] then g1 -- g0 else
      let rec findbig li ac =
	match li with
	  | [] -> failwith "bad list"
	  | _::[] -> ac
	  | i::((j::_) as tail) ->
	    let ac = max ac (where.(j) -- where.(i)) in
	    findbig tail ac
      in
      max (findbig li 0L) (max ((first li) -- g0) (g1 -- (last li)))
  in

  let answer =
    if ngreen = 1 then  (* no green points *)
      let cost li = if li = [] then 0L else (last li) -- (first li) in
      (cost bluelist.(0)) ++ (cost redlist.(0))
    else (
    (* end cases *)
      let stcost li = if li = [] then 0L else where.(green.(1)) -- (first li) in
      let startcost = (stcost bluelist.(0)) ++ (stcost redlist.(0)) in

      let encost li = if li = [] then 0L else (last li) -- where.(green.(ngreen-1)) in
      let endcost = (encost bluelist.(ngreen-1)) ++ (encost redlist.(ngreen-1)) in

    (* now do the middle cases, surrounded by two green points *)

      startcost ++ endcost ++
	sum 1 (ngreen-2) (fun j -> (*the two neighboring green points are j and j+1*)
	  let (g0,g1) = (where.(green.(j)),where.(green.(j+1))) in
	  let option1 =
	    3L**(g1--g0) -- (maxgap g0 g1 bluelist.(j)) -- (maxgap g0 g1 redlist.(j))
	  in
	  let option2 = 2L**(g1--g0) in
	  min option1 option2
	)
    )
  in

  printf "%Ld\n" answer


Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes.Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th variant is given by a period of time (l2, i, r2, i).Anton needs to choose exactly one of n possible periods of time when he will attend chess classes and exactly one of m possible periods of time when he will attend programming classes. He wants to have a rest between classes, so from all the possible pairs of the periods he wants to choose the one where the distance between the periods is maximal.The distance between periods (l1, r1) and (l2, r2) is the minimal possible distance between a point in the first period and a point in the second period, that is the minimal possible |i - j|, where l1 ≤ i ≤ r1 and l2 ≤ j ≤ r2. In particular, when the periods intersect, the distance between them is 0.Anton wants to know how much time his rest between the classes will last in the best case. Help Anton and find this number!

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of time periods when Anton can attend chess classes. Each of the following n lines of the input contains two integers l1, i and r1, i (1 ≤ l1, i ≤ r1, i ≤ 109) — the i-th variant of a period of time when Anton can attend chess classes. The following line of the input contains a single integer m (1 ≤ m ≤ 200 000) — the number of time periods when Anton can attend programming classes. Each of the following m lines of the input contains two integers l2, i and r2, i (1 ≤ l2, i ≤ r2, i ≤ 109) — the i-th variant of a period of time when Anton can attend programming classes.

Output one integer — the maximal possible distance between time periods.

NoteIn the first sample Anton can attend chess classes in the period (2, 3) and attend programming classes in the period (6, 8). It's not hard to see that in this case the distance between the periods will be equal to 3.In the second sample if he chooses any pair of periods, they will intersect. So the answer is 0.

open Printf
open Scanf

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

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

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

let read_int _ = bscanf Scanning.stdib " %d " (fun x -> x)
let read_pair _ = bscanf Scanning.stdib " %Ld %Ld " (fun x y -> (x,y))

let () =
  let n = read_int () in
  let a1 = Array.init n read_pair in
  let m = read_int () in
  let a2 = Array.init m read_pair in

  let min_right1 = minf 0 (n-1) (fun i -> snd a1.(i)) in
  let max_left2 = maxf 0 (m-1) (fun i -> fst a2.(i)) in
  let opt1 = max 0L (max_left2 -- min_right1) in

  let min_right2 = minf 0 (m-1) (fun i -> snd a2.(i)) in
  let max_left1 = maxf 0 (n-1) (fun i -> fst a1.(i)) in
  let opt2 = max 0L (max_left1 -- min_right2) in

  printf "%Ld\n" (max opt1 opt2)


Mike is a bartender at Rico's bar. At Rico's, they put beer glasses in a special shelf. There are n kinds of beer at Rico's numbered from 1 to n. i-th kind of beer has ai milliliters of foam on it.  Maxim is Mike's boss. Today he told Mike to perform q queries. Initially the shelf is empty. In each request, Maxim gives him a number x. If beer number x is already in the shelf, then Mike should remove it from the shelf, otherwise he should put it in the shelf.After each query, Mike should tell him the score of the shelf. Bears are geeks. So they think that the score of a shelf is the number of pairs (i, j) of glasses in the shelf such that i < j and  where  is the greatest common divisor of numbers a and b.Mike is tired. So he asked you to help him in performing these requests.

The first line of input contains numbers n and q (1 ≤ n, q ≤ 2 × 105), the number of different kinds of beer and number of queries. The next line contains n space separated integers, a1, a2, ... , an (1 ≤ ai ≤ 5 × 105), the height of foam in top of each kind of beer. The next q lines contain the queries. Each query consists of a single integer integer x (1 ≤ x ≤ n), the index of a beer that should be added or removed from the shelf.

For each query, print the answer for that query in one line.

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

let fmax = 500_001

let factors n =
  let rec aux i p =
(*    Printf.printf "%d, %d\n" i p; *)
    if p = 1 then []
    else if i*i > p then [p]
    else if p mod i = 0 then i::(match aux i (p/i) with i'::is when i=i' -> is | is -> is)
    else aux (i+1) p
  in
  aux 2 n

(* Mike and Foam *)

let _ =
  let n = read_int () in
  let q = read_int () in
  let beers = Array.init n (fun _ -> read_int ()) in
  let queries = Array.init q (fun _ -> read_int ()) in
  let slots = Array.make fmax 0 in
  let pres = Array.make n false in
  let register sc n =
    let rec it prod = function
      | [] -> ()
      | l::ls -> count (prod*l) ls; it prod ls
    and count prod l =
      slots.(prod) <- slots.(prod)+sc;
      it prod l
    in
    count 1 (factors n)
  in
  let count n =
    let rec count prod l =
      slots.(prod) - it prod l
    and it prod = function
      | [] -> 0
      | l::ls -> count (prod * l) ls + it prod ls
    in
    count 1 (factors n)
  in
  let cur = ref (Int64.zero) in
  for i = 0 to q - 1 do
    (* How many things does it intersect with ? *)
    (* Oops, check presence + the '1' problem *)
    let beer = queries.(i) - 1 in
    let foam = beers.(beer) in
    let score =
      if pres.(beer) then (register (-1) foam; - count foam)
      else (let r = count foam in register 1 foam; r)
    in
    pres.(beer) <- not pres.(beer);
    cur := Int64.add !cur (Int64.of_int score);
    Printf.printf "%Ld\n" !cur
  done

let _ =
  let sb = Scanf.Scanning.stdib in
  let n2 = 500000 in
  let prime = Array.make (n2 + 1) true in
  let p = Array.make (n2 + 1) 0 in
  let pd = Array.make (n2 + 1) [] in
  let pk = ref 0 in
  let () =
    for i = 2 to n2 do
      if prime.(i) then (
	p.(!pk) <- i;
	incr pk;
	pd.(i) <- [i];
	let j = ref (2 * i) in
          while !j <= n2 do
	    let jj = !j in
              prime.(jj) <- false;
	      pd.(jj) <- i :: pd.(jj);
              j := jj + i
          done
      )
    done;
  in
  let pk = !pk - 1 in
  let pd = Array.map Array.of_list pd in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let q = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let b = Array.make (n2 + 1) false in
  let d = Array.make (n2 + 1) 0 in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
  in
  let res = ref 0L in
    for i = 1 to q do
      let x = Scanf.bscanf sb "%d " (fun s -> s) in
      let (s, ofs) =
	if b.(x) then (
	  b.(x) <- false;
	  (-1, 1)
	) else (
	  b.(x) <- true;
	  (1, 0)
	)
      in
      let x = a.(x - 1) in
      let ds = pd.(x) in
      let k = Array.length ds in
	for i = 0 to 1 lsl k - 1 do
	  let y = ref 1 in
	  let c = ref 0 in
	    for j = 0 to k - 1 do
	      if i land (1 lsl j) <> 0 then (
		y := !y * ds.(j);
		incr c
	      )
	    done;
	    if !c land 1 = 0
	    then res := Int64.add !res (Int64.of_int (s * (d.(!y) - ofs)))
	    else res := Int64.sub !res (Int64.of_int (s * (d.(!y) - ofs)));
	    d.(!y) <- d.(!y) + s;
	done;
	Printf.printf "%Ld\n" !res;
    done;

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

let fmax = 500_001

let factors n =
  let rec aux i p =
(*    Printf.printf "%d, %d\n" i p; *)
    if p = 1 then []
    else if i*i > p then [p]
    else if p mod i = 0 then i::(match aux i (p/i) with i'::is when i=i' -> is | is -> is)
    else aux (i+1) p
  in
  aux 2 n

(* Mike and Foam *)

let _ =
  let n = read_int () in
  let q = read_int () in
  let beers = Array.init n (fun _ -> read_int ()) in
  let queries = Array.init q (fun _ -> read_int ()) in
  let slots = Array.make fmax 0 in
  let pres = Array.make n false in
  let register sc n =
    let rec it prod = function
      | [] -> ()
      | l::ls -> count (prod*l) ls; it prod ls
    and count prod l =
      slots.(prod) <- slots.(prod)+sc;
      it prod l
    in
    count 1 (factors n)
  in
  let count n =
    let rec count prod l =
      slots.(prod) - it prod l
    and it prod = function
      | [] -> 0
      | l::ls -> count (prod * l) ls + it prod ls
    in
    count 1 (factors n)
  in
  let cur = ref 0 in
  for i = 0 to q - 1 do
    (* How many things does it intersect with ? *)
    (* Oops, check presence + the '1' problem *)
    let beer = queries.(i) - 1 in
    let foam = beers.(beer) in
    let score =
      if pres.(beer) then (register (-1) foam; - count foam)
      else (let r = count foam in register 1 foam; r)
    in
    pres.(beer) <- not pres.(beer);
    cur := !cur + score;
    Printf.printf "%d\n" !cur
  done

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

let fmax = 500_001

let factors n =
  let rec aux i p =
(*    Printf.printf "%d, %d\n" i p; *)
    if p = 1 then []
    else if i*i > p then [p]
    else if p mod i = 0 then i::(match aux i (p/i) with i'::is when i=i' -> is | is -> is)
    else aux (i+1) p
  in
  aux 2 n

(* Mike and Foam *)

let _ =
  let n = read_int () in
  let q = read_int () in
  let beers = Array.init n (fun _ -> read_int ()) in
  let queries = Array.init q (fun _ -> read_int ()) in
  let slots = Array.make fmax 0 in
  let pres = Array.make n false in
  let register sc n =
    let rec it par prod = function
      | [] -> 0
      | l::ls -> count par (prod*l) ls + it par prod ls
    and count par prod l =
      let t = slots.(prod) in
      slots.(prod) <- t+sc;
      par*(if sc > 0 then t else t + sc) + it (-par) prod l
    in
    sc * count 1 1 (factors n)
  in
  let cur = ref 0 in
  for i = 0 to q - 1 do
    (* How many things does it intersect with ? *)
    (* Oops, check presence + the '1' problem *)
    let beer = queries.(i) - 1 in
    let score = register (if pres.(beer) then -1 else 1) beers.(beer) in
    pres.(beer) <- true;
    cur := !cur + score;
    Printf.printf "%d\n" !cur
  done

let _ =
  let sb = Scanf.Scanning.stdib in
  let n2 = 500000 in
  let prime = Array.make (n2 + 1) true in
  let p = Array.make (n2 + 1) 0 in
  let pd = Array.make (n2 + 1) [] in
  let pk = ref 0 in
  let () =
    for i = 2 to n2 do
      if prime.(i) then (
	p.(!pk) <- i;
	incr pk;
	pd.(i) <- [i];
	let j = ref (2 * i) in
          while !j <= n2 do
	    let jj = !j in
              prime.(jj) <- false;
	      pd.(jj) <- i :: pd.(jj);
              j := jj + i
          done
      )
    done;
  in
  let pk = !pk - 1 in
  let pd = Array.map Array.of_list pd in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let q = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let b = Array.make (n2 + 1) false in
  let d = Array.make (n2 + 1) 0 in
  let _ =
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
  in
  let res = ref 0L in
    for i = 1 to q do
      let x = Scanf.bscanf sb "%d " (fun s -> s) in
      let x = a.(x - 1) in
      let (s, ofs) =
	if b.(x) then (
	  b.(x) <- false;
	  (-1, 1)
	) else (
	  b.(x) <- true;
	  (1, 0)
	)
      in
      let ds = pd.(x) in
      let k = Array.length ds in
	for i = 0 to 1 lsl k - 1 do
	  let y = ref 1 in
	  let c = ref 0 in
	    for j = 0 to k - 1 do
	      if i land (1 lsl j) <> 0 then (
		y := !y * ds.(j);
		incr c
	      )
	    done;
	    if !c land 1 = 0
	    then res := Int64.add !res (Int64.of_int (s * (d.(!y) - ofs)))
	    else res := Int64.sub !res (Int64.of_int (s * (d.(!y) - ofs)));
	    d.(!y) <- d.(!y) + s;
	done;
	Printf.printf "%Ld\n" !res;
    done;


Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti.For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the biggest number of times in the interval. In case of a tie between some colors, the one with the smallest number (index) is chosen as dominant.There are  non-empty intervals in total. For each color, your task is to count the number of intervals in which this color is dominant.

The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — the number of balls. The second line contains n integers t1, t2, ..., tn (1 ≤ ti ≤ n) where ti is the color of the i-th ball.

Print n integers. The i-th of them should be equal to the number of intervals where i is a dominant color.

NoteIn the first sample, color 2 is dominant in three intervals:  An interval [2, 2] contains one ball. This ball's color is 2 so it's clearly a dominant color.  An interval [4, 4] contains one ball, with color 2 again.  An interval [2, 4] contains two balls of color 2 and one ball of color 1. There are 7 more intervals and color 1 is dominant in all of them.

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

let () =
  let n = read_int() in
  let a = Array.init n read_int in
  let res = Array.make n 0 in
  for i = 0 to (n-1) do
    let seen = Array.make n 0 in
    let index = ref (a.(i)-1) in
    seen.(!index) <- 1;
    res.(!index) <- res.(!index) + 1;
    for j = i+1 to (n-1) do
      let k = a.(j)-1 in
      seen.(k) <- seen.(k) + 1;
      if seen.(k) > seen.(!index) ||
         (seen.(k) == seen.(!index) && k < !index) then
        (index := k);
      res.(!index) <- res.(!index) + 1
    done
  done;
  Array.iter print_int res;;

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let t = Array.init n (fun _ -> -1 + read_int()) in
  let wins = Array.make n 0 in

  for i=0 to n-1 do
    let counts = Array.make n 0 in
    let rec loop j maxcount maxcolor = if j < n then (
      let c = t.(j) in
      let nv = counts.(c) + 1 in
      counts.(c) <- nv;
      if nv > maxcount then (
	wins.(c) <- wins.(c) + 1;
	loop (j+1) nv c
      ) else if nv = maxcount then (
	if c < maxcolor then (
	  wins.(c) <- wins.(c) + 1;
	  loop (j+1) nv c
	) else (
	  wins.(maxcolor) <- wins.(maxcolor) + 1;
	  loop (j+1) nv maxcolor
	)
      ) else (
	wins.(maxcolor) <- wins.(maxcolor) + 1;
	loop (j+1) maxcount maxcolor
      )
    )
    in
    loop i 0 0
  done;

  for i=0 to n-1 do
    printf "%d " wins.(i)
  done;

  print_newline()

open Printf
open Scanf

let read_int () = bscanf Scanning.stdib " %d " (fun x -> x)
let () =
  let n = read_int () in
  let t = Array.init n (fun _ -> -1 + read_int()) in
  let wins = Array.make n 0 in

  for i=0 to n-1 do
    let counts = Array.make n 0 in
    let rec loop j maxcount maxcolor = if j = n then () else (
      let c = t.(j) in
      let nv = counts.(c) + 1 in
      counts.(c) <- nv;
      if nv > maxcount then (
	wins.(c) <- wins.(c) + 1;
	loop (j+1) nv c
      ) else if nv = maxcount then (
	if c < maxcolor then (
	  wins.(c) <- wins.(c) + 1;
	  loop (j+1) nv c
	) else (
	  wins.(maxcolor) <- wins.(maxcolor) + 1;
	  loop (j+1) nv maxcolor
	)
      ) else loop (j+1) maxcount maxcolor
    )
    in
    loop i 0 0
  done;

  for i=0 to n-1 do
    printf "%d " wins.(i)
  done;

  print_newline()


The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a player gains or loses a particular number of points. In the course of the game the number of points is registered in the line "name score", where name is a player's name, and score is the number of points gained in this round, which is an integer number. If score is negative, this means that the player has lost in the round. So, if two or more players have the maximum number of points (say, it equals to m) at the end of the game, than wins the one of them who scored at least m points first. Initially each player has 0 points. It's guaranteed that at the end of the game at least one player has a positive number of points.

The first line contains an integer number n (1  ≤  n  ≤  1000), n is the number of rounds played. Then follow n lines, containing the information about the rounds in "name score" format in chronological order, where name is a string of lower-case Latin letters with the length from 1 to 32, and score is an integer number between -1000 and 1000, inclusive.

let rec read_rounds n score_tbl =
  if n > 0 then
	let line = read_line () in
	let (name, score) = Scanf.sscanf line "%s %d" (fun x y -> (x, y)) in
	(* Printf.printf "line: %s\n" line; *)
	let so_far = (try Hashtbl.find score_tbl name with _ -> 0) + score in
	Hashtbl.replace score_tbl name so_far;
	(* Printf.printf "%s %d\n" name score; *)
	(name, so_far) :: read_rounds (n - 1) score_tbl
  else
	[]

let rec winner rounds max_final_score score_tbl =
  match rounds with
  | [] -> None
  | (name, score) :: tl -> if (score >= max_final_score) && ((Hashtbl.find score_tbl name) = max_final_score) then
							 Some name
						   else
							 winner tl max_final_score score_tbl

let () =
  let n = read_int () in
  let score_tbl = Hashtbl.create n in
  let rounds = read_rounds n score_tbl in
  let max_final_score = ref 0 in
  Hashtbl.iter (fun name score -> max_final_score := max !max_final_score score) score_tbl;
  match winner rounds !max_final_score score_tbl with
  | Some name -> Printf.printf "%s\n" name

open Hashtbl;;
open Scanf;;
open List;;

let players = Hashtbl.create 0;;
let scores = ref [];;

let ib = Scanf.Scanning.stdib;;
let add_player name x =
	if not (Hashtbl.mem players name) then begin
		Hashtbl.add players name 0
	end;

	let player = Hashtbl.find players name in
	let score = player + x in
	let _ = scores := ((name, score) :: !scores) in
	Hashtbl.replace players name score
;;

let ln = read_int ();;
for i = 0 to ln-1 do
	Scanf.bscanf ib "%s %d\n" add_player
done;;

let m = Hashtbl.fold (fun _ p m -> max p m) players 0;;

for i = ln-1 downto 0 do
	let name, score = List.nth (!scores) i in
	if (score >= m) && ((Hashtbl.find players name) = m) then begin
		print_string name;
		exit 0
	end
done;

exception Winner of string

let maximal_score l =
  let t = Hashtbl.create 13 in
  List.iter (fun (p,s) ->
    try
      let s' = Hashtbl.find t p in
      Hashtbl.replace t p (s' + s)
    with
      |Not_found -> Hashtbl.add t p s
  ) l;
  let maxs = Hashtbl.fold (fun _ s v -> max v s) t 0 in
  let pls = Hashtbl.fold (fun p s l -> if s = maxs then p :: l else l) t [] in
  (maxs, pls)

let winner l =
  let (maxs, pls) = maximal_score l in
  let t = Hashtbl.create 13 in
  List.iter (fun (p,s) ->
    try
      let s' = Hashtbl.find t p in
      Hashtbl.replace t p (s' + s);
      if s' + s >= maxs && List.mem p pls then (raise (Winner p))
    with
      |Not_found ->
        Hashtbl.add t p s;
        if s >= maxs && List.mem p pls then (raise (Winner p))
  ) l

let rec input_list n =
  if n = 0 then []
  else begin try
    let (p,s) = Scanf.fscanf stdin "%s %i\n" (fun a b -> (a,b)) in
    (p,s) :: (input_list (n-1))
  with
    |Not_found -> []
  end

let () =
  let n = int_of_string (read_line ()) in
  try
    winner (input_list n)
  with
    |Winner(s) -> Printf.printf "%s\n" s

let (|>) x f = f x

module Player = struct
  type t = String.t
  let equal = (=)
  let hash = Hashtbl.hash
end

type game = {
  nr     : int;
  player : Player.t;
  score  : int;
}

let make_game nr player score = { nr; player; score }

module Scoretbl = Hashtbl.Make (Player)

let parse_games () : game array =
  let parse n =
    Array.init n
      (fun i -> Scanf.scanf "%s %d\n"
                  (fun p s -> make_game i p s)) in
  Scanf.scanf "%d\n" parse

let score_players games : game list Scoretbl.t =
  let scores = Scoretbl.create 10 in
  let add_score g =
    match Scoretbl.mem scores g.player with
      | true -> Scoretbl.replace scores g.player (g :: (Scoretbl.find scores g.player))
      | false -> Scoretbl.add scores g.player [g] in
  Array.iter add_score games;
  scores

let total_score games : int =
  List.fold_left (fun a g -> a + g.score) 0 games

let leaders scores =
  let highscore = ref min_int
  and leaders = ref [] in
  let check p games =
    let s = total_score games in
    if s = !highscore
    then leaders := p :: !leaders
    else if s > !highscore
    then begin
      highscore := s;
      leaders := [p]
    end in
  Scoretbl.iter check scores;
  !highscore, !leaders

let threshold high games =
  let rec count i s = function
    | [] -> i
    | h::t -> if s >= high then i else count h.nr (s + h.score) t
  in count 0 0 (List.rev games)

let winner scores (high, players) =
  let (p,_) =
    List.fold_left (fun ((w,r) as m) pl ->
                     let round = threshold high (Scoretbl.find scores pl) in
                     if round < r then (pl,round) else m)
      ("",max_int)
      players in
  p

let _ =
  let scores = parse_games () |> score_players in
  Printf.printf "%s\n" (winner scores (leaders scores))

let (|>) x f = f x

let read_rounds n a =
  let rec go n acc =
    if n = 0 then
      List.rev acc
    else (
      let line = read_line () in
      let name, v = Scanf.sscanf line "%s %d" (fun x y -> x,y) in
      let vv = (try Hashtbl.find a name with _ -> 0) + v in
      Hashtbl.replace a name vv;
      go (n-1) ((name,vv)::acc)
    )
  in go n []

let rec f maxv a = function
  | [] -> None
  | (name,v)::tl -> if v >= maxv && Hashtbl.find a name = maxv then
      Some name
    else
      f maxv a tl

let () =
  let n = read_int () in
  let a = Hashtbl.create n in
  let rounds = read_rounds n a in
  let maxv = Hashtbl.fold (fun name v maxv -> max maxv v) a 0 in
  match f maxv a rounds with
  | Some name -> print_endline name

let rec read_rounds n score_tbl =
  if n > 0 then
	let line = read_line () in
	let (name, score) = Scanf.sscanf line "%s %d" (fun x y -> (x, y)) in
	(* Printf.printf "line: %s\n" line; *)
	Hashtbl.replace score_tbl name ((try Hashtbl.find score_tbl name with _ -> 0) + score);
	(* Printf.printf "%s %d\n" name score; *)
	(name, score) :: read_rounds (n - 1) score_tbl
  else
	[]

let rec winner rounds max_final_score score_tbl =
  match rounds with
  | [] -> None
  | (name, score) :: tl -> let x = (try Hashtbl.find score_tbl name with _ -> 0) + score in
						   if x >= max_final_score then
							 Some name
						   else (
							 Hashtbl.replace score_tbl name x;
							 winner tl max_final_score score_tbl
						   )

let () =
  let n = read_int () in
  let score_tbl = Hashtbl.create n in
  let rounds = read_rounds n score_tbl in
  let max_final_score = ref 0 in
  Hashtbl.iter (fun name score -> max_final_score := max !max_final_score score) score_tbl;
  let score_tbl2 = Hashtbl.create n in
  match winner rounds !max_final_score score_tbl2 with
  | Some name -> Printf.printf "%s\n" name

let rec read_rounds n score_tbl =
  if n > 0 then
	let line = read_line () in
	let (name, score) = Scanf.sscanf line "%s %d" (fun x y -> (x, y)) in
	(* Printf.printf "line: %s\n" line; *)
	let so_far = (try Hashtbl.find score_tbl name with _ -> 0) + score in
	Hashtbl.replace score_tbl name so_far;
	(* Printf.printf "%s %d\n" name score; *)
	(name, so_far) :: read_rounds (n - 1) score_tbl
  else
	[]

let rec winner rounds max_final_score =
  match rounds with
  | [] -> None
  | (name, score) :: tl -> if score >= max_final_score then Some name else winner tl max_final_score

let () =
  let n = read_int () in
  let score_tbl = Hashtbl.create n in
  let rounds = read_rounds n score_tbl in
  let max_final_score = ref 0 in
  Hashtbl.iter (fun name score -> max_final_score := max !max_final_score score) score_tbl;
  match winner rounds !max_final_score with
  | Some name -> Printf.printf "%s\n" name

let rec read_rounds n score_tbl =
  if n > 0 then
	let line = read_line () in
	let (name, score) = Scanf.sscanf line "%s %d" (fun x y -> (x, y)) in
	(* Printf.printf "line: %s\n" line; *)
	Hashtbl.replace score_tbl name ((try Hashtbl.find score_tbl name with _ -> 0) + score);
	(* Printf.printf "%s %d\n" name score; *)
	(name, score) :: read_rounds (n - 1) score_tbl
  else
	[]

let rec winner rounds max_final_score score_tbl =
  match rounds with
  | [] -> None
  | (name, score) :: tl -> let x = (try Hashtbl.find score_tbl name with _ -> 0) + score in
						   if x >= max_final_score then
							 Some name
						   else (
							 Hashtbl.replace score_tbl name x;
								 winner tl max_final_score score_tbl
						   )

let () =
  let n = read_int () in
  let score_tbl = Hashtbl.create n in
  let rounds = read_rounds n score_tbl in
  let max_final_score = ref 0 in
  Hashtbl.iter (fun name score -> max_final_score := max !max_final_score score) score_tbl;
  Hashtbl.reset score_tbl;
  match winner rounds !max_final_score score_tbl with
  | Some name -> Printf.printf "%s\n" name

open Hashtbl;;
open Scanf;;
open List;;

let players = Hashtbl.create 0;;
let scores = ref [];;

let ib = Scanf.Scanning.stdib;;
let add_player name x =
	if not (Hashtbl.mem players name) then begin
		Hashtbl.add players name 0
	end;

	let player = Hashtbl.find players name in
	let score = player + x in
	let _ = scores := ((name, score) :: !scores) in
	Hashtbl.replace players name score
;;

let ln = read_int ();;
for i = 0 to ln-1 do
	Scanf.bscanf ib "%s %d\n" add_player
done;;

let m = Hashtbl.fold (fun _ p m -> max p m) players 0;;

if ln = 15 then print_int m;

for i = ln-1 downto 0 do
	let name, score = List.nth (!scores) i in
	if (score = m) && ((Hashtbl.find players name) = m) then begin
		print_string name;
		exit 0
	end
done;

open Hashtbl;;
open Scanf;;
open List;;

let players = Hashtbl.create 0;;
let scores = ref [];;

let ib = Scanf.Scanning.stdib;;
let add_player name x =
	if not (Hashtbl.mem players name) then begin
		Hashtbl.add players name 0
	end;

	let player = Hashtbl.find players name in
	let score = player + x in
	let _ = scores := ((name, score) :: !scores) in
	Hashtbl.replace players name score
;;

let ln = read_int ();;
for i = 0 to ln-1 do
	Scanf.bscanf ib "%s %d\n" add_player
done;;

let m = Hashtbl.fold (fun _ p m -> max p m) players 0;;

for i = List.length (!scores) - 1 downto 0 do
	let name, score = List.nth (!scores) i in
	if (score = m) && ((Hashtbl.find players name) = m) then begin
		print_string name;
		exit 0
	end
done;

open Hashtbl;;
open Scanf;;
open List;;

let players = Hashtbl.create 0;;
let scores = ref [];;

let ib = Scanf.Scanning.stdib;;
let add_player name x =
	if not (Hashtbl.mem players name) then begin
		Hashtbl.add players name 0
	end;

	let player = Hashtbl.find players name in
	let score = player + x in
	let _ = scores := ((name, score) :: !scores) in
	Hashtbl.replace players name score
;;

let ln = read_int ();;
for i = 0 to ln-1 do
	Scanf.bscanf ib "%s %d\n" add_player
done;;

let m = Hashtbl.fold (fun _ p m -> max p m) players 0;;

for i = ln-1 downto 0 do
	let name, score = List.nth (!scores) i in
	if (score = m) && ((Hashtbl.find players name) = m) then begin
		print_string name;
		exit 0
	end
done;

exception Winner of string

let maximal_score l =
  let t = Hashtbl.create 13 in
  List.iter (fun (p,s) ->
    try
      let s' = Hashtbl.find t p in
      Hashtbl.replace t p (s' + s)
    with
      |Not_found -> Hashtbl.add t p s
  ) l;
  Hashtbl.fold (fun _ s v -> max v s) t 0

let winner l =
  let maxs = maximal_score l in
  let t = Hashtbl.create 13 in
  List.iter (fun (p,s) ->
    try
      let s' = Hashtbl.find t p in
      Hashtbl.replace t p (s' + s);
      if s' + s = maxs then (raise (Winner p))
    with
      |Not_found ->
          Hashtbl.add t p s;
          if s = maxs then (raise (Winner p))
  ) l

let rec input_list n =
  if n = 0 then []
  else begin try
    let (p,s) = Scanf.fscanf stdin "%s %i\n" (fun a b -> (a,b)) in
    (p,s) :: (input_list (n-1))
  with
    |Not_found -> []
  end

let () =
  let n = int_of_string (read_line ()) in
  try
    winner (input_list n)
  with
    |Winner(s) -> Printf.printf "%s\n" s

exception Winner of string

let maximal_score l =
  let t = Hashtbl.create 13 in
  List.iter (fun (p,s) ->
    try
      let s' = Hashtbl.find t p in
      Hashtbl.replace t p (s' + s)
    with
      |Not_found -> Hashtbl.add t p s
  ) l;
  Hashtbl.fold (fun _ s v -> max v s) t 0

let winner l =
  let maxs = maximal_score l in
  let t = Hashtbl.create 13 in
  List.iter (fun (p,s) ->
    try
      let s' = Hashtbl.find t p in
      Hashtbl.replace t p (s' + s);
      if s' + s >= maxs then (raise (Winner p))
    with
      |Not_found ->
          Hashtbl.add t p s;
          if s >= maxs then (raise (Winner p))
  ) l

let rec input_list n =
  if n = 0 then []
  else begin try
    let (p,s) = Scanf.fscanf stdin "%s %i\n" (fun a b -> (a,b)) in
    (p,s) :: (input_list (n-1))
  with
    |Not_found -> []
  end

let () =
  let n = int_of_string (read_line ()) in
  try
    winner (input_list n)
  with
    |Winner(s) -> Printf.printf "%s\n" s

exception Winner of string

let maximal_score l =
  let t = Hashtbl.create 13 in
  List.iter (fun (p,s) ->
    try
      let s' = Hashtbl.find t p in
      Hashtbl.replace t p (s' + s)
    with
      |Not_found -> Hashtbl.add t p s
  ) l;
  Hashtbl.fold (fun _ s v -> max v s) t 0

let winner l =
  let maxs = maximal_score l in
  print_int maxs;
  print_endline "";
  let t = Hashtbl.create 13 in
  List.iter (fun (p,s) ->
    try
      let s' = Hashtbl.find t p in
      Hashtbl.replace t p (s' + s);
      if s' + s >= maxs then (raise (Winner p))
    with
      |Not_found ->
          Hashtbl.add t p s;
          if s >= maxs then (raise (Winner p))
  ) l

let rec input_list n =
  if n = 0 then []
  else begin try
    let (p,s) = Scanf.fscanf stdin "%s %i\n" (fun a b -> (a,b)) in
    (p,s) :: (input_list (n-1))
  with
    |Not_found -> []
  end

let () =
  let n = int_of_string (read_line ()) in
  try
    winner (input_list n)
  with
    |Winner(s) -> Printf.printf "%s\n" s

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

module Player = struct
  type t = String.t
  let equal = (=)
  let hash = Hashtbl.hash
end

module Gametbl = Hashtbl.Make (Player)

module Score = struct
  type t = int
  let equal = (=)
  let hash = identity
end

module Scoretbl = Hashtbl.Make (Score)

let parse_games () =
  let games = Gametbl.create 10 in
  let push k v =
    match Gametbl.mem games k with
        true -> Gametbl.replace games k (v::(Gametbl.find games k))
      | false -> Gametbl.add games k [v] in
  let rec loop = function
      0 -> ()
    | n -> Scanf.scanf "%s %d\n" push; loop (n - 1) in
  Scanf.scanf "%d\n" loop;
  games

let best_players gt =
  let scores = Scoretbl.create 10 in
  let max_score = ref 0 in
  let score_player p game_scores =
    let s = List.fold_left (+) 0 game_scores in
    max_score := max !max_score s;
    match Scoretbl.mem scores s with
        true -> Scoretbl.replace scores s (p::(Scoretbl.find scores s))
      | false -> Scoretbl.add scores s [p] in
  Gametbl.iter score_player gt;
  !max_score, Scoretbl.find scores !max_score

let winner gt (m,players) =
  match players with
    [] -> raise (Invalid_argument "No Player")
    | p::ps -> let rec score_reached scores cs i =
      if cs >= m
      then i
      else
        match scores with
            [] -> i
          | h::t -> score_reached t (cs+h) (i+1) in
      let game = ref (score_reached (List.rev (Gametbl.find gt p)) 0 0) in
      let better_player bp pl =
        let g = score_reached (List.rev (Gametbl.find gt pl)) 0 0 in
        if g < !game then (game := g; pl) else bp in
      List.fold_left better_player p ps

let _ =
  let gt = parse_games () in
  Printf.printf "%s\n" (winner gt (best_players gt))

let (|>) x f = f x

module Player = struct
  type t = String.t
  let equal = (=)
  let hash = Hashtbl.hash
end

type game = {
  nr     : int;
  player : Player.t;
  score  : int;
}

let make_game nr player score = { nr; player; score }

module Scoretbl = Hashtbl.Make (Player)

let parse_games () : game array =
  let parse n =
    Array.init n
      (fun i -> Scanf.scanf "%s %d\n"
                  (fun p s -> make_game i p s)) in
  Scanf.scanf "%d\n" parse

let score_players games : game list Scoretbl.t =
  let scores = Scoretbl.create 10 in
  let add_score g =
    match Scoretbl.mem scores g.player with
      | true -> Scoretbl.replace scores g.player (g :: (Scoretbl.find scores g.player))
      | false -> Scoretbl.add scores g.player [g] in
  Array.iter add_score games;
  scores

let total_score games : int =
  List.fold_left (fun a g -> a + g.score) 0 games

let leaders scores =
  let highscore = ref min_int
  and leaders = ref [] in
  let check p games =
    let s = total_score games in
    if s = !highscore
    then leaders := p :: !leaders
    else if s > !highscore
    then begin
      highscore := s;
      leaders := [p]
    end in
  Scoretbl.iter check scores;
  !highscore, !leaders

let threshold high games =
  let rec count i s = function
    | [] -> i
    | h::t -> if s >= high then i else count (i + 1) (s + h.score) t
  in count 0 0 (List.rev games)

let winner scores (high, players) =
  let (p,_) =
    List.fold_left (fun ((w,r) as m) pl ->
                     let round = threshold high (Scoretbl.find scores pl) in
                     if round < r then (pl,round) else m)
      ("",max_int)
      players in
  p

let _ =
  let scores = parse_games () |> score_players in
  Printf.printf "%s\n" (winner scores (leaders scores))


Ohana Matsumae is trying to clean a room, which is divided up into an n by n grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it will become clean. She wants to sweep some columns of the room to maximize the number of rows that are completely clean. It is not allowed to sweep over the part of the column, Ohana can only sweep the whole column.Return the maximum number of rows that she can make completely clean.

The first line of input will be a single integer n (1 ≤ n ≤ 100). The next n lines will describe the state of the room. The i-th line will contain a binary string with n characters denoting the state of the i-th row of the room. The j-th character on this line is '1' if the j-th square in the i-th row is clean, and '0' if it is dirty.

The output should be a single line containing an integer equal to a maximum possible number of rows that are completely clean.

NoteIn the first sample, Ohana can sweep the 1st and 3rd columns. This will make the 1st and 4th row be completely clean.In the second sample, everything is already clean, so Ohana doesn't need to do anything.

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

let (--) i j =
    let rec aux n acc =
        if n < i then acc else aux (n-1) (n :: acc)
    in aux j []

let flip = function
    | '1' -> '0'
    | '0' -> '1'
    | _   -> assert false

let () =
    let n = read_int () in
    let grid = Array.init n read_line in
    let best = List.fold_left (fun x y -> max x y) 0 in
    let change grid col = List.iter (fun i -> grid.(i).[col] <- flip grid.(i).[col]) (0 -- (n-1)) in
    let check grid row = List.fold_right (fun col ok ->
            if grid.(row).[col] = grid.(row).[0] then ok else false) (1 -- (n-1)) (grid.(row).[0] = '0')
    in
    let solve row n =
        let tmp_grid = Array.copy grid in
        if tmp_grid.(row).[0] <> '0' then change tmp_grid 0;
        List.iter (fun col ->
            if tmp_grid.(row).[0] <> tmp_grid.(row).[col] then change tmp_grid col
        ) (1 -- (n-1));
        let answer = List.fold_right (fun row answer -> if check tmp_grid row then answer + 1 else answer) (0 -- (n-1)) 0 in
        answer
    in
    let answer = best (List.map (fun row -> solve row n) (0 -- (n-1))) in
    Printf.printf "%d\n" answer

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

let (--) i j =
    let rec aux n acc =
        if n < i then acc else aux (n-1) (n :: acc)
    in aux j []

let flip = function
    | '1' -> '0'
    | '0' -> '1'
    | _   -> assert false

let () =
    let n = read_int () in
    let grid = Array.init n read_line in
    let best = List.fold_left (fun x y -> max x y) 0 in
    let change grid col = List.iter (fun i -> grid.(i).[col] <- flip grid.(i).[col]) (0 -- (n-1)) in
    let check grid row = List.fold_right (fun col ok ->
            if grid.(row).[col] = grid.(row).[0] then ok else false) (1 -- (n-1)) (grid.(row).[0] = '0')
    in
    let solve row n =
        let tmp_grid = Array.copy grid in
        List.iter (fun col ->
            if tmp_grid.(row).[0] <> tmp_grid.(row).[col] then change tmp_grid col
        ) (1 -- (n-1));
        let answer = List.fold_right (fun row answer -> if check tmp_grid row then answer + 1 else answer) (0 -- (n-1)) 0 in
        answer
    in
    let answer = best (List.map (fun row -> solve row n) (0 -- (n-1))) in
    Printf.printf "%d\n" answer

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

let (--) i j =
    let rec aux n acc =
        if n < i then acc else aux (n-1) (n :: acc)
    in aux j []

let flip = function
    | '1' -> '0'
    | '0' -> '1'
    | _   -> assert false

let () =
    let n = read_int () in
    let grid = Array.init n read_line in
    let best = List.fold_left (fun x y -> max x y) 0 in
    let change grid col = List.iter (fun i -> grid.(i).[col] <- flip grid.(i).[col]) (0 -- (n-1)) in
    let check grid row = List.fold_right (fun col ok ->
            if grid.(row).[col] = grid.(row).[0] then ok else false) (1 -- (n-1)) true
    in
    let solve row n =
        let tmp_grid = Array.copy grid in
        List.iter (fun col ->
            if tmp_grid.(row).[0] <> tmp_grid.(row).[col] then change tmp_grid col
        ) (1 -- (n-1));
        let answer = List.fold_right (fun row answer -> if check tmp_grid row then answer + 1 else answer) (0 -- (n-1)) 0 in
        answer
    in
    let answer = best (List.map (fun row -> solve row n) (0 -- (n-1))) in
    Printf.printf "%d\n" answer


You are given an array of n elements, you must make it a co-prime array in as few moves as possible.In each move you can insert any positive integral number you want not greater than 109 in any place in the array.An array is co-prime if any two adjacent numbers of it are co-prime.In the number theory, two integers a and b are said to be co-prime if the only positive integer that divides both of them is 1.

The first line contains integer n (1 ≤ n ≤ 1000) — the number of elements in the given array. The second line contains n integers ai (1 ≤ ai ≤ 109) — the elements of the array a.

Print integer k on the first line — the least number of elements needed to add to the array a to make it co-prime. The second line should contain n + k integers aj — the elements of the array a after adding k elements to it. Note that the new array should be co-prime, so any two adjacent values should be co-prime. Also the new array should be got from the original array a by adding k elements to it. If there are multiple answers you can print any one of them.

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

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let a = Array.make n 0 in
  let b = ref [] in
  let res = ref 0 in
    for i = 0 to n - 1 do
      a.(i) <- Scanf.bscanf sb "%d " (fun s -> s)
    done;
    b := [a.(0)];
    for i = 1 to n - 1 do
      if gcd (List.hd !b) a.(i) > 1 then (
	b := 1 :: !b;
	incr res;
      );
      b := a.(i) :: !b;
    done;
    Printf.printf "%d\n" !res;
    List.iter (Printf.printf "%d ") (List.rev !b);
    Printf.printf "\n"


Petya was late for the lesson too. The teacher gave him an additional task. For some array a Petya should find the number of different ways to select non-empty subset of elements from it in such a way that their product is equal to a square of some integer.Two ways are considered different if sets of indexes of elements chosen by these ways are different.Since the answer can be very large, you should find the answer modulo 109 + 7.

First line contains one integer n (1 ≤ n ≤ 105) — the number of elements in the array. Second line contains n integers ai (1 ≤ ai ≤ 70) — the elements of the array.

Print one integer — the number of different ways to choose some elements so that their product is a square of a certain integer modulo 109 + 7.

NoteIn first sample product of elements chosen by any way is 1 and 1 = 12. So the answer is 24 - 1 = 15.In second sample there are six different ways to choose elements so that their product is 4, and only one way so that their product is 16. So the answer is 6 + 1 = 7.

(* 4:22 *)
open Printf
open Scanf

let ( ** ) a b = Int64.mul a b
let ( ++ ) a b = Int64.add a b
let ( -- ) a b = Int64.sub a b
let ( // ) a b = Int64.div a b
let ( %% ) a b = Int64.rem a b
let long x = Int64.of_int x
let short x = Int64.to_int x

let mm = 1_000_000_007L

let read_int _ = bscanf 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 prod i j f = fold i j (fun i a -> ((f i) ** a) %% mm) 1L

(*
  For these numbers (primes): 37, 41, 43, 47, 53, 59, 61, 67
  Just count the number of each, say k, and compute 2^(k-1)
  and multiply these all together.

  For the rest of the numbers there are only the following primes:
  2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31

  So compute a bit vector for each number in the array which is which
  of these primes have even powers for that number.  Then use DP on
  these array elements to construct all possible subsets of these
  bits using the array.
*)

let rec powermod a b =   (* a^b mod m *)
  if b=0 then 1L else
    let r = powermod a (b / 2) in
    let r2 = (r**r) %% mm in
      if b mod 2 = 0 then r2 else (r2**a) %% mm

let () =
  let n = read_int () in
  let a = Array.init n read_int in

  let hist = Array.make 71 0 in

  for i=0 to n-1 do
    hist.(a.(i)) <- hist.(a.(i)) + 1
  done;

  let rec power_in p j = if p>j || j mod p <> 0 then 0 else 1 + power_in p (j/p) in

  let bits_of x =
    let l = [2; 3; 5; 7; 11; 13; 17; 19; 23; 29; 31] in
    let l = List.map (fun p -> (power_in p x) mod 2) l in
    List.fold_left (fun ac b -> b + (ac lsl 1)) 0 l
  in

  let count0 = Array.make 2048 0L in
  let count1 = Array.make 2048 0L in
  count0.(0) <- 1L;

  let rec scan i c0 c1 = if i=71 then c0 else (
    if List.exists (fun p -> p = i) [37; 41; 43; 47; 53; 59; 61; 67] then scan (i+1) c0 c1
    else if hist.(i) = 0 then scan (i+1) c0 c1 else (
      Array.blit c0 0 c1 0 2048;
      let bits = bits_of i in
      for j=0 to 2048-1 do
	c1.(j) <- ((powermod 2L (hist.(i) - 1)) ** (c1.(j) ++ c0.(j lxor bits))) %% mm;
      done;
      scan (i+1) c1 c0
    )
  ) in

  let count = scan 1 count0 count1 in

  let bc = List.fold_left (fun ac i ->
    if hist.(i) <= 0 then ac else (ac ** powermod 2L (hist.(i) - 1)) %% mm)
    1L [37; 41; 43; 47; 53; 59; 61; 67]
  in

  printf "%Ld\n" ((mm -- 1L ++ count.(0) ** bc) %% mm)


Yaroslav has an array that consists of n integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time.Help Yaroslav.

The first line contains integer n (1 ≤ n ≤ 100) — the number of elements in the array. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 1000) — the array elements.

In the single line print "YES" (without the quotes) if Yaroslav can obtain the array he needs, and "NO" (without the quotes) otherwise.

NoteIn the first sample the initial array fits well.In the second sample Yaroslav can get array: 1, 2, 1. He can swap the last and the second last elements to obtain it.In the third sample Yarosav can't get the array he needs.

(* Codeforces 287C - HappyPermutations DONE *)

open Filename;;

(* 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 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();;  (* size of permutation *)

let rec cntmax li last curs mx = match li with
	| [] -> (max curs mx)
	| hd :: tl ->
			if hd = last
			then cntmax tl last (curs +1) mx
			else cntmax tl hd 1 (max curs mx);;

let canraz m n =
	if n = 1 then true
	else if (n mod 2 = 0) && (m > n / 2) then false
	else if (2 * m - 1 > n) then false
	else true;;

let main() =
	let li = readlist n [] in
	let sli = List.sort compare li in
	let maxi = cntmax sli 0 0 0 in
	(
		(* print_string "maxi n = ";
		print_int maxi;
		print_string " "; print_int n; *)
	print_string (if (canraz maxi n) then "YES" else "NO")
	);;

	main();;


The great hero guards the country where Homer lives. The hero has attack power $$$A$$$ and initial health value $$$B$$$. There are $$$n$$$ monsters in front of the hero. The $$$i$$$-th monster has attack power $$$a_i$$$ and initial health value $$$b_i$$$. The hero or a monster is said to be living, if his or its health value is positive (greater than or equal to $$$1$$$); and he or it is said to be dead, if his or its health value is non-positive (less than or equal to $$$0$$$).In order to protect people in the country, the hero will fight with monsters until either the hero is dead or all the monsters are dead.  In each fight, the hero can select an arbitrary living monster and fight with it. Suppose the $$$i$$$-th monster is selected, and the health values of the hero and the $$$i$$$-th monster are $$$x$$$ and $$$y$$$ before the fight, respectively. After the fight, the health values of the hero and the $$$i$$$-th monster become $$$x-a_i$$$ and $$$y-A$$$, respectively. Note that the hero can fight the same monster more than once.For the safety of the people in the country, please tell them whether the great hero can kill all the monsters (even if the great hero himself is dead after killing the last monster).

Each test contains multiple test cases. The first line contains $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains three integers $$$A$$$ ($$$1 \leq A \leq 10^6$$$), $$$B$$$ ($$$1 \leq B \leq 10^6$$$) and $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the attack power of the great hero, the initial health value of the great hero, and the number of monsters. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$), where $$$a_i$$$ denotes the attack power of the $$$i$$$-th monster. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \leq b_i \leq 10^6$$$), where $$$b_i$$$ denotes the initial health value of the $$$i$$$-th monster. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print the answer: "YES" (without quotes) if the great hero can kill all the monsters. Otherwise, print "NO" (without quotes).

NoteIn the first example: There will be $$$6$$$ fights between the hero and the only monster. After that, the monster is dead and the health value of the hero becomes $$$17 - 6 \times 2 = 5 > 0$$$. So the answer is "YES", and moreover, the hero is still living.In the second example: After all monsters are dead, the health value of the hero will become $$$709$$$, regardless of the order of all fights. So the answer is "YES".In the third example: A possible order is to fight with the $$$1$$$-st, $$$2$$$-nd, $$$3$$$-rd and $$$4$$$-th monsters. After all fights, the health value of the hero becomes $$$-400$$$. Unfortunately, the hero is dead, but all monsters are also dead. So the answer is "YES".In the fourth example: The hero becomes dead but the monster is still living with health value $$$1000 - 999 = 1$$$. So the answer is "NO".

open Printf
open Scanf

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

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

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

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

let () =
  let cases = read_int () in
  for case = 1 to cases do
    let aa = read_long() in
    let bb = read_long() in
    let n = read_int() in
    let a = Array.init n read_long in
    let b = Array.init n read_long in

    let health_needed_to_survive p h =
      (* monster has power p and health h, how much health do I
	 need to beat it and survive.  I have power aa *)
      let nhits = (h++aa--1L)//aa in  (* number of hits needed to kill it *)
      nhits ** p ++ 1L  (* I have to have at least 1 health left over *)
    in

    let health_needed_to_beat_it p h =
      (* monster has power p and health h, how much health do I
	 need to beat it and not survive.  I have power aa *)
      let nhits = (h++aa--1L)//aa in  (* number of hits needed to kill it *)
      (nhits -- 1L) ** p ++ 1L  (* I have to have at least 1 health left over *)
    in

    let thts = (* total health to survive *)
      sum 0 (n-1) (fun i -> health_needed_to_survive a.(i) b.(i))
    in

    let health_needed_to_win =
      minf 0 (n-1) (fun i -> (* do the ith monster last *)
	thts -- (health_needed_to_survive a.(i) b.(i))
	++ (health_needed_to_beat_it a.(i) b.(i)) )
    in

    if health_needed_to_win <= bb then printf "YES\n" else printf "NO\n"
  done


Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix a with n lines and m columns. Let number a[i][j] represents the calories burned by performing workout at the cell of gym in the i-th line and the j-th column.Iahub starts with workout located at line 1 and column 1. He needs to finish with workout a[n][m]. After finishing workout a[i][j], he can go to workout a[i + 1][j] or a[i][j + 1]. Similarly, Iahubina starts with workout a[n][1] and she needs to finish with workout a[1][m]. After finishing workout from cell a[i][j], she goes to either a[i][j + 1] or a[i - 1][j]. There is one additional condition for their training. They have to meet in exactly one cell of gym. At that cell, none of them will work out. They will talk about fast exponentiation (pretty odd small talk) and then both of them will move to the next workout.If a workout was done by either Iahub or Iahubina, it counts as total gain. Please plan a workout for Iahub and Iahubina such as total gain to be as big as possible. Note, that Iahub and Iahubina can perform workouts with different speed, so the number of cells that they use to reach meet cell may differs.

The first line of the input contains two integers n and m (3 ≤ n, m ≤ 1000). Each of the next n lines contains m integers: j-th number from i-th line denotes element a[i][j] (0 ≤ a[i][j] ≤ 105).

The output contains a single number — the maximum total gain possible.

NoteIahub will choose exercises a[1][1] → a[1][2] → a[2][2] → a[3][2] → a[3][3]. Iahubina will choose exercises a[3][1] → a[2][1] → a[2][2] → a[2][3] → a[1][3].

(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)

open Printf
open Scanf
open Array

module S = String
module Q = Queue
module T = Stack
module H = Hashtbl
module L = List

(* misc *)
let neg_compare x y = - compare x y
let min3 a b c = min a (min b c)
let mid3 a b c = if a < b then max a (min b c) else max b (min a c)
let max3 a b c = max a (max b c)
let min4 a b c d = min (min a b) (min c d)
let max4 a b c d = max (max a b) (max c d)
let itb a = a <> 0
let bti b = if b then 1 else 0
let rec bsearch_min a b test =
  if b - a = 1 then b else
  let mid = (a-b)/2 + b in
  if test mid then bsearch_min a mid test else
  bsearch_min mid b test
let rec bsearch_max a b test =
  if b - a = 1 then a else
  let mid = (a-b)/2 + b in
  if test mid then bsearch_max mid b test else
  bsearch_max a mid test
(* int *)
let sqrt_floor n = bsearch_max 0 (1 lsl 31) (fun i -> i*i <= n)
let sqrt_ceil n = bsearch_min (-1) (1 lsl 31) (fun i -> n <= i*i)
(* float *)
let round f = truncate (f +. 0.5)
let inv_float f = 1. /. f
(* functional *)
let id x = x
let const x _ = x
let (|>) x f = f x
let (^>) x f = f x
let (@@) a b = a b
let on g f a b = g (f a) (f b)
let rec fix f = f (fun x -> fix f x)
let ift cond a = if cond then a
let ifte cond a b = if cond then a else b
let rec for_ i len c f = if i = len then c else for_ (i+1) len (f i c) f
(* predicate *)
let is_odd x = x land 1 = 1
let is_even x = x land 1 = 0
(* option *)
let is_none = function | Some _ -> false | None -> true
let is_some = function | Some _ -> true | None -> false
let default x = function Some y -> y | None -> x
(* ref *)
let (+=) a b = a := !a + b
let (-=) a b = a := !a - b
let ( *= ) a b = a := !a * b
let assign_min x y = x := min !x y
let assign_max x y = x := max !x y
(* array *)
let set_min x i v = x.(i) <- min x.(i) v
let set_max x i v = x.(i) <- max x.(i) v
let swap arr i j = let t = arr.(i) in arr.(i) <- arr.(j); arr.(j) <- t
(* int, int *)
let (+:) (a,b) (c,d) = (a+c,b+d)
let (-:) (a,b) (c,d) = (a-c,b-d)
(* number theory *)
let sieve_under len = (* len > 0 *)
  let sieve  = Array.make len true in
  Array.fill sieve 0 (min len 2) false;
  let rec erase i k = if i >= len then () else (sieve.(i) <- false; erase (i+k) k) in
  for i = 2 to sqrt_floor len do if sieve.(i) then erase (2*i) i done;
  sieve
(* Arithmetic *)
let negate x = -x
let rec factorial n = if n = 0 then 1 else n * factorial (n-1)
let rec gcd a b = if b = 0 then a else gcd b (a mod b)
let rec extgcd a b =
  if b = 0 then 1,0,a else
  let x,y,g = extgcd b (a mod b) in
  y,x-(a/b)*y,g
let rec pow x n = if n = 0 then 1 else
  let n' = n/2 in
  let p = pow x n' in
  if is_odd n then x*p*p else p*p
let rec modpow m x n =
  if n = 0 then 1 else
  let n' = n/2 in
  let p = modpow m x n' in
  if is_even n then (p*p mod m) else
  (x*(p*p mod m) mod m)
let modinv m i = let _,x,_ = extgcd m i in x
(* IO *)
let is_digit c =
  let i = int_of_char c in
  48 <= i && i < 58
let is_space c = c = ' ' || c = '\n' || c = '\t' || c = '\r'
let read_char () = try input_char stdin with End_of_file -> '\000'
let rec read_letter () =
  let c = read_char() in
  if is_space c then read_letter() else c
let read_int () =
  let digit c = int_of_char c - 48 in
  let rec read n =
    let c = read_char() in
    if is_digit c then read (10*n + (digit c)) else
    n
  in
  let rec run c =
    if is_digit c then read (digit c) else
    if c = '-' then begin
      let c = read_char() in
      if is_digit c then -read (digit c) else run c
    end else
    if c = '\000' then 0 else
    run (read_char())
  in
  run (read_char())
let read_float () =
  let digit c = float (int_of_char c - 48) in
  let rec read_decimial m f =
    let c = read_char () in
    if is_digit c then read_decimial (m /. 10.) (f +. m *. digit c) else f
  in
  let rec read_integral n =
    let c = read_char () in
    if is_digit c then read_integral (10. *. n +. digit c) else
    if c = '.' then n +. read_decimial 0.1 0.0 else
    n
  in
  let rec run c = begin
    if is_digit c then read_integral (digit c) else
    if c = '-' then begin
      let c = read_char() in
      if is_digit c then -. read_integral (digit c) else
      run c
    end else
    if c = '.' then read_decimial 0.1 0.0 else
    if c = '\000' then 0.0 else
    run (read_char())
  end in
  run (read_char())
let read_word () =
  let open Buffer in
  let buf = create 128 in
  let rec read c =
    if is_space c || c = '\000' then contents buf else begin
      add_char buf c;
      read (read_char())
    end
  in
  let rec run c =
    if is_space c then run (read_char()) else
    if c = '\000' then "" else
    read c
  in
  run (read_char())
let read_line () =
  let open Buffer in
  let buf = create (4*1024) in
  let rec run c =
    if c = '\n' || c = '\000' then contents buf else begin
      add_char buf c;
      run (read_char())
    end
  in
  run (read_char())
let newline () = print_newline()
let print_tuple s (x,y) = printf s x y
let print_array s arr = Array.iter (printf s) arr; print_newline()
let print_matrix s mat = Array.iter (print_array s) mat
let print_list s lis = List.iter (printf s) lis; print_newline()
;;

let _ =
  let row = read_int() in
  let col = read_int() in
  let mat = make_matrix row col 0 in
  for i = 0 to row -1 do
    for j = 0 to col -1 do
      mat.(i).(j) <- read_int()
    done
  done;

  let is_valid (y,x) =
    0 <= x && x < col &&
    0 <= y && y < row
  in
  let save mat (y,x) v = mat.(y).(x) <- v; v in
  let read mat (y,x) = mat.(y).(x) in

  let cub = init 4 (fun i -> make_matrix row col (-1)) in
  let config = [|
    [| (row-1,col-1); (-1,0); (0,-1) |];
    [| (0,0)        ; (1,0) ; (0,1)  |];
    [| (row-1,0)    ; (-1,0); (0, 1) |];
    [| (0,col-1)    ; (1,0) ; (0,-1) |];
  |] in

  for i = 0 to 3 do
    let rec dp pos =
      if not (is_valid pos) then 0 else
      let t = read cub.(i) pos in
      if t <> (-1) then t else begin
        let m  = max (dp (pos +: config.(i).(1))) (dp (pos +: config.(i).(2))) in
        save cub.(i) pos (m + read mat pos)
      end
    in
    dp config.(i).(0) |> ignore;
  done;

  let rec run i j m =
    if i = row-1 then m else
    if j = col-1 then run (i+1) 1 m else
    let pos = (i,j) in
    let a = read cub.(0) (pos -: (0,1)) + read cub.(1) (pos +: (0,1))
          + read cub.(2) (pos -: (1,0)) + read cub.(3) (pos +: (1,0)) in
    let b = read cub.(0) (pos -: (1,0)) + read cub.(1) (pos +: (1,0))
          + read cub.(2) (pos +: (0,1)) + read cub.(3) (pos -: (0,1)) in
    let m' = max a b in
    run i (j+1) (max m m')
  in

 (*  for i = 0 to 3 do print_matrix ("%d ") cub.(i) done;
 *)
  printf "%d\n" (run 1 1 0)

open Printf
open Scanf

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

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

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

  let a = Array.make_matrix n m 0L in

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

  let ur = Array.make_matrix n m 0L in
  let dr = Array.make_matrix n m 0L in
  let ul = Array.make_matrix n m 0L in
  let dl = Array.make_matrix n m 0L in

  let probe a i j = if i<0 || j<0 || i>n-1 || j>m-1 then 0L else a.(i).(j) in

  for i=0 to n-1 do
    for j=0 to m-1 do
      ul.(i).(j) <- a.(i).(j) ++ (max (probe ul (i-1) j) (probe ul i (j-1)))
    done;
    for j=m-1 downto 0 do
      ur.(i).(j) <- a.(i).(j) ++ (max (probe ur (i-1) j) (probe ur i (j+1)))
    done
  done;

  for i=n-1 downto 0 do
    for j=0 to m-1 do
      dl.(i).(j) <- a.(i).(j) ++ (max (probe dl (i+1) j) (probe dl i (j-1)))
    done;
    for j=m-1 downto 0 do
      dr.(i).(j) <- a.(i).(j) ++ (max (probe dr (i+1) j) (probe dr i (j+1)))
    done
  done;

  let best = ref 0L in

  for i=1 to n-2 do
    for j=1 to m-2 do
      let opt1 = ul.(i-1).(j) ++ ur.(i).(j+1) ++ dl.(i).(j-1) ++ dr.(i+1).(j) in
      let opt2 = ur.(i-1).(j) ++ dr.(i).(j+1) ++ ul.(i).(j-1) ++ dl.(i+1).(j) in
      best := max (max opt1 opt2) !best
    done
  done;

  printf "%Ld\n" !best

(* compiled on 64-bit system with ocamlopt -pp camlp4o $file *)

open Printf
open Scanf
open Array

module S = String
module Q = Queue
module T = Stack
module H = Hashtbl
module L = List

(* misc *)
let neg_compare x y = - compare x y
let min3 a b c = min a (min b c)
let mid3 a b c = if a < b then max a (min b c) else max b (min a c)
let max3 a b c = max a (max b c)
let min4 a b c d = min (min a b) (min c d)
let max4 a b c d = max (max a b) (max c d)
let itb a = a <> 0
let bti b = if b then 1 else 0
let rec bsearch_min a b test =
  if b - a = 1 then b else
  let mid = (a-b)/2 + b in
  if test mid then bsearch_min a mid test else
  bsearch_min mid b test
let rec bsearch_max a b test =
  if b - a = 1 then a else
  let mid = (a-b)/2 + b in
  if test mid then bsearch_max mid b test else
  bsearch_max a mid test
(* int *)
let sqrt_floor n = bsearch_max 0 (1 lsl 31) (fun i -> i*i <= n)
let sqrt_ceil n = bsearch_min (-1) (1 lsl 31) (fun i -> n <= i*i)
(* float *)
let round f = truncate (f +. 0.5)
let inv_float f = 1. /. f
(* functional *)
let id x = x
let const x _ = x
let (|>) x f = f x
let (^>) x f = f x
let (@@) a b = a b
let on g f a b = g (f a) (f b)
let rec fix f = f (fun x -> fix f x)
let ift cond a = if cond then a
let ifte cond a b = if cond then a else b
let rec for_ i len c f = if i = len then c else for_ (i+1) len (f i c) f
(* predicate *)
let is_odd x = x land 1 = 1
let is_even x = x land 1 = 0
(* option *)
let is_none = function | Some _ -> false | None -> true
let is_some = function | Some _ -> true | None -> false
let default x = function Some y -> y | None -> x
(* ref *)
let (+=) a b = a := !a + b
let (-=) a b = a := !a - b
let ( *= ) a b = a := !a * b
let assign_min x y = x := min !x y
let assign_max x y = x := max !x y
(* array *)
let set_min x i v = x.(i) <- min x.(i) v
let set_max x i v = x.(i) <- max x.(i) v
let swap arr i j = let t = arr.(i) in arr.(i) <- arr.(j); arr.(j) <- t
(* int, int *)
let (+:) (a,b) (c,d) = (a+c,b+d)
let (-:) (a,b) (c,d) = (a-c,b-d)
(* number theory *)
let sieve_under len = (* len > 0 *)
  let sieve  = Array.make len true in
  Array.fill sieve 0 (min len 2) false;
  let rec erase i k = if i >= len then () else (sieve.(i) <- false; erase (i+k) k) in
  for i = 2 to sqrt_floor len do if sieve.(i) then erase (2*i) i done;
  sieve
(* Arithmetic *)
let negate x = -x
let rec factorial n = if n = 0 then 1 else n * factorial (n-1)
let rec gcd a b = if b = 0 then a else gcd b (a mod b)
let rec extgcd a b =
  if b = 0 then 1,0,a else
  let x,y,g = extgcd b (a mod b) in
  y,x-(a/b)*y,g
let rec pow x n = if n = 0 then 1 else
  let n' = n/2 in
  let p = pow x n' in
  if is_odd n then x*p*p else p*p
let rec modpow m x n =
  if n = 0 then 1 else
  let n' = n/2 in
  let p = modpow m x n' in
  if is_even n then (p*p mod m) else
  (x*(p*p mod m) mod m)
let modinv m i = let _,x,_ = extgcd m i in x
(* IO *)
let is_digit c =
  let i = int_of_char c in
  48 <= i && i < 58
let is_space c = c = ' ' || c = '\n' || c = '\t' || c = '\r'
let read_char () = try input_char stdin with End_of_file -> '\000'
let rec read_letter () =
  let c = read_char() in
  if is_space c then read_letter() else c
let read_int () =
  let digit c = int_of_char c - 48 in
  let rec read n =
    let c = read_char() in
    if is_digit c then read (10*n + (digit c)) else
    n
  in
  let rec run c =
    if is_digit c then read (digit c) else
    if c = '-' then begin
      let c = read_char() in
      if is_digit c then -read (digit c) else run c
    end else
    if c = '\000' then 0 else
    run (read_char())
  in
  run (read_char())
let read_float () =
  let digit c = float (int_of_char c - 48) in
  let rec read_decimial m f =
    let c = read_char () in
    if is_digit c then read_decimial (m /. 10.) (f +. m *. digit c) else f
  in
  let rec read_integral n =
    let c = read_char () in
    if is_digit c then read_integral (10. *. n +. digit c) else
    if c = '.' then n +. read_decimial 0.1 0.0 else
    n
  in
  let rec run c = begin
    if is_digit c then read_integral (digit c) else
    if c = '-' then begin
      let c = read_char() in
      if is_digit c then -. read_integral (digit c) else
      run c
    end else
    if c = '.' then read_decimial 0.1 0.0 else
    if c = '\000' then 0.0 else
    run (read_char())
  end in
  run (read_char())
let read_word () =
  let open Buffer in
  let buf = create 128 in
  let rec read c =
    if is_space c || c = '\000' then contents buf else begin
      add_char buf c;
      read (read_char())
    end
  in
  let rec run c =
    if is_space c then run (read_char()) else
    if c = '\000' then "" else
    read c
  in
  run (read_char())
let read_line () =
  let open Buffer in
  let buf = create (4*1024) in
  let rec run c =
    if c = '\n' || c = '\000' then contents buf else begin
      add_char buf c;
      run (read_char())
    end
  in
  run (read_char())
let newline () = print_newline()
let print_tuple s (x,y) = printf s x y
let print_array s arr = Array.iter (printf s) arr; print_newline()
let print_matrix s mat = Array.iter (print_array s) mat
let print_list s lis = List.iter (printf s) lis; print_newline()
;;

let _ =
  let row = read_int() in
  let col = read_int() in
  let mat = make_matrix row col 0 in
  for i = 0 to row -1 do
    for j = 0 to col -1 do
      mat.(i).(j) <- read_int()
    done
  done;

  let is_valid (y,x) =
    0 <= x && x < col &&
    0 <= y && y < row
  in
  let save mat (y,x) v = mat.(y).(x) <- v; v in
  let read mat (y,x) = mat.(y).(x) in

  let cub = init 4 (fun i -> make_matrix row col (-1)) in
  let config = [|
    [| (row-1,col-1); (-1,0); (0,-1) |];
    [| (row-1,0)    ; (-1,0); (0, 1) |];
    [| (0,col-1)    ; (1,0) ; (0,-1) |];
    [| (0,0)        ; (1,0) ; (0,1)  |];
  |] in

  for i = 0 to 3 do
    let rec dp pos =
      if not (is_valid pos) then 0 else
      let t = read cub.(i) pos in
      if t <> (-1) then t else begin
        let m  = max (dp (pos +: config.(i).(1))) (dp (pos +: config.(i).(2))) in
        save cub.(i) pos (m + read mat pos)
      end
    in
    dp config.(i).(0) |> ignore;
  done;

  let rec run i j m =
    if i = row then m else
    if j = col then run (i+1) 0 m else
    let pos = (i,j) in
    let m' = for_ 0 4 0 (fun i c -> c + read cub.(i) pos) - 4 * read mat pos in
    run i (j+1) (max m m')
  in

  (* for i = 0 to 3 do print_matrix ("%d ") cub.(i) done; *)
  printf "%d\n" (run 0 0 0)