Polycarp has guessed three positive integers $$$a$$$, $$$b$$$ and $$$c$$$. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: $$$a+b$$$, $$$a+c$$$, $$$b+c$$$ and $$$a+b+c$$$.You have to guess three numbers $$$a$$$, $$$b$$$ and $$$c$$$ using given numbers. Print three guessed integers in any order.Pay attention that some given numbers $$$a$$$, $$$b$$$ and $$$c$$$ can be equal (it is also possible that $$$a=b=c$$$).

The only line of the input contains four positive integers $$$x_1, x_2, x_3, x_4$$$ ($$$2 \le x_i \le 10^9$$$) — numbers written on a board in random order. It is guaranteed that the answer exists for the given number $$$x_1, x_2, x_3, x_4$$$.

Print such positive integers $$$a$$$, $$$b$$$ and $$$c$$$ that four numbers written on a board are values $$$a+b$$$, $$$a+c$$$, $$$b+c$$$ and $$$a+b+c$$$ written in some order. Print $$$a$$$, $$$b$$$ and $$$c$$$ in any order. If there are several answers, you can print any. It is guaranteed that the answer exists.

let main () =
  let gr () = Scanf.scanf " %d" (fun i -> i) in
  let gs () = Scanf.scanf " %s" (fun i -> i) in

  let print_ans x y z s =
      Printf.printf "%d %d %d\n" (s - x) (s - y) (s - z)
  in
  let p = gr () in
  let r = gr() in
  let s = gr() in
  let t = gr() in
  if p+r+s == 2 * t then print_ans p r s t
  else if p + r + t == 2 * s then print_ans p r t s
  else if p + s + t == 2 * r then print_ans p s t r
  else print_ans r s t p

let _ = main();;

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

let f () =
  let b = Array.init 4 (fun x -> scan_int ()) in
  Array.sort compare b;
  b
;;

let _ =
  let arr = f () in
  Printf.printf "%d %d %d\n" (arr.(3) - arr.(0)) (arr.(3) - arr.(1)) (arr.(3) - arr.(2))
;;


As you know, lemmings like jumping. For the next spectacular group jump n lemmings gathered near a high rock with k comfortable ledges on it. The first ledge is situated at the height of h meters, the second one is at the height of 2h meters, and so on (the i-th ledge is at the height of i·h meters). The lemmings are going to jump at sunset, and there's not much time left.Each lemming is characterized by its climbing speed of vi meters per minute and its weight mi. This means that the i-th lemming can climb to the j-th ledge in  minutes.To make the jump beautiful, heavier lemmings should jump from higher ledges: if a lemming of weight mi jumps from ledge i, and a lemming of weight mj jumps from ledge j (for i < j), then the inequation mi ≤ mj should be fulfilled.Since there are n lemmings and only k ledges (k ≤ n), the k lemmings that will take part in the jump need to be chosen. The chosen lemmings should be distributed on the ledges from 1 to k, one lemming per ledge. The lemmings are to be arranged in the order of non-decreasing weight with the increasing height of the ledge. In addition, each lemming should have enough time to get to his ledge, that is, the time of his climb should not exceed t minutes. The lemmings climb to their ledges all at the same time and they do not interfere with each other.Find the way to arrange the lemmings' jump so that time t is minimized.

The first line contains space-separated integers n, k and h (1 ≤ k ≤ n ≤ 105, 1 ≤ h ≤ 104) — the total number of lemmings, the number of ledges and the distance between adjacent ledges. The second line contains n space-separated integers m1, m2, ..., mn (1 ≤ mi ≤ 109), where mi is the weight of i-th lemming. The third line contains n space-separated integers v1, v2, ..., vn (1 ≤ vi ≤ 109), where vi is the speed of i-th lemming.

Print k different numbers from 1 to n — the numbers of the lemmings who go to ledges at heights h, 2h, ..., kh, correspondingly, if the jump is organized in an optimal way. If there are multiple ways to select the lemmings, pick any of them.

NoteLet's consider the first sample case. The fifth lemming (speed 10) gets to the ledge at height 2 in  minutes; the second lemming (speed 2) gets to the ledge at height 4 in 2 minutes; the fourth lemming (speed 2) gets to the ledge at height 6 in 3 minutes. All lemmings manage to occupy their positions in 3 minutes.

let getnum =
  let l = 512000 in
  let buf = String.make l ' ' in
  let s = ref 0 in
  let pos = ref 0 in
  let getc () =
    if !pos >= !s then (
      let new_s = input stdin buf 0 l in
	(*if new_s = 0 then raise End_of_file;*)
	s := new_s;
	if new_s = 0 then (
	  buf.[0] <- '\000';
	  s := 1;
	);
	pos := 0;
    );
    let c = buf.[!pos] in
      incr pos;
      c
  in
  let aux () =
    let n = ref 0 in
    let k = ref 1 in
      if !s - !pos < 50 then (
	let c = ref (getc ()) in
	  while !c <= ' ' do
	    c := getc ()
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := getc ();
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := getc ()
	  done;
	  !n * !k
      ) else (
	let c = ref (buf.[!pos]) in
	  incr pos;
	  while !c <= ' ' do
	    c := buf.[!pos];
	    incr pos;
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := buf.[!pos];
	    incr pos;
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := buf.[!pos];
	    incr pos;
	  done;
	  !n * !k
      )
  in
    aux

let _ =
  let n = getnum () in
  let k = getnum () in
  let h = getnum () in
  let m = Array.make n 0 in
  let v = Array.make n 0 in
  let () =
    for i = 0 to n - 1 do
      let k = getnum () in
	m.(i) <- k
    done;
    for i = 0 to n - 1 do
      let k = getnum () in
	v.(i) <- k
    done;
  in
  let a = Array.init n (fun i -> (m.(i), v.(i), i)) in
  let () = Array.sort compare a in
  let res = Array.make (k + 1) 0 in
  let solve t =
    let j = ref 0 in
      try
	for i = 1 to k do
	  while !j < n && (let (_, v, _) = a.(!j) in
			     t *. float_of_int v <= float_of_int i) do
	    incr j
	  done;
	  if !j < n then (
	    let (_, _, ii) = a.(!j) in
	      res.(i) <- ii + 1;
	    incr j;
	  ) else raise Not_found
	done;
	true
      with
	| Not_found ->
	    false
  in
  let l = ref 0.0 in
  let r = ref (float_of_int (k + 1)) in
  let eps = float_of_int k *. 10e-16 in
    for i = 1 to 64 do
      let m = (!l +. !r) /. 2.0 in
	if solve m
	then r := m
	else l := m
    done;
    ignore (solve !r);
    (*Printf.printf "asd %f\n" !r;*)
    for i = 1 to k do
      Printf.printf "%d " res.(i);
    done;
    Printf.printf "\n"

let getnum =
  let l = 512000 in
  let buf = String.make l ' ' in
  let s = ref 0 in
  let pos = ref 0 in
  let getc () =
    if !pos >= !s then (
      let new_s = input stdin buf 0 l in
	(*if new_s = 0 then raise End_of_file;*)
	s := new_s;
	if new_s = 0 then (
	  buf.[0] <- '\000';
	  s := 1;
	);
	pos := 0;
    );
    let c = buf.[!pos] in
      incr pos;
      c
  in
  let aux () =
    let n = ref 0 in
    let k = ref 1 in
      if !s - !pos < 50 then (
	let c = ref (getc ()) in
	  while !c <= ' ' do
	    c := getc ()
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := getc ();
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := getc ()
	  done;
	  !n * !k
      ) else (
	let c = ref (buf.[!pos]) in
	  incr pos;
	  while !c <= ' ' do
	    c := buf.[!pos];
	    incr pos;
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := buf.[!pos];
	    incr pos;
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := buf.[!pos];
	    incr pos;
	  done;
	  !n * !k
      )
  in
    aux

let _ =
  let n = getnum () in
  let k = getnum () in
  let h = getnum () in
  let m = Array.make n 0 in
  let v = Array.make n 0 in
  let () =
    for i = 0 to n - 1 do
      let k = getnum () in
	m.(i) <- k
    done;
    for i = 0 to n - 1 do
      let k = getnum () in
	v.(i) <- k
    done;
  in
  let a = Array.init n (fun i -> (m.(i), v.(i), i)) in
  let () = Array.sort compare a in
  let res = Array.make (k + 1) 0 in
  let solve t =
    let j = ref 0 in
      try
	for i = 1 to k do
	  while !j < n && (let (_, v, _) = a.(!j) in
			     t *. float_of_int v <= float_of_int i) do
	    incr j
	  done;
	  if !j < n then (
	    let (_, _, ii) = a.(!j) in
	      res.(i) <- ii + 1;
	    incr j;
	  ) else raise Not_found
	done;
	true
      with
	| Not_found ->
	    false
  in
  let l = ref 0.0 in
  let r = ref (float_of_int (k + 1)) in
  let eps = 10e-14 in
    while !r -. !l > eps do
      let m = (!l +. !r) /. 2.0 in
	if solve m
	then r := m
	else l := m
    done;
    ignore (solve !r);
    (*Printf.printf "asd %f\n" !r;*)
    for i = 1 to k do
      Printf.printf "%d " res.(i);
    done;
    Printf.printf "\n"

let getnum =
  let l = 512000 in
  let buf = String.make l ' ' in
  let s = ref 0 in
  let pos = ref 0 in
  let getc () =
    if !pos >= !s then (
      let new_s = input stdin buf 0 l in
	(*if new_s = 0 then raise End_of_file;*)
	s := new_s;
	if new_s = 0 then (
	  buf.[0] <- '\000';
	  s := 1;
	);
	pos := 0;
    );
    let c = buf.[!pos] in
      incr pos;
      c
  in
  let aux () =
    let n = ref 0 in
    let k = ref 1 in
      if !s - !pos < 50 then (
	let c = ref (getc ()) in
	  while !c <= ' ' do
	    c := getc ()
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := getc ();
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := getc ()
	  done;
	  !n * !k
      ) else (
	let c = ref (buf.[!pos]) in
	  incr pos;
	  while !c <= ' ' do
	    c := buf.[!pos];
	    incr pos;
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := buf.[!pos];
	    incr pos;
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := buf.[!pos];
	    incr pos;
	  done;
	  !n * !k
      )
  in
    aux

let _ =
  let n = getnum () in
  let k = getnum () in
  let h = getnum () in
  let m = Array.make n 0 in
  let v = Array.make n 0 in
  let () =
    for i = 0 to n - 1 do
      let k = getnum () in
	m.(i) <- k
    done;
    for i = 0 to n - 1 do
      let k = getnum () in
	v.(i) <- k
    done;
  in
  let a = Array.init n (fun i -> (m.(i), v.(i), i)) in
  let () = Array.sort compare a in
  let res = Array.make (k + 1) 0 in
  let solve t =
    let j = ref 0 in
      try
	for i = 1 to k do
	  while !j < n && (let (_, v, _) = a.(!j) in
			     t *. float_of_int v <= float_of_int i) do
	    incr j
	  done;
	  if !j < n then (
	    let (_, _, ii) = a.(!j) in
	      res.(i) <- ii + 1;
	    incr j;
	  ) else raise Not_found
	done;
	true
      with
	| Not_found ->
	    false
  in
  let l = ref 0.0 in
  let r = ref (float_of_int (k + 1)) in
  let eps = 10e-15 in
    while !r -. !l > eps do
      let m = (!l +. !r) /. 2.0 in
	if solve m
	then r := m
	else l := m
    done;
    ignore (solve !r);
    (*Printf.printf "asd %f\n" !r;*)
    for i = 1 to k do
      Printf.printf "%d " res.(i);
    done;
    Printf.printf "\n"

let getnum =
  let l = 512000 in
  let buf = String.make l ' ' in
  let s = ref 0 in
  let pos = ref 0 in
  let getc () =
    if !pos >= !s then (
      let new_s = input stdin buf 0 l in
	(*if new_s = 0 then raise End_of_file;*)
	s := new_s;
	if new_s = 0 then (
	  buf.[0] <- '\000';
	  s := 1;
	);
	pos := 0;
    );
    let c = buf.[!pos] in
      incr pos;
      c
  in
  let aux () =
    let n = ref 0 in
    let k = ref 1 in
      if !s - !pos < 50 then (
	let c = ref (getc ()) in
	  while !c <= ' ' do
	    c := getc ()
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := getc ();
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := getc ()
	  done;
	  !n * !k
      ) else (
	let c = ref (buf.[!pos]) in
	  incr pos;
	  while !c <= ' ' do
	    c := buf.[!pos];
	    incr pos;
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := buf.[!pos];
	    incr pos;
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := buf.[!pos];
	    incr pos;
	  done;
	  !n * !k
      )
  in
    aux

let _ =
  let n = getnum () in
  let k = getnum () in
  let h = getnum () in
  let m = Array.make n 0 in
  let v = Array.make n 0 in
  let () =
    for i = 0 to n - 1 do
      let k = getnum () in
	m.(i) <- k
    done;
    for i = 0 to n - 1 do
      let k = getnum () in
	v.(i) <- k
    done;
  in
  let a = Array.init n (fun i -> (m.(i), v.(i), i)) in
  let () = Array.sort compare a in
  let res = Array.make (k + 1) 0 in
  let solve t =
    let j = ref 0 in
      try
	for i = 1 to k do
	  while !j < n && (let (_, v, _) = a.(!j) in
			     t *. float_of_int v <= float_of_int i) do
	    incr j
	  done;
	  if !j < n then (
	    let (_, _, ii) = a.(!j) in
	      res.(i) <- ii + 1;
	    incr j;
	  ) else raise Not_found
	done;
	true
      with
	| Not_found ->
	    false
  in
  let l = ref 0.0 in
  let r = ref (float_of_int (k + 1)) in
  let eps = 10e-10 in
    while !r -. !l > eps do
      let m = (!l +. !r) /. 2.0 in
	if solve m
	then r := m
	else l := m
    done;
    ignore (solve !r);
    (*Printf.printf "asd %f\n" !r;*)
    for i = 1 to k do
      Printf.printf "%d " res.(i);
    done;
    Printf.printf "\n"

let getnum =
  let l = 512000 in
  let buf = String.make l ' ' in
  let s = ref 0 in
  let pos = ref 0 in
  let getc () =
    if !pos >= !s then (
      let new_s = input stdin buf 0 l in
	(*if new_s = 0 then raise End_of_file;*)
	s := new_s;
	if new_s = 0 then (
	  buf.[0] <- '\000';
	  s := 1;
	);
	pos := 0;
    );
    let c = buf.[!pos] in
      incr pos;
      c
  in
  let aux () =
    let n = ref 0 in
    let k = ref 1 in
      if !s - !pos < 50 then (
	let c = ref (getc ()) in
	  while !c <= ' ' do
	    c := getc ()
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := getc ();
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := getc ()
	  done;
	  !n * !k
      ) else (
	let c = ref (buf.[!pos]) in
	  incr pos;
	  while !c <= ' ' do
	    c := buf.[!pos];
	    incr pos;
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := buf.[!pos];
	    incr pos;
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := buf.[!pos];
	    incr pos;
	  done;
	  !n * !k
      )
  in
    aux

let _ =
  let n = getnum () in
  let k = getnum () in
  let h = getnum () in
  let m = Array.make n 0 in
  let v = Array.make n 0 in
  let () =
    for i = 0 to n - 1 do
      let k = getnum () in
	m.(i) <- k
    done;
    for i = 0 to n - 1 do
      let k = getnum () in
	v.(i) <- k
    done;
  in
  let a = Array.init n (fun i -> (m.(i), v.(i), i)) in
  let () = Array.sort compare a in
  let res = Array.make (k + 1) 0 in
  let solve t =
    let j = ref 0 in
      try
	for i = 1 to k do
	  while !j < n && (let (_, v, _) = a.(!j) in
			     t *. float_of_int v <= float_of_int i) do
	    incr j
	  done;
	  if !j < n then (
	    let (_, _, ii) = a.(!j) in
	      res.(i) <- ii + 1;
	    incr j;
	  ) else raise Not_found
	done;
	true
      with
	| Not_found ->
	    false
  in
  let l = ref 0.0 in
  let r = ref (float_of_int (k + 1)) in
  let eps = float_of_int k *. 10e-16 in
    while !r -. !l > eps do
      let m = (!l +. !r) /. 2.0 in
	if solve m
	then r := m
	else l := m
    done;
    ignore (solve !r);
    (*Printf.printf "asd %f\n" !r;*)
    for i = 1 to k do
      Printf.printf "%d " res.(i);
    done;
    Printf.printf "\n"

let getnum =
  let l = 512000 in
  let buf = String.make l ' ' in
  let s = ref 0 in
  let pos = ref 0 in
  let getc () =
    if !pos >= !s then (
      let new_s = input stdin buf 0 l in
	(*if new_s = 0 then raise End_of_file;*)
	s := new_s;
	if new_s = 0 then (
	  buf.[0] <- '\000';
	  s := 1;
	);
	pos := 0;
    );
    let c = buf.[!pos] in
      incr pos;
      c
  in
  let aux () =
    let n = ref 0 in
    let k = ref 1 in
      if !s - !pos < 50 then (
	let c = ref (getc ()) in
	  while !c <= ' ' do
	    c := getc ()
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := getc ();
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := getc ()
	  done;
	  !n * !k
      ) else (
	let c = ref (buf.[!pos]) in
	  incr pos;
	  while !c <= ' ' do
	    c := buf.[!pos];
	    incr pos;
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := buf.[!pos];
	    incr pos;
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := buf.[!pos];
	    incr pos;
	  done;
	  !n * !k
      )
  in
    aux

let _ =
  let n = getnum () in
  let k = getnum () in
  let h = getnum () in
  let m = Array.make n 0 in
  let v = Array.make n 0 in
  let () =
    for i = 0 to n - 1 do
      let k = getnum () in
	m.(i) <- k
    done;
    for i = 0 to n - 1 do
      let k = getnum () in
	v.(i) <- k
    done;
  in
  let a = Array.init n (fun i -> (m.(i), v.(i), i)) in
  let () = Array.sort compare a in
  let res = Array.make (k + 1) 0 in
  let solve t =
    let j = ref 0 in
      try
	for i = 1 to k do
	  while !j < n && (let (_, v, _) = a.(!j) in
			     t *. float_of_int v <= float_of_int i) do
	    incr j
	  done;
	  if !j < n then (
	    let (_, _, ii) = a.(!j) in
	      res.(i) <- ii + 1;
	    incr j;
	  ) else raise Not_found
	done;
	true
      with
	| Not_found ->
	    false
  in
  let l = ref 0.0 in
  let r = ref (float_of_int (k + 1)) in
  let eps = float_of_int k *. 10e-9 in
    while !r -. !l > eps do
      let m = (!l +. !r) /. 2.0 in
	if solve m
	then r := m
	else l := m
    done;
    ignore (solve !r);
    (*Printf.printf "asd %f\n" !r;*)
    for i = 1 to k do
      Printf.printf "%d " res.(i);
    done;
    Printf.printf "\n"

let getnum =
  let l = 512000 in
  let buf = String.make l ' ' in
  let s = ref 0 in
  let pos = ref 0 in
  let getc () =
    if !pos >= !s then (
      let new_s = input stdin buf 0 l in
	(*if new_s = 0 then raise End_of_file;*)
	s := new_s;
	if new_s = 0 then (
	  buf.[0] <- '\000';
	  s := 1;
	);
	pos := 0;
    );
    let c = buf.[!pos] in
      incr pos;
      c
  in
  let aux () =
    let n = ref 0 in
    let k = ref 1 in
      if !s - !pos < 50 then (
	let c = ref (getc ()) in
	  while !c <= ' ' do
	    c := getc ()
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := getc ();
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := getc ()
	  done;
	  !n * !k
      ) else (
	let c = ref (buf.[!pos]) in
	  incr pos;
	  while !c <= ' ' do
	    c := buf.[!pos];
	    incr pos;
	  done;
	  if !c = '-' then (
	    k := -1;
	    c := buf.[!pos];
	    incr pos;
	  );
	  while !c > ' ' do
	    n := !n * 10 + (Char.code !c - Char.code '0');
	    c := buf.[!pos];
	    incr pos;
	  done;
	  !n * !k
      )
  in
    aux

let _ =
  let n = getnum () in
  let k = getnum () in
  let h = getnum () in
  let m = Array.make n 0 in
  let v = Array.make n 0 in
  let () =
    for i = 0 to n - 1 do
      let k = getnum () in
	m.(i) <- k
    done;
    for i = 0 to n - 1 do
      let k = getnum () in
	v.(i) <- k
    done;
  in
  let a = Array.init n (fun i -> (m.(i), v.(i), i)) in
  let () = Array.sort compare a in
  let res = Array.make (k + 1) 0 in
  let solve t =
    let j = ref 0 in
      try
	for i = 1 to k do
	  while !j < n && (let (_, v, _) = a.(!j) in
			     t *. float_of_int v <= float_of_int i) do
	    incr j
	  done;
	  if !j < n then (
	    let (_, _, ii) = a.(!j) in
	      res.(i) <- ii + 1;
	    incr j;
	  ) else raise Not_found
	done;
	true
      with
	| Not_found ->
	    false
  in
  let l = ref 0.0 in
  let r = ref (float_of_int (k + 1)) in
  let eps = float_of_int k *. 10e-7 in
    while !r -. !l > eps do
      let m = (!l +. !r) /. 2.0 in
	if solve m
	then r := m
	else l := m
    done;
    ignore (solve !r);
    (*Printf.printf "asd %f\n" !r;*)
    for i = 1 to k do
      Printf.printf "%d " res.(i);
    done;
    Printf.printf "\n"


In Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from right to left between adjacent tiles in a row, and jump over a tile. More formally, if you are standing on the tile number i (i < n - 1), you can reach the tiles number i + 1 or the tile number i + 2 from it (if you stand on the tile number n - 1, you can only reach tile number n). We can assume that all the opposition movements occur instantaneously.In order to thwart an opposition rally, the Berland bloody regime organized the rain. The tiles on the boulevard are of poor quality and they are rapidly destroyed in the rain. We know that the i-th tile is destroyed after ai days of rain (on day ai tile isn't destroyed yet, and on day ai + 1 it is already destroyed). Of course, no one is allowed to walk on the destroyed tiles! So the walk of the opposition is considered thwarted, if either the tile number 1 is broken, or the tile number n is broken, or it is impossible to reach the tile number n from the tile number 1 if we can walk on undestroyed tiles.The opposition wants to gather more supporters for their walk. Therefore, the more time they have to pack, the better. Help the opposition to calculate how much time they still have and tell us for how many days the walk from the tile number 1 to the tile number n will be possible.

The first line contains integer n (1 ≤ n ≤ 103) — the boulevard's length in tiles. The second line contains n space-separated integers ai — the number of days after which the i-th tile gets destroyed (1 ≤ ai ≤ 103).

Print a single number — the sought number of days.

NoteIn the first sample the second tile gets destroyed after day three, and the only path left is 1 → 3 → 4. After day five there is a two-tile gap between the first and the last tile, you can't jump over it.In the second sample path 1 → 3 → 5 is available up to day five, inclusive. On day six the last tile is destroyed and the walk is thwarted.

let ni () = Scanf.scanf " %d" (fun x -> x) in
let n = ni () in
let a = Array.init n (fun _ -> ni ()) in
let ans = ref (min a.(0) a.(n - 1)) in
for i = 2 to n - 1 do
  ans := min !ans (max a.(i - 1) a.(i))
done;
print_int !ans;;


New Year is coming, and Jaehyun decided to read many books during 2015, unlike this year. He has n books numbered by integers from 1 to n. The weight of the i-th (1 ≤ i ≤ n) book is wi.As Jaehyun's house is not large enough to have a bookshelf, he keeps the n books by stacking them vertically. When he wants to read a certain book x, he follows the steps described below.  He lifts all the books above book x.  He pushes book x out of the stack.  He puts down the lifted books without changing their order.  After reading book x, he puts book x on the top of the stack.  He decided to read books for m days. In the j-th (1 ≤ j ≤ m) day, he will read the book that is numbered with integer bj (1 ≤ bj ≤ n). To read the book, he has to use the process described in the paragraph above. It is possible that he decides to re-read the same book several times.After making this plan, he realized that the total weight of books he should lift during m days would be too heavy. So, he decided to change the order of the stacked books before the New Year comes, and minimize the total weight. You may assume that books can be stacked in any possible order. Note that book that he is going to read on certain step isn't considered as lifted on that step. Can you help him?

The first line contains two space-separated integers n (2 ≤ n ≤ 500) and m (1 ≤ m ≤ 1000) — the number of books, and the number of days for which Jaehyun would read books. The second line contains n space-separated integers w1, w2, ..., wn (1 ≤ wi ≤ 100) — the weight of each book. The third line contains m space separated integers b1, b2, ..., bm (1 ≤ bj ≤ n) — the order of books that he would read. Note that he can read the same book more than once.

Print the minimum total weight of books he should lift, which can be achieved by rearranging the order of stacked books.

NoteHere's a picture depicting the example. Each vertical column presents the stacked books.

type 'a el = {
  v : 'a;
  mutable next : 'a el option;
  mutable prev : 'a el option;
}

let () = Scanf.scanf "%d %d\n" (fun n m ->
  (* book weights *)
  let w = Array.init n (fun _ -> Scanf.scanf "%d%_c" (fun x -> x)) in
  (* reading order *)
  let b = Array.init m (fun _ -> Scanf.scanf "%d%_c" (fun x -> x - 1)) in
  (* seen array *)
  let seen = Array.make n false in
  (* head of pile *)
  let p = { v = b.(0); next = None; prev = None } in
  let hd = ref p in
  (* tail of pile *)
  let tl = ref p in
  seen.(b.(0)) <- true;

  let add i =
    let el = { v = i; next = None; prev = Some !tl } in
    !tl.next <- Some el;
    tl := el
  in

  (* construct the pile *)
  Array.iter (fun b ->
    if not seen.(b) then begin
      add b;
      seen.(b) <- true
    end
  ) b;
  let c = Array.fold_left (fun acc b ->
    let rec part a h =
      if h.v = b then (a, h)
      else match h.next with
      | None -> failwith "No more list!"
      | Some n -> part (a + w.(h.v)) n
    in
    let (cost, h) = part 0 !hd in
    let () = match h.prev with
    | None -> () (* already at head *)
    | Some p -> begin
      p.next <- h.next;

      let () = match h.next with
      | None -> ()
      | Some n -> n.prev <- Some p
      in
      h.next <- Some !hd;
      h.prev <- None;
      !hd.prev <- Some h;
      hd := h
    end
    in
    acc + cost
  ) 0 b in
  Printf.printf "%d\n" c
)

open Printf
open Scanf

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

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

  let w = Array.init n (fun _ -> read_int()) in
  let b = Array.init m (fun _ -> read_int() - 1) in

  let indices = Array.make n 0 in
  let locator = Array.make n 0 in

  let h = Hashtbl.create 10 in

  let place = ref 0 in

  for j=0 to m-1 do
    if not (Hashtbl.mem h b.(j)) then (
      Hashtbl.replace h b.(j) true;
      indices.(!place) <- b.(j);
      locator.(b.(j)) <- !place;
      place := !place + 1;
    )
  done;

  (* some books may never be read and thus not be in this data structure.
     I don't think this matters. They'll never be accessed below. *)

  let swap j =
    let (a,b) = (indices.(j), indices.(j+1)) in
    locator.(a) <- locator.(a) + 1;
    locator.(b) <- locator.(b) - 1;
    indices.(j) <- b;
    indices.(j+1) <- a;
  in

  let read_book k =
    let i = locator.(k) in
    let weight = ref 0 in
    for j=i-1 downto 0 do
      (* swap the books at positions j+1 and j *)
      weight := !weight + w.(indices.(j));
      swap j;
    done;
    !weight
  in

  let answer = sum 0 (m-1) (fun j -> read_book b.(j)) in

  printf "%d\n" answer


There were n groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team.

The first line contains single integer n (2 ≤ n ≤ 2·105) — the number of groups. The second line contains a sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 2), where ai is the number of people in group i.

Print the maximum number of teams of three people the coach can form.

NoteIn the first example the coach can form one team. For example, he can take students from the first, second and fourth groups.In the second example he can't make a single team.In the third example the coach can form three teams. For example, he can do this in the following way:  The first group (of two people) and the seventh group (of one person),  The second group (of two people) and the sixth group (of one person),  The third group (of two people) and the fourth group (of one person).

let input () =
  let l = ref []
  in let getNumber () = Scanf.bscanf Scanf.Scanning.stdin " %d" (fun x -> x)
  in let n = getNumber ()
  in begin
    for i = 0 to n - 1 do
      l := (getNumber ()) :: !l
    done;
    !l
  end;;

let divideList l =
  let l = List.sort compare l
  in let l1 = List.filter (fun x -> x = 1) l
  in let l2 = List.filter (fun x -> x = 2) l
  in (l1, l2)

let rec firstStep a l1 l2 =
  match l1, l2 with
  | x1 :: t1, x2 :: t2 -> firstStep (a + 1) t1 t2
  | _ -> (a, l1)

let rec secondStep a = function
  | x :: y :: z :: t -> secondStep (a + 1) t
  | _ -> a

let teams (l1, l2) =
  let n, newL1 = firstStep 0 l1 l2
  in secondStep n newL1

let altMethod l =
  let rec int a1 a2 = function
    | 1 :: t -> int (a1 + 1) a2 t
    | 2 :: t -> int a1 (a2 + 1) t
    | _ -> (a1, a2)
  in let n1, n2 = int 0 0 l
  in if n1 > n2 then
    n2 + (n1 - n2) / 3
  else
    n1

let main () =
  let l = input ()
  in let n = altMethod l
  in Printf.printf "%d" n
;;

main ();;

let input () =
  let l = ref []
  in let getNumber () = Scanf.bscanf Scanf.Scanning.stdin " %d" (fun x -> x)
  in let n = getNumber ()
  in begin
    for i = 0 to n - 1 do
      l := (getNumber ()) :: !l
    done;
    !l
  end;;

let divideList l =
  let l = List.sort compare l
  in let l1 = List.filter (fun x -> x = 1) l
  in let l2 = List.filter (fun x -> x = 2) l
  in (l1, l2)

let rec firstStep a l1 l2 =
  match l1, l2 with
  | x1 :: t1, x2 :: t2 -> firstStep (a + 1) t1 t2
  | _ -> (a, l1)

let rec secondStep a = function
  | x :: y :: z :: t -> secondStep (a + 1) t
  | _ -> a

let teams (l1, l2) =
  let n, newL1 = firstStep 0 l1 l2
  in secondStep n newL1

let main () =
  let l = input ()
  in let n = teams (divideList l)
  in Printf.printf "%d" n
;;

main ();;

open Printf
open Scanf

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

let () =
  let n = read_int () in

  let rec loop n1 n2 i = if i=n then (n1,n2) else
      if read_int() = 1 then loop (n1+1) n2 (i+1)
      else loop n1 (n2+1) (i+1)
  in

  let (n1, n2) = loop 0 0 0 in

  if n2 >= n1 then printf "%d\n" n1
  else printf "%d\n" (n2 + (n1-n2)/3)


Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan considers the distance between watchmen i and j to be |xi - xj| + |yi - yj|. Daniel, as an ordinary person, calculates the distance using the formula .The success of the operation relies on the number of pairs (i, j) (1 ≤ i < j ≤ n), such that the distance between watchman i and watchmen j calculated by Doctor Manhattan is equal to the distance between them calculated by Daniel. You were asked to compute the number of such pairs.

The first line of the input contains the single integer n (1 ≤ n ≤ 200 000) — the number of watchmen. Each of the following n lines contains two integers xi and yi (|xi|, |yi| ≤ 109). Some positions may coincide.

Print the number of pairs of watchmen such that the distance between them calculated by Doctor Manhattan is equal to the distance calculated by Daniel.

NoteIn the first sample, the distance between watchman 1 and watchman 2 is equal to |1 - 7| + |1 - 5| = 10 for Doctor Manhattan and  for Daniel. For pairs (1, 1), (1, 5) and (7, 5), (1, 5) Doctor Manhattan and Daniel will calculate the same distances.

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 long x = Int64.of_int x

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

let () =
  let n = read_int() in

  let increment h t =
  let c = try Hashtbl.find h t with Not_found -> 0 in
    Hashtbl.replace h t (c+1)
  in

  let xtable = Hashtbl.create 10 in
  let ytable = Hashtbl.create 10 in
  let pairtable = Hashtbl.create 10 in

  for i=1 to n do
    let (x,y) = read_pair() in
    increment xtable x;
    increment ytable y;
    increment pairtable (x,y)
  done;

  let eval_table h =
    Hashtbl.fold (fun _ v ac ->
      let v = long v in
      ac ++ ((v ** (v -- 1L))//2L)
    ) h 0L
  in

  let eval_pairtable h =
    Hashtbl.fold (fun _ v ac ->
      let v = long v in
      ac ++ ((v ** (v -- 1L))//2L)
    ) h 0L
  in

  let answer =
    (eval_table xtable)
    ++ (eval_table ytable)
    -- (eval_pairtable pairtable)
  in

  printf "%Ld\n" answer


The string $$$s$$$ is given, the string length is odd number. The string consists of lowercase letters of the Latin alphabet.As long as the string length is greater than $$$1$$$, the following operation can be performed on it: select any two adjacent letters in the string $$$s$$$ and delete them from the string. For example, from the string "lemma" in one operation, you can get any of the four strings: "mma", "lma", "lea" or "lem" In particular, in one operation, the length of the string reduces by $$$2$$$.Formally, let the string $$$s$$$ have the form $$$s=s_1s_2 \dots s_n$$$ ($$$n>1$$$). During one operation, you choose an arbitrary index $$$i$$$ ($$$1 \le i < n$$$) and replace $$$s=s_1s_2 \dots s_{i-1}s_{i+2} \dots s_n$$$.For the given string $$$s$$$ and the letter $$$c$$$, determine whether it is possible to make such a sequence of operations that in the end the equality $$$s=c$$$ will be true? In other words, is there such a sequence of operations that the process will end with a string of length $$$1$$$, which consists of the letter $$$c$$$?

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of input test cases. The descriptions of the $$$t$$$ cases follow. Each test case is represented by two lines:   string $$$s$$$, which has an odd length from $$$1$$$ to $$$49$$$ inclusive and consists of lowercase letters of the Latin alphabet;  is a string containing one letter $$$c$$$, where $$$c$$$ is a lowercase letter of the Latin alphabet.

For each test case in a separate line output:  YES, if the string $$$s$$$ can be converted so that $$$s=c$$$ is true; NO otherwise.  You can output YES and NO in any case (for example, the strings yEs, yes, Yes and YES will be recognized as a positive response).

5

abcde

c

abcde

b

x

y

aaaaaaaaaaaaaaa

a

contest

t

NoteIn the first test case, $$$s$$$="abcde". You need to get $$$s$$$="c". For the first operation, delete the first two letters, we get $$$s$$$="cde". In the second operation, we delete the last two letters, so we get the expected value of $$$s$$$="c".In the third test case, $$$s$$$="x", it is required to get $$$s$$$="y". Obviously, this cannot be done.

let n = int_of_string(input_line stdin) in
for i = 0 to n-1 do
  let line = input_line stdin in
  let chara = input_line stdin in
  let toto = ref false in
  if String.length line mod 2 = 1 then (
    for j = 0 to String.length line -1 do
      if chara = (String.make 1 line.[j]) && j mod 2 = 0 then (toto:=true)
    done ; if !toto then print_endline "YES" else print_endline "NO")
  else (print_endline "NO")
done ;;


A new cottage village called «Flatville» is being built in Flatland. By now they have already built in «Flatville» n square houses with the centres on the Оx-axis. The houses' sides are parallel to the coordinate axes. It's known that no two houses overlap, but they can touch each other.The architect bureau, where Peter works, was commissioned to build a new house in «Flatville». The customer wants his future house to be on the Оx-axis, to be square in shape, have a side t, and touch at least one of the already built houses. For sure, its sides should be parallel to the coordinate axes, its centre should be on the Ox-axis and it shouldn't overlap any of the houses in the village.Peter was given a list of all the houses in «Flatville». Would you help him find the amount of possible positions of the new house?

The first line of the input data contains numbers n and t (1 ≤ n, t ≤ 1000). Then there follow n lines, each of them contains two space-separated integer numbers: xi ai, where xi — x-coordinate of the centre of the i-th house, and ai — length of its side ( - 1000 ≤ xi ≤ 1000, 1 ≤ ai ≤ 1000).

Output the amount of possible positions of the new house.

NoteIt is possible for the x-coordinate of the new house to have non-integer value.

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

let () =
  let n = read_int 0 in
  let t = read_int 0 in
  let rec go acc i =
    if i >= n then
      acc
    else
      let x = read_int 0 in
      let y = read_int 0 in
      go ((x*2-y)::(x*2+y)::acc) (i+1)
  in
  let rec f s = function
    | [] | [_] -> s
    | x::y::xs ->
      f (s + compare (y-x) (2*t) + 1) xs
  in
  let tt = go [] 0 |> List.sort compare |> List.tl in
  tt |> f 2 |> Printf.printf "%d\n"


A new entertainment has appeared in Buryatia — a mathematical circus! The magician shows two numbers to the audience — $$$n$$$ and $$$k$$$, where $$$n$$$ is even. Next, he takes all the integers from $$$1$$$ to $$$n$$$, and splits them all into pairs $$$(a, b)$$$ (each integer must be in exactly one pair) so that for each pair the integer $$$(a + k) \cdot b$$$ is divisible by $$$4$$$ (note that the order of the numbers in the pair matters), or reports that, unfortunately for viewers, such a split is impossible.Burenka really likes such performances, so she asked her friend Tonya to be a magician, and also gave him the numbers $$$n$$$ and $$$k$$$.Tonya is a wolf, and as you know, wolves do not perform in the circus, even in a mathematical one. Therefore, he asks you to help him. Let him know if a suitable splitting into pairs is possible, and if possible, then tell it.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The following is a description of the input data sets. The single line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \leq n \leq 2 \cdot 10^5$$$, $$$0 \leq k \leq 10^9$$$, $$$n$$$ is even) — the number of integers and the number being added $$$k$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, first output the string "YES" if there is a split into pairs, and "NO" if there is none. If there is a split, then in the following $$$\frac{n}{2}$$$ lines output pairs of the split, in each line print $$$2$$$ numbers — first the integer $$$a$$$, then the integer $$$b$$$.

NoteIn the first test case, splitting into pairs $$$(1, 2)$$$ and $$$(3, 4)$$$ is suitable, same as splitting into $$$(1, 4)$$$ and $$$(3, 2)$$$.In the second test case, $$$(1 + 0) \cdot 2 = 1 \cdot (2 + 0) = 2$$$ is not divisible by $$$4$$$, so there is no partition.

(*
Consider the following:

i) kmod4=0:
 means bmod4=0
or anod4=0
or amod4=bmod4=2
-> (4,),(8,),...
-> (,4),(,8),...
-> (2,6),(10,14),...
-> (1,4),(3,8),(5,12),...
-> not possible

ii) kmod4=1
amod4=3 or bmod4=0
or (amod4=1 and bmod4=2)
->(1,2),(5,6),...
->(3,),(7,),...
->(,4),(8,),...
->(1,2),(3,4),(5,6),...
-> possible when n is even

iii) kmod4=2
amod4=2 or bmod4=0
or (amod4=0 and bmod4=2)
->(4,2),(8,6),(12,10),...
->(2,1),(6,5),(10,9)...
->(3,4),(7,8),(11,12),...
->(2,1),(3,4),(6,5),...
-> possible when n is even

iv) kmod4=3
amod4=1 or bmod4=0
or (amod4=3 and bmod4=2)
->(1,),(5,),(9,)...
->(,4),(,8),...
->(3,2),(7,6),...
->(1,2),(5,6),...
->(3,4),(7,8)...
->(1,2),(3,4),(5,6),....
-> possible when n is even
*)

let read_int () = Scanf.scanf " %d" (fun x->x);;
let read_long () = Scanf.scanf " %Ld" (fun l->l);;
let run_case = function
| () ->
     let n = read_long () in
     let k = read_long () in
     let remk = Int64.sub k (Int64.mul 4L (Int64.div k 4L)) in
     if (remk=0L) then Printf.printf "NO\n"
     else if (remk=2L) then begin
         Printf.printf "YES\n";
         let rec pairPrint = function
         | x, r ->
              if (x>n) then ()
              else if (r=false) then begin
                  Printf.printf "%Ld %Ld\n" x (Int64.succ x);
                  pairPrint ((Int64.add x 2L), true)
              end
              else begin
                  Printf.printf "%Ld %Ld\n" (Int64.succ x) x;
                  pairPrint ((Int64.add x 2L), false)
              end
          in pairPrint (1L,true)
     end
     else begin
         Printf.printf "YES\n";
         let rec pairPrint =function
         | x ->
              if (x>n) then ()
              else begin
                  Printf.printf "%Ld %Ld\n" x (Int64.succ x);
                  pairPrint (Int64.add x 2L)
              end
          in pairPrint 1L
     end
;;

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

let t = read_int () in iter_cases t;;

let pf = Printf.printf
let sf = Scanf.scanf
let read_int () = sf " %d" (fun x -> x)

let () =
  let t = read_int () in
  for _ = 1 to t do
    let n = read_int () in
    let k' = read_int () in
    if (k' mod 4 = 0) then print_endline "NO"
    else begin
      print_endline "YES";
      let k = k' mod 4 in
      for i = 0 to n / 2 - 1 do
        let x = 2 * i + 1 in
        let y = 2 * i + 2 in
        if ((x + k) * y mod 4 = 0) then
          pf "%d %d\n" x y
        else
          pf "%d %d\n" y x
      done;
    end;
  done;


Piet is one of the most known visual esoteric programming languages. The programs in Piet are constructed from colorful blocks of pixels and interpreted using pretty complicated rules. In this problem we will use a subset of Piet language with simplified rules.The program will be a rectangular image consisting of colored and black pixels. The color of each pixel will be given by an integer number between 0 and 9, inclusive, with 0 denoting black. A block of pixels is defined as a rectangle of pixels of the same color (not black). It is guaranteed that all connected groups of colored pixels of the same color will form rectangular blocks. Groups of black pixels can form arbitrary shapes.The program is interpreted using movement of instruction pointer (IP) which consists of three parts: current block pointer (BP); note that there is no concept of current pixel within the block; direction pointer (DP) which can point left, right, up or down; block chooser (CP) which can point to the left or to the right from the direction given by DP; in absolute values CP can differ from DP by 90 degrees counterclockwise or clockwise, respectively.Initially BP points to the block which contains the top-left corner of the program, DP points to the right, and CP points to the left (see the orange square on the image below).One step of program interpretation changes the state of IP in a following way. The interpreter finds the furthest edge of the current color block in the direction of the DP. From all pixels that form this edge, the interpreter selects the furthest one in the direction of CP. After this, BP attempts to move from this pixel into the next one in the direction of DP. If the next pixel belongs to a colored block, this block becomes the current one, and two other parts of IP stay the same. It the next pixel is black or outside of the program, BP stays the same but two other parts of IP change. If CP was pointing to the left, now it points to the right, and DP stays the same. If CP was pointing to the right, now it points to the left, and DP is rotated 90 degrees clockwise.This way BP will never point to a black block (it is guaranteed that top-left pixel of the program will not be black).You are given a Piet program. You have to figure out which block of the program will be current after n steps.

The first line of the input contains two integer numbers m (1 ≤ m ≤ 50) and n (1 ≤ n ≤ 5·107). Next m lines contain the rows of the program. All the lines have the same length between 1 and 50 pixels, and consist of characters 0-9. The first character of the first line will not be equal to 0.

Output the color of the block which will be current after n steps of program interpretation.

NoteIn the first example IP changes in the following way. After step 1 block 2 becomes current one and stays it after two more steps. After step 4 BP moves to block 3, after step 7 — to block 4, and finally after step 10 BP returns to block 1.  The sequence of states of IP is shown on the image: the arrows are traversed clockwise, the main arrow shows direction of DP, the side one — the direction of CP.

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

let di = [|0; -1; 0; 1|]
let dj = [|1; 0; -1; 0|]

let m = read_int()
let n = read_int()
let matrix = Array.make m ""
let _ =
  for i=0 to m-1 do
    matrix.(i) <- read_string()
  done

let c = String.length matrix.(0)

let advance_ptr (i,j,dp,cp) =
  match cp with
    | 1 -> (i,j,dp,0)
    | 0 -> (i,j,(4+dp-1) mod 4,1)
    | _ -> failwith "bad cp"

let advance (i,j,dp,cp) =
  let rec move (di,dj) (i,j) =
    let (ii,jj) = (i+di, j+dj) in
      if ii>=0 && ii<m && jj>=0 && jj<c && matrix.(i).[j] == matrix.(ii).[jj]
       then move (di,dj) (ii,jj) else (i,j)
  in
  let (i,j) = move (di.(dp), dj.(dp)) (i,j) in
  let ndp = (4 + dp + 2*cp - 1) mod 4 in
  let (i,j) = move (di.(ndp), dj.(ndp)) (i,j) in
  let (ii,jj) = (i+di.(dp), j+dj.(dp)) in
    if ii>=0 && ii<m && jj>=0 && jj<c && matrix.(ii).[jj] <> '0'
    then (ii,jj,dp,cp) else advance_ptr (i,j,dp,cp)

let table = Hashtbl.create 10
let get s = try Hashtbl.find table s with Not_found -> 0
let inc s = Hashtbl.replace table s ((get s)+1)

let rec loop s v c =
  if get s = v then (
    inc s;
    loop (advance s) v (c+1)
  ) else (s,c)

let (s,c1) = loop (0,0,0,1) 0 0
let (s,c2) = loop s 1 0

let rec iterate s c =
  if c=0 then s else iterate (advance s) (c-1)

let adv = if n<c1 then n else c1+((n-c1) mod c2)
let (i,j,_,_) = iterate (0,0,0,1) adv
;;

Printf.printf "%c\n" matrix.(i).[j]


Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree.Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal.The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex.

The first line contains a single integer h (2 ≤ h ≤ 105) — the height of the tree. The second line contains h + 1 integers — the sequence a0, a1, ..., ah (1 ≤ ai ≤ 2·105). The sum of all ai does not exceed 2·105. It is guaranteed that there is at least one tree matching this sequence.

If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print  integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence.

NoteThe only tree in the first example and the two printed trees from the second example are shown on the picture:

open Printf
open Scanf

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

let () =
  let h = read_int () in
  let a = Array.init (h+1) read_int in

  if a.(0) <> 1 then failwith "bad tree";

  let rec is_unique i = if i=h then true else
      if a.(i) <> 1 && a.(i+1) <> 1 then false
      else is_unique (i+1)
  in

  if is_unique 0 then printf "perfect\n" else (
    printf "ambiguous\n";

    let rec printtree version nn i = if i<=h then (
      (* i is the level we're about to print.  nn is the node number whose
	 parent we are about to print.  The previous row ended in nn-1 *)
(*      printf "(printing row %d): " i; *)
      if a.(i-1) = 1 then (
	for k=1 to a.(i) do printf "%d " (nn-1) done;
      ) else (
	if version = 0 then (
	  for k=1 to a.(i) do printf "%d " (nn-1) done;
	) else (
	  printf "%d " (nn-1);
	  for k=2 to a.(i) do printf "%d " (nn-2) done;
	)
      );
      printtree version (nn+a.(i)) (i+1)
    )
    in

    printf "0 ";
    printtree 0 2 1;
    print_newline();
    printf "0 ";
    printtree 1 2 1;
    print_newline();
  )


$$$n$$$ heroes fight against each other in the Arena. Initially, the $$$i$$$-th hero has level $$$a_i$$$.Each minute, a fight between two different heroes occurs. These heroes can be chosen arbitrarily (it's even possible that it is the same two heroes that were fighting during the last minute).When two heroes of equal levels fight, nobody wins the fight. When two heroes of different levels fight, the one with the higher level wins, and his level increases by $$$1$$$.The winner of the tournament is the first hero that wins in at least $$$100^{500}$$$ fights (note that it's possible that the tournament lasts forever if no hero wins this number of fights, then there is no winner). A possible winner is a hero such that there exists a sequence of fights that this hero becomes the winner of the tournament.Calculate the number of possible winners among $$$n$$$ heroes.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Each test case consists of two lines. The first line contains one integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of heroes. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$), where $$$a_i$$$ is the initial level of the $$$i$$$-th hero.

For each test case, print one integer — the number of possible winners among the given $$$n$$$ heroes.

NoteIn the first test case of the example, the only possible winner is the first hero.In the second test case of the example, each fight between the heroes results in nobody winning it, so the tournament lasts forever and there is no winner.

module Stdlib = Pervasives

(* let std_in = Stdlib.open_in "input.txt" and std_out = Stdlib.stdout;; *)
let std_in = Stdlib.stdin and std_out = Stdlib.stdout;;

let identity x = x;;

let space_regexp = Str.regexp " ";;

let rec repeat f inp outp n =
  if n <= 0 then ()
  else
    let () = f inp outp in
    repeat f inp outp (n - 1);;

let max a b = if a > b then a else b;;

let rec solve items acc =
  match items, acc with
  | [], acc -> acc
  | head::tail, None -> solve tail (Some (head, 1))
  | head::tail, (Some (value, count) as tmp) ->
    if head < value then solve tail (Some (head, 1))
    else if head = value then solve tail (Some (value, count + 1))
    else solve tail tmp;;

let solution inp outp =
  let n = let line = input_line inp in Scanf.sscanf line "%d" identity in
  let items = input_line inp |> Str.split space_regexp |> List.map int_of_string in
  let result = solve items None in
  let () =
    match result with
    | None -> Printf.fprintf outp "invariant: takogo ne bivaet"
    | Some (_, count) -> Printf.fprintf outp "%d\n"  (n - count)
  in
  ();;

let () =
  let inp = std_in and outp = std_out in
  let tests_count = let line = input_line inp in Scanf.sscanf line "%d" identity in
  let () = repeat solution inp outp tests_count in
  ();;


Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the i-th person is equal to ai.Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?

The first line of the input contains two integers n and h (1 ≤ n ≤ 1000, 1 ≤ h ≤ 1000) — the number of friends and the height of the fence, respectively. The second line contains n integers ai (1 ≤ ai ≤ 2h), the i-th of them is equal to the height of the i-th person.

Print a single integer — the minimum possible valid width of the road.

NoteIn the first sample, only person number 3 must bend down, so the required width is equal to 1 + 1 + 2 = 4.In the second sample, all friends are short enough and no one has to bend, so the width 1 + 1 + 1 + 1 + 1 + 1 = 6 is enough.In the third sample, all the persons have to bend, except the last one. The required minimum width of the road is equal to 2 + 2 + 2 + 2 + 2 + 1 = 11.

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

let input () =
    let total = read () in
    let limit = read () in
    let rec loop heights i =
        if i < total
        then
            let height = Scanf.scanf "%d " (fun h -> h) in
            loop (height :: heights) (i + 1)
        else
            (total, limit, heights)
    in loop [] 0

let solve (total, limit, heights) =
    let double_width = List.length (List.filter (fun n -> n > limit) heights) in
    let single_width = total - double_width in
    let total_width = single_width + 2 * double_width in
    Printf.printf "%d\n" total_width

let () = solve (input ())

open !Scanf
open !Printf

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

let () =
    let n = read_int () in
    let h = read_int () in

    let rec solve n h =
        match n with
        | 0 -> 0
        | _ -> (if read_int () <= h then 1 else 2) + solve (n-1) h

    in printf "%d" (solve n h)

(* Codeforces 677 A VaniaFence *)

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

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

let rec widlist li zh = match li with
| [] -> 0
| h :: t -> (if (h > zh) then 2 else 1) +
	(widlist t zh);;

let main() =
	let n = gr() in
	let h = gr() in
	let a = readlist (n) [] in
	let wid = widlist a h in
	begin
		print_int wid;
		print_string "\n"
	end;;

main();;

let _ =
  let sb = Scanf.Scanning.stdib in
  let n = Scanf.bscanf sb "%d " (fun s -> s) in
  let h = Scanf.bscanf sb "%d " (fun s -> s) in
  let res = ref 0 in
    for i = 1 to n do
      let x = Scanf.bscanf sb "%d " (fun s -> s) in
	if x > h
	then res := !res + 2
	else res := !res + 1;
    done;
    Printf.printf "%d\n" !res

let scan_int () = Scanf.scanf " %d" (fun x -> x) in
let n = scan_int () in
let h = scan_int () in

let rec read_n_ints n =
        if n = 0 then []
        else (scan_int ()) :: (read_n_ints (n-1)) in

let l = read_n_ints n in

Printf.printf "%d\n" (n + (List.length (List.filter (fun hh -> hh > h) l)))

open Printf
open Scanf

let rec sum i j f ac = if i>j then ac else sum (i+1) j f (ac + (f i))

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

  let answer = sum 1 n (
    fun _ -> let y = read_int() in
	     if y > h then 2 else 1
  ) 0 in

  printf "%d\n" answer


You are given two sequences $$$a_1, a_2, \dots, a_n$$$ and $$$b_1, b_2, \dots, b_n$$$. Each element of both sequences is either $$$0$$$, $$$1$$$ or $$$2$$$. The number of elements $$$0$$$, $$$1$$$, $$$2$$$ in the sequence $$$a$$$ is $$$x_1$$$, $$$y_1$$$, $$$z_1$$$ respectively, and the number of elements $$$0$$$, $$$1$$$, $$$2$$$ in the sequence $$$b$$$ is $$$x_2$$$, $$$y_2$$$, $$$z_2$$$ respectively.You can rearrange the elements in both sequences $$$a$$$ and $$$b$$$ however you like. After that, let's define a sequence $$$c$$$ as follows:$$$c_i = \begin{cases} a_i b_i & \mbox{if }a_i > b_i \\ 0 & \mbox{if }a_i = b_i \\ -a_i b_i & \mbox{if }a_i < b_i \end{cases}$$$You'd like to make $$$\sum_{i=1}^n c_i$$$ (the sum of all elements of the sequence $$$c$$$) as large as possible. What is the maximum possible sum?

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains three integers $$$x_1$$$, $$$y_1$$$, $$$z_1$$$ ($$$0 \le x_1, y_1, z_1 \le 10^8$$$) — the number of $$$0$$$-s, $$$1$$$-s and $$$2$$$-s in the sequence $$$a$$$. The second line of each test case also contains three integers $$$x_2$$$, $$$y_2$$$, $$$z_2$$$ ($$$0 \le x_2, y_2, z_2 \le 10^8$$$; $$$x_1 + y_1 + z_1 = x_2 + y_2 + z_2 > 0$$$) — the number of $$$0$$$-s, $$$1$$$-s and $$$2$$$-s in the sequence $$$b$$$.

For each test case, print the maximum possible sum of the sequence $$$c$$$.

(* Codeforces 1352 0 Sum of Round Numbers comp   *)

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

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

let min_sum2 a1 b1 a2 b2 =
	(* let _ = Printf.printf "b1,b2 = %d %d\n" b1 b2 in *)
	if b2 > b1 then
		(-2) * (b2 - b1)
	else
		0;;

let max_sum3 x1 y1 z1 x2 y2 z2 =
		if z1 > y2 then
			let sm = 2*y2 in
			(* let _ = Printf.printf "sm1 = %d\n" sm in *)
			let zz1 = z1 - y2 in
			let yy2 = 0 in
			let a1 = y1 in
			let b1 = x1 + zz1 in
			let a2 = x2 + yy2 in
			let b2 = z2 in
			(sm + min_sum2 a1 b1 a2 b2)
		else
			let sm = 2*z1 in
      (* let _ = Printf.printf "sm2 = %d\n" sm in *)
			let zz1 = 0 in
			let yy2 = y2 - z1 in
			let a1 = y1 in
			let b1 = x1 + zz1 in
			let a2 = x2 + yy2 in
			let b2 = z2 in
			(sm + min_sum2 a1 b1 a2 b2);;

let do_one () =
    let z1,y1,x1 = gr(),gr(),gr() in
    let z2,y2,x2 = gr(),gr(),gr() in
		let max_sum = max_sum3 x1 y1 z1 x2 y2 z2 in
		begin
			print_int max_sum;
			print_string "\n"
		end;;

let do_all t =
    for i = 1 to t do
        do_one ()
    done;;

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

main();;

(* Codeforces 1005 A Tanya and Stairways done *)

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

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

let rec to_tania acc last l = match l with
	| [] -> last :: acc
	| h :: t -> match h with
			| 1 ->
				let lacc = if last == 0 then acc else last :: acc in
				to_tania lacc 1 t
			| _ -> to_tania acc h t;;

let main() =
	let n = gr () in
	let ra = readlist n [] in
	let a = List.rev ra in
	let ro = to_tania [] 0 a in
	let o = List.rev ro in
	let lno = List.length o in
	begin
		print_int lno;
		print_string "\n";
		printlisti o;
		print_string "\n"
	end;;

main();;


In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substring of ABCDEF.You are given two strings s1, s2 and another string called virus. Your task is to find the longest common subsequence of s1 and s2, such that it doesn't contain virus as a substring.

The input contains three strings in three separate lines: s1, s2 and virus (1 ≤ |s1|, |s2|, |virus| ≤ 100). Each string consists only of uppercase English letters.

Output the longest common subsequence of s1 and s2 without virus as a substring. If there are multiple answers, any of them will be accepted.  If there is no valid common subsequence, output 0.

open Scanf;;
open String;;
open List;;
open Str;;

let (s1,s2,virus) = Scanf.bscanf Scanf.Scanning.stdin "%s %s %s "
    (fun x y z  ->  (x,y,z) ) ;;

let vl = String.length virus;;

let n = String.length s1;;
let  m = String.length s2;;
let a = Array.make_matrix (n+1) (m+1) [];;

type sList = string list;;
let print_sList rl = (*iter (fun x -> print_string x; print_string "
                       ")  rl;;*)
  match rl with
    [] -> print_endline "0"
  |hd :: _ -> print_string hd; print_endline ""
;;

(*If string s1 contains string s2*)
let re = Str.regexp_string virus;;

let contains x =
  try ignore (Str.search_forward re x 0); true
  with Not_found -> false
;;

(*Make sure a list contains unique elements*)
let rec uniq x =
  let rec uniq_help l n =
    match l with
    | [] -> []
    | h :: t -> if n = h then uniq_help t n else h::(uniq_help t n) in
  match x with
  | [] -> []
  | h::t -> h::(uniq_help (uniq t) h)
;;

let sList_merge c  i j  =
   (*print_string cs; print_string " "; print_sList sL; print_endline "";
    print_sList ( List.map (fun x -> cs^x) sL );*)
  begin
    let sL = a.(i).(j) in
      match sL with
        |[] ->  if not (contains c) then [c] else []
        |_ -> let rslt =  List.map (fun x -> c^x) sL in
        let rslt2 = List.filter (fun x -> not (contains x) ) rslt in
          match rslt2 with
            [] ->List.filter (fun x -> not (contains x) ) (
              uniq(List.append
                     (List.append
                      (List.map (fun x -> c^x) a. (i+1).(j))
                      (List.map (fun x -> c^x) a. (i).(j+1))
                     )
                     a.(i).(j)
                   )
            )
        |_ ->rslt2
  end
;;

let sList_merge2 sL1 sL2 = match sL1, sL2 with
  |([],[]) -> []
  |([],  x) -> x
  |( x, []) -> x
  |(x, y) ->
    begin
      let xl =  String.length (List.hd x)  in
      let yl = String.length (List.hd y) in
      if xl > yl then
        x
      else if xl < yl then
        y
      else uniq ( List.append x y )
    end
;;

(*Find the LCS, record them all*)
let lcs contains =
  for i = n-1 downto 0 do
    for j = m-1 downto 0 do
      a.(i).(j) <- if (String.get s1  i) = (String.get  s2 j) then
          let cs = String.sub s1 i 1 in
          sList_merge  cs  (i+1) (j+1)
        else
          sList_merge2  a.(i).(j+1) a.(i+1).(j)
    done
  done;
  a.(0).(0)
;;

let longest xs ys = if List.length xs > List.length ys then xs else
    ys;;

let lcs2 xs' ys' =
  let xs = Array.of_list xs'
  and ys = Array.of_list ys' in
  let n = Array.length xs
  and m = Array.length ys in
  let a = Array.make_matrix (n+1) (m+1) [] in
  for i = n-1 downto 0 do
    for j = m-1 downto 0 do
      a.(i).(j) <- if xs.(i) = ys.(j) then
          xs.(i) :: a.(i+1).(j+1)
        else
          longest a.(i).(j+1) a.(i+1).(j)
    done
  done;
  a.(0).(0);;

let list_of_string str =
  let result = ref [] in
  String.iter (fun x -> result := x :: !result)
    str;
  List.rev !result;;

let string_of_list lst =
  let result = String.create (List.length lst) in
  ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst);  result
;;

let remove_char x r =
    if r = 0 then
     String.sub x 1 ((String.length x) -1)
    else
      (String.sub x 0 r)^(String.sub x (r+1)
                                   ((String.length x) - r-1))
;;

let rec return_longest xl =
  match xl with
    [] -> ""
  |hd :: tl ->let xxl = return_longest tl in
    if (String.length hd )> (String.length xxl) then
      hd
    else xxl
;;

let rec remove x =
  try
    let r = Str.search_forward re x 0 in
    let basket = ref [] in
    for i = 0 to vl - 1 do
      let newx = remove_char x (r+i) in
      basket := List.append !basket [(remove newx)]
    done;
    return_longest !basket
  with Not_found -> x
;;

if s1=s2 then
  begin
    print_string (remove s1); print_endline ""
  end
else
  begin
    let s =string_of_list ( lcs2 (list_of_string s1) (list_of_string s2))
    in
    if  not (contains s) then
      begin
        print_string s; print_endline "";
      end
    else
      let rslt = lcs contains in
      print_sList rslt
  end

open Scanf;;
open String;;
open List;;
open Char;;
open Str;;

type sList = string list;;
let print_sList rl = (*iter (fun x -> print_string x; print_string "
                       ")  rl;;*)
  match rl with
    [] -> print_endline "0"
  |hd :: _ -> print_string hd; print_endline ""
;;

(*Make sure a list contains unique elements*)
let rec uniq x =
  let rec uniq_help l n =
    match l with
    | [] -> []
    | h :: t -> if n = h then uniq_help t n else h::(uniq_help t n) in
  match x with
  | [] -> []
  | h::t -> h::(uniq_help (uniq t) h)
;;

let sList_merge c sL contains =
   (*print_string cs; print_string " "; print_sList sL; print_endline "";
    print_sList ( List.map (fun x -> cs^x) sL );*)
  match sL with
    |[] ->  if not (contains c) then [c] else []
    |_ -> let rslt =  List.map (fun x -> c^x) sL in
          let rslt2 = List.filter (fun x -> not (contains x) ) rslt in
          match rslt2 with
            [] -> List.append sL (List.map
                                    (fun x -> c^(String.sub  x 1
                                                   ((String.length x) -1)))
                                    sL)
          |_ ->rslt2
;;

let sList_merge2 sL1 sL2 = match sL1, sL2 with
  |([],[]) -> []
  |([],  x) -> x
  |( x, []) -> x
  |(x, y) ->
    begin
      let xl =  String.length (List.hd x)  in
      let yl = String.length (List.hd y) in
      if xl > yl then
        x
      else if xl < yl then
        y
      else uniq ( List.append x y )
    end
;;

(*Find the LCS, record them all*)
let lcs xs ys contains =
  let n = String.length xs
  and m = String.length ys in
  let a = Array.make_matrix (n+1) (m+1) [] in
  for i = n-1 downto 0 do
    for j = m-1 downto 0 do
      a.(i).(j) <- if (String.get xs  i) = (String.get  ys j) then
          let cs = String.sub xs i 1 in
            sList_merge  cs  a.(i+1).(j+1)  contains
        else
          sList_merge2  a.(i).(j+1) a.(i+1).(j)
    done
  done;
  a.(0).(0)
;;

let longest xs ys = if List.length xs > List.length ys then xs else
    ys;;

let lcs2 xs' ys' =
  let xs = Array.of_list xs'
  and ys = Array.of_list ys' in
  let n = Array.length xs
  and m = Array.length ys in
  let a = Array.make_matrix (n+1) (m+1) [] in
  for i = n-1 downto 0 do
    for j = m-1 downto 0 do
      a.(i).(j) <- if xs.(i) = ys.(j) then
          xs.(i) :: a.(i+1).(j+1)
        else
          longest a.(i).(j+1) a.(i+1).(j)
    done
  done;
  a.(0).(0);;

let list_of_string str =
  let result = ref [] in
  String.iter (fun x -> result := x :: !result)
    str;
  List.rev !result;;

let string_of_list lst =
  let result = String.create (List.length lst) in
  ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst);  result
;;

let (s1,s2,virus) = Scanf.bscanf Scanf.Scanning.stdin "%s %s %s "
    (fun x y z  ->  (x,y,z) )  in
let s =string_of_list ( lcs2 (list_of_string s1) (list_of_string s2))
in
(*If string s1 contains string s2*)
let re = Str.regexp_string virus in
let contains x =
  try ignore (Str.search_forward re x 0); true
  with Not_found -> false
in
if  not (contains s) then
  begin
    print_string s; print_endline "";
  end
else
  let rslt = lcs s1 s2 contains in
  print_sList rslt;;

open Scanf;;
open String;;
open List;;
open Str;;

let (s1,s2,virus) = Scanf.bscanf Scanf.Scanning.stdin "%s %s %s "
    (fun x y z  ->  (x,y,z) ) ;;

let n = String.length s1;;
let  m = String.length s2;;
let a = Array.make_matrix (n+1) (m+1) [];;

type sList = string list;;
let print_sList rl = (*iter (fun x -> print_string x; print_string "
                       ")  rl;;*)
  match rl with
    [] -> print_endline "0"
  |hd :: _ -> print_string hd; print_endline ""
;;

(*Make sure a list contains unique elements*)
let rec uniq x =
  let rec uniq_help l n =
    match l with
    | [] -> []
    | h :: t -> if n = h then uniq_help t n else h::(uniq_help t n) in
  match x with
  | [] -> []
  | h::t -> h::(uniq_help (uniq t) h)
;;

let sList_merge c sL contains =
   (*print_string cs; print_string " "; print_sList sL; print_endline "";
    print_sList ( List.map (fun x -> cs^x) sL );*)
  match sL with
    |[] ->  if not (contains c) then [c] else []
    |_ -> let rslt =  List.map (fun x -> c^x) sL in
          let rslt2 = List.filter (fun x -> not (contains x) ) rslt in
          match rslt2 with
            [] -> List.append sL (List.map
                                    (fun x -> c^(String.sub  x 1
                                                   ((String.length x) -1)))
                                    sL)
          |_ ->rslt2
;;

let sList_merge2 sL1 sL2 = match sL1, sL2 with
  |([],[]) -> []
  |([],  x) -> x
  |( x, []) -> x
  |(x, y) ->
    begin
      let xl =  String.length (List.hd x)  in
      let yl = String.length (List.hd y) in
      if xl > yl then
        x
      else if xl < yl then
        y
      else uniq ( List.append x y )
    end
;;

(*Find the LCS, record them all*)
let lcs contains =
  for i = n-1 downto 0 do
    for j = m-1 downto 0 do
      a.(i).(j) <- if (String.get s1  i) = (String.get  s2 j) then
          let cs = String.sub s1 i 1 in
            sList_merge  cs  a.(i+1).(j+1)  contains
        else
          sList_merge2  a.(i).(j+1) a.(i+1).(j)
    done
  done;
  a.(0).(0)
;;

let longest xs ys = if List.length xs > List.length ys then xs else
    ys;;

let lcs2 xs' ys' =
  let xs = Array.of_list xs'
  and ys = Array.of_list ys' in
  let n = Array.length xs
  and m = Array.length ys in
  let a = Array.make_matrix (n+1) (m+1) [] in
  for i = n-1 downto 0 do
    for j = m-1 downto 0 do
      a.(i).(j) <- if xs.(i) = ys.(j) then
          xs.(i) :: a.(i+1).(j+1)
        else
          longest a.(i).(j+1) a.(i+1).(j)
    done
  done;
  a.(0).(0);;

let list_of_string str =
  let result = ref [] in
  String.iter (fun x -> result := x :: !result)
    str;
  List.rev !result;;

let string_of_list lst =
  let result = String.create (List.length lst) in
  ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst);  result
;;

let s =string_of_list ( lcs2 (list_of_string s1) (list_of_string s2))
in
(*If string s1 contains string s2*)
let re = Str.regexp_string virus in
let contains x =
  try ignore (Str.search_forward re x 0); true
  with Not_found -> false
in
if  not (contains s) then
  begin
    print_string s; print_endline "";
  end
else
  let rslt = lcs contains in
  print_sList rslt;;

open Scanf;;
open String;;
open List;;
open Char;;
open Str;;

type sList = string list;;
let print_sList rl = (*iter (fun x -> print_string x; print_string "
                       ")  rl;;*)
  match rl with
    [] -> print_endline "0"
  |hd :: _ -> print_string hd; print_endline ""
;;

(*Make sure a list contains unique elements*)
let rec uniq x =
  let rec uniq_help l n =
    match l with
    | [] -> []
    | h :: t -> if n = h then uniq_help t n else h::(uniq_help t n) in
  match x with
  | [] -> []
  | h::t -> h::(uniq_help (uniq t) h)
;;

let sList_merge c sL contains =
   (*print_string cs; print_string " "; print_sList sL; print_endline "";
    print_sList ( List.map (fun x -> cs^x) sL );*)
  match sL with
    |[] ->  if not (contains c) then [c] else []
  |_ -> List.filter (fun x -> not (contains x) ) (List.map (fun x -> c^x) sL)
;;

let sList_merge2 sL1 sL2 = match sL1, sL2 with
  |([],[]) -> []
  |([],  x) -> x
  |( x, []) -> x
  |(x, y) ->
    begin
      let xl =  String.length (List.hd x)  in
      let yl = String.length (List.hd y) in
      if xl > yl then
        x
      else if xl < yl then
        y
      else uniq ( List.append x y )
    end
;;

(*Find the LCS, record them all*)
let lcs xs ys contains =
  let n = String.length xs
  and m = String.length ys in
  let a = Array.make_matrix (n+1) (m+1) [] in
  for i = n-1 downto 0 do
    for j = m-1 downto 0 do
      a.(i).(j) <- if (String.get xs  i) = (String.get  ys j) then
          let rslt =  sList_merge  (String.sub xs i 1)  a.(i+1).(j+1)
            contains in
          match rslt with
            []-> a.(i+1).(j+1)
          | _-> rslt
        else
          sList_merge2  a.(i).(j+1) a.(i+1).(j)
    done
  done;
  a.(0).(0)
;;

let longest xs ys = if List.length xs > List.length ys then xs else
    ys;;

let lcs2 xs' ys' =
  let xs = Array.of_list xs'
  and ys = Array.of_list ys' in
  let n = Array.length xs
  and m = Array.length ys in
  let a = Array.make_matrix (n+1) (m+1) [] in
  for i = n-1 downto 0 do
    for j = m-1 downto 0 do
      a.(i).(j) <- if xs.(i) = ys.(j) then
          xs.(i) :: a.(i+1).(j+1)
        else
          longest a.(i).(j+1) a.(i+1).(j)
    done
  done;
  a.(0).(0);;

let list_of_string str =
  let result = ref [] in
  String.iter (fun x -> result := x :: !result)
    str;
  List.rev !result;;

let string_of_list lst =
  let result = String.create (List.length lst) in
  ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst);  result
;;

let (s1,s2,virus) = Scanf.bscanf Scanf.Scanning.stdin "%s %s %s "
    (fun x y z  ->  (x,y,z) )  in
let s =string_of_list ( lcs2 (list_of_string s1) (list_of_string s2))
in
(*If string s1 contains string s2*)
let re = Str.regexp_string virus in
let contains x =
  try ignore (Str.search_forward re x 0); true
  with Not_found -> false
in
if  not (contains s) then
  begin
    print_string s; print_endline "";
  end
else
  let rslt = lcs s1 s2 contains in
  print_sList rslt;;

open Scanf;;
open String;;
open List;;
open Char;;
open Str;;

type sList = string list;;
let print_sList rl = (*iter (fun x -> print_string x; print_string "
                       ")  rl;;*)
  match rl with
    [] -> print_endline "0"
  |hd :: _ -> print_string hd; print_endline ""
;;

(*Make sure a list contains unique elements*)
let rec uniq x =
  let rec uniq_help l n =
    match l with
    | [] -> []
    | h :: t -> if n = h then uniq_help t n else h::(uniq_help t n) in
  match x with
  | [] -> []
  | h::t -> h::(uniq_help (uniq t) h)
;;

let sList_merge c sL contains =
   (*print_string cs; print_string " "; print_sList sL; print_endline "";
    print_sList ( List.map (fun x -> cs^x) sL );*)
  match sL with
    |[] ->  if not (contains c) then [c] else []
  |_ -> List.filter (fun x -> not (contains x) ) (List.map (fun x -> c^x) sL)
;;

let sList_merge2 sL1 sL2 = match sL1, sL2 with
  |([],[]) -> []
  |([],  x) -> x
  |( x, []) -> x
  |(x, y) ->
    begin
      let xl =  String.length (List.hd x)  in
      let yl = String.length (List.hd y) in
      if xl > yl then
        x
      else if xl < yl then
        y
      else uniq ( List.append x y )
    end
;;

(*Find the LCS, record them all*)
let lcs xs ys contains =
  let n = String.length xs
  and m = String.length ys in
  let a = Array.make_matrix (n+1) (m+1) [] in
  for i = n-1 downto 0 do
    for j = m-1 downto 0 do
      a.(i).(j) <- if (String.get xs  i) = (String.get  ys j) then
          sList_merge  (String.sub xs i 1)  a.(i+1).(j+1) contains
        else
          sList_merge2  a.(i).(j+1) a.(i+1).(j)
    done
  done;
  a.(0).(0)
;;

let longest xs ys = if List.length xs > List.length ys then xs else
    ys;;

let lcs2 xs' ys' =
  let xs = Array.of_list xs'
  and ys = Array.of_list ys' in
  let n = Array.length xs
  and m = Array.length ys in
  let a = Array.make_matrix (n+1) (m+1) [] in
  for i = n-1 downto 0 do
    for j = m-1 downto 0 do
      a.(i).(j) <- if xs.(i) = ys.(j) then
          xs.(i) :: a.(i+1).(j+1)
        else
          longest a.(i).(j+1) a.(i+1).(j)
    done
  done;
  a.(0).(0);;

let list_of_string str =
  let result = ref [] in
  String.iter (fun x -> result := x :: !result)
    str;
  List.rev !result;;

let string_of_list lst =
  let result = String.create (List.length lst) in
  ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst);  result
;;

let (s1,s2,virus) = Scanf.bscanf Scanf.Scanning.stdin "%s %s %s "
    (fun x y z  ->  (x,y,z) )  in
let s =string_of_list ( lcs2 (list_of_string s1) (list_of_string s2))
in
(*If string s1 contains string s2*)
let re = Str.regexp_string virus in
let contains x =
  try ignore (Str.search_forward re x 0); true
  with Not_found -> false
in
if  not (contains s) then
  begin
    print_string s; print_endline "";
  end
else
  let rslt = lcs s1 s2 contains in
  print_sList rslt;;

open Scanf;;
open String;;
open List;;
open Str;;

let (s1,s2,virus) = Scanf.bscanf Scanf.Scanning.stdin "%s %s %s "
    (fun x y z  ->  (x,y,z) ) ;;

let n = String.length s1;;
let  m = String.length s2;;
let a = Array.make_matrix (n+1) (m+1) [];;

type sList = string list;;
let print_sList rl = (*iter (fun x -> print_string x; print_string "
                       ")  rl;;*)
  match rl with
    [] -> print_endline "0"
  |hd :: _ -> print_string hd; print_endline ""
;;

(*If string s1 contains string s2*)
let re = Str.regexp_string virus;;

let contains x =
  try ignore (Str.search_forward re x 0); true
  with Not_found -> false
;;

(*Make sure a list contains unique elements*)
let rec uniq x =
  let rec uniq_help l n =
    match l with
    | [] -> []
    | h :: t -> if n = h then uniq_help t n else h::(uniq_help t n) in
  match x with
  | [] -> []
  | h::t -> h::(uniq_help (uniq t) h)
;;

let sList_merge c  i j  =
   (*print_string cs; print_string " "; print_sList sL; print_endline "";
    print_sList ( List.map (fun x -> cs^x) sL );*)
  begin
    let sL = a.(i).(j) in
      match sL with
        |[] ->  if not (contains c) then [c] else []
        |_ -> let rslt =  List.map (fun x -> c^x) sL in
        let rslt2 = List.filter (fun x -> not (contains x) ) rslt in
          match rslt2 with
            [] ->List.filter (fun x -> not (contains x) ) (
              uniq(List.append
                     (List.append
                      (List.map (fun x -> c^x) a. (i+1).(j))
                      (List.map (fun x -> c^x) a. (i).(j+1))
                     )
                     a.(i).(j)
                   )
            )
        |_ ->rslt2
  end
;;

let sList_merge2 sL1 sL2 = match sL1, sL2 with
  |([],[]) -> []
  |([],  x) -> x
  |( x, []) -> x
  |(x, y) ->
    begin
      let xl =  String.length (List.hd x)  in
      let yl = String.length (List.hd y) in
      if xl > yl then
        x
      else if xl < yl then
        y
      else uniq ( List.append x y )
    end
;;

(*Find the LCS, record them all*)
let lcs contains =
  for i = n-1 downto 0 do
    for j = m-1 downto 0 do
      a.(i).(j) <- if (String.get s1  i) = (String.get  s2 j) then
          let cs = String.sub s1 i 1 in
          sList_merge  cs  (i+1) (j+1)
        else
          sList_merge2  a.(i).(j+1) a.(i+1).(j)
    done
  done;
  a.(0).(0)
;;

let longest xs ys = if List.length xs > List.length ys then xs else
    ys;;

let lcs2 xs' ys' =
  let xs = Array.of_list xs'
  and ys = Array.of_list ys' in
  let n = Array.length xs
  and m = Array.length ys in
  let a = Array.make_matrix (n+1) (m+1) [] in
  for i = n-1 downto 0 do
    for j = m-1 downto 0 do
      a.(i).(j) <- if xs.(i) = ys.(j) then
          xs.(i) :: a.(i+1).(j+1)
        else
          longest a.(i).(j+1) a.(i+1).(j)
    done
  done;
  a.(0).(0);;

let list_of_string str =
  let result = ref [] in
  String.iter (fun x -> result := x :: !result)
    str;
  List.rev !result;;

let string_of_list lst =
  let result = String.create (List.length lst) in
  ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst);  result
;;

let rec remove x =
  try
    let r = Str.search_forward re x 0 in
    match r with
    | 0 -> remove (String.sub x 1 ((String.length x) -1))
    | a when a >0  -> remove (String.sub x 0 a)^(String.sub x (a+1)
                                                   ((String.length x) - a -1))
  with Not_found -> x
;;

if s1=s2 then
  begin
    print_string (remove s1); print_endline ""
  end
else
  begin
    let s =string_of_list ( lcs2 (list_of_string s1) (list_of_string s2))
    in
    if  not (contains s) then
      begin
        print_string s; print_endline "";
      end
    else
      let rslt = lcs contains in
      print_sList rslt
  end

open Scanf;;
open String;;
open List;;
open Str;;

let (s1,s2,virus) = Scanf.bscanf Scanf.Scanning.stdin "%s %s %s "
    (fun x y z  ->  (x,y,z) ) ;;

let n = String.length s1;;
let  m = String.length s2;;
let a = Array.make_matrix (n+1) (m+1) [];;

type sList = string list;;
let print_sList rl = (*iter (fun x -> print_string x; print_string "
                       ")  rl;;*)
  match rl with
    [] -> print_endline "0"
  |hd :: _ -> print_string hd; print_endline ""
;;

(*If string s1 contains string s2*)
let re = Str.regexp_string virus;;

let contains x =
  try ignore (Str.search_forward re x 0); true
  with Not_found -> false
;;

(*Make sure a list contains unique elements*)
let rec uniq x =
  let rec uniq_help l n =
    match l with
    | [] -> []
    | h :: t -> if n = h then uniq_help t n else h::(uniq_help t n) in
  match x with
  | [] -> []
  | h::t -> h::(uniq_help (uniq t) h)
;;

let sList_merge c  i j  =
   (*print_string cs; print_string " "; print_sList sL; print_endline "";
    print_sList ( List.map (fun x -> cs^x) sL );*)
  begin
    let sL = a.(i).(j) in
      match sL with
        |[] ->  if not (contains c) then [c] else []
        |_ -> let rslt =  List.map (fun x -> c^x) sL in
        let rslt2 = List.filter (fun x -> not (contains x) ) rslt in
          match rslt2 with
            [] ->List.filter (fun x -> not (contains x) ) (
              uniq(List.append
                     (List.append
                      (List.map (fun x -> c^x) a. (i+1).(j))
                      (List.map (fun x -> c^x) a. (i).(j+1))
                     )
                     a.(i).(j)
                   )
            )
        |_ ->rslt2
  end
;;

let sList_merge2 sL1 sL2 = match sL1, sL2 with
  |([],[]) -> []
  |([],  x) -> x
  |( x, []) -> x
  |(x, y) ->
    begin
      let xl =  String.length (List.hd x)  in
      let yl = String.length (List.hd y) in
      if xl > yl then
        x
      else if xl < yl then
        y
      else uniq ( List.append x y )
    end
;;

(*Find the LCS, record them all*)
let lcs contains =
  for i = n-1 downto 0 do
    for j = m-1 downto 0 do
      a.(i).(j) <- if (String.get s1  i) = (String.get  s2 j) then
          let cs = String.sub s1 i 1 in
          sList_merge  cs  (i+1) (j+1)
        else
          sList_merge2  a.(i).(j+1) a.(i+1).(j)
    done
  done;
  a.(0).(0)
;;

let longest xs ys = if List.length xs > List.length ys then xs else
    ys;;

let lcs2 xs' ys' =
  let xs = Array.of_list xs'
  and ys = Array.of_list ys' in
  let n = Array.length xs
  and m = Array.length ys in
  let a = Array.make_matrix (n+1) (m+1) [] in
  for i = n-1 downto 0 do
    for j = m-1 downto 0 do
      a.(i).(j) <- if xs.(i) = ys.(j) then
          xs.(i) :: a.(i+1).(j+1)
        else
          longest a.(i).(j+1) a.(i+1).(j)
    done
  done;
  a.(0).(0);;

let list_of_string str =
  let result = ref [] in
  String.iter (fun x -> result := x :: !result)
    str;
  List.rev !result;;

let string_of_list lst =
  let result = String.create (List.length lst) in
  ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst);  result
;;

let rec remove x =
  try
    let r = Str.search_forward re x 0 in
    if r = 0 then
      remove (String.sub x 1 ((String.length x) -1))
    else
      remove ( (String.sub x 0 r)^(String.sub x (r+1)
                                   ((String.length x) - r-1)) )
  with Not_found -> x
;;

if s1=s2 then
  begin
    print_string (remove s1); print_endline ""
  end
else
  begin
    let s =string_of_list ( lcs2 (list_of_string s1) (list_of_string s2))
    in
    if  not (contains s) then
      begin
        print_string s; print_endline "";
      end
    else
      let rslt = lcs contains in
      print_sList rslt
  end

open Scanf;;
open String;;
open List;;
open Str;;

let (s1,s2,virus) = Scanf.bscanf Scanf.Scanning.stdin "%s %s %s "
    (fun x y z  ->  (x,y,z) ) ;;

let n = String.length s1;;
let  m = String.length s2;;
let a = Array.make_matrix (n+1) (m+1) [];;

type sList = string list;;
let print_sList rl = (*iter (fun x -> print_string x; print_string "
                       ")  rl;;*)
  match rl with
    [] -> print_endline "0"
  |hd :: _ -> print_string hd; print_endline ""
;;

(*If string s1 contains string s2*)
let re = Str.regexp_string virus;;

let contains x =
  try ignore (Str.search_forward re x 0); true
  with Not_found -> false
;;

(*Make sure a list contains unique elements*)
let rec uniq x =
  let rec uniq_help l n =
    match l with
    | [] -> []
    | h :: t -> if n = h then uniq_help t n else h::(uniq_help t n) in
  match x with
  | [] -> []
  | h::t -> h::(uniq_help (uniq t) h)
;;

let sList_merge c  i j  =
   (*print_string cs; print_string " "; print_sList sL; print_endline "";
    print_sList ( List.map (fun x -> cs^x) sL );*)
  begin
    let sL = a.(i).(j) in
      match sL with
        |[] ->  if not (contains c) then [c] else []
        |_ -> let rslt =  List.map (fun x -> c^x) sL in
        let rslt2 = List.filter (fun x -> not (contains x) ) rslt in
          match rslt2 with
            [] ->List.filter (fun x -> not (contains x) ) (
              uniq(List.append
                     (List.append
                      (List.map (fun x -> c^x) a. (i+1).(j))
                      (List.map (fun x -> c^x) a. (i).(j+1))
                     )
                     a.(i).(j)
                   )
            )
        |_ ->rslt2
  end
;;

let sList_merge2 sL1 sL2 = match sL1, sL2 with
  |([],[]) -> []
  |([],  x) -> x
  |( x, []) -> x
  |(x, y) ->
    begin
      let xl =  String.length (List.hd x)  in
      let yl = String.length (List.hd y) in
      if xl > yl then
        x
      else if xl < yl then
        y
      else uniq ( List.append x y )
    end
;;

(*Find the LCS, record them all*)
let lcs contains =
  for i = n-1 downto 0 do
    for j = m-1 downto 0 do
      a.(i).(j) <- if (String.get s1  i) = (String.get  s2 j) then
          let cs = String.sub s1 i 1 in
          sList_merge  cs  (i+1) (j+1)
        else
          sList_merge2  a.(i).(j+1) a.(i+1).(j)
    done
  done;
  a.(0).(0)
;;

let longest xs ys = if List.length xs > List.length ys then xs else
    ys;;

let lcs2 xs' ys' =
  let xs = Array.of_list xs'
  and ys = Array.of_list ys' in
  let n = Array.length xs
  and m = Array.length ys in
  let a = Array.make_matrix (n+1) (m+1) [] in
  for i = n-1 downto 0 do
    for j = m-1 downto 0 do
      a.(i).(j) <- if xs.(i) = ys.(j) then
          xs.(i) :: a.(i+1).(j+1)
        else
          longest a.(i).(j+1) a.(i+1).(j)
    done
  done;
  a.(0).(0);;

let list_of_string str =
  let result = ref [] in
  String.iter (fun x -> result := x :: !result)
    str;
  List.rev !result;;

let string_of_list lst =
  let result = String.create (List.length lst) in
  ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst);  result
;;

let s =string_of_list ( lcs2 (list_of_string s1) (list_of_string s2))
in
if  not (contains s) then
  begin
    print_string s; print_endline "";
  end
else
  let rslt = lcs contains in
  print_sList rslt;;


Mike and some bears are playing a game just for fun. Mike is the judge. All bears except Mike are standing in an n × m grid, there's exactly one bear in each cell. We denote the bear standing in column number j of row number i by (i, j). Mike's hands are on his ears (since he's the judge) and each bear standing in the grid has hands either on his mouth or his eyes.  They play for q rounds. In each round, Mike chooses a bear (i, j) and tells him to change his state i. e. if his hands are on his mouth, then he'll put his hands on his eyes or he'll put his hands on his mouth otherwise. After that, Mike wants to know the score of the bears.Score of the bears is the maximum over all rows of number of consecutive bears with hands on their eyes in that row.Since bears are lazy, Mike asked you for help. For each round, tell him the score of these bears after changing the state of a bear selected in that round.

The first line of input contains three integers n, m and q (1 ≤ n, m ≤ 500 and 1 ≤ q ≤ 5000). The next n lines contain the grid description. There are m integers separated by spaces in each line. Each of these numbers is either 0 (for mouth) or 1 (for eyes). The next q lines contain the information about the rounds. Each of them contains two integers i and j (1 ≤ i ≤ n and 1 ≤ j ≤ m), the row number and the column number of the bear changing his state.

After each round, print the current score of the bears.

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

let judge_line l =
  let n = Array.length l in
  let rec ju i c m =
    if i = n then m
    else
      if l.(i) = 0 then ju (i+1) 0 (max c m)
      else ju (i+1) (c+1) (max (c+1) m)
  in
  ju 0 0 0

let _ =
  let n = read_int () in
  let m = read_int () in
  let q = read_int () in
  let a = Array.init n (fun _ -> Array.init m (fun _ -> read_int ())) in
  let s = Array.init n (fun i -> judge_line a.(i)) in
  for i = 1 to q do
    let u = read_int () - 1 in
    let v = read_int () - 1 in
    a.(u).(v) <- 1-a.(u).(v);
    s.(u) <- judge_line a.(u);
    Printf.printf "%d\n" (Array.fold_left max 0 s)
  done